String Method To Return A Double
Jul 11, 2014
I'm having an issue with figuring out how to structure and call a method using a string prompt. My prof has given us specific methods to create, and the one I'm having issues with is blic static double getOperand(String prompt). What I have currently is this:
public static double getOperand(String operand1, String operand2){
Scanner input = new Scanner(System.in);
System.out.println("What is the first operand?");
operand1 = input.toString();
System.out.println("What is the second operand?");
operand2 = input.toString();
return operand1, operand2;
}
which is obviously not working. When I asked my prof he sent me this, "The String paramater in the getOperand() method is intended to have the prompt value that is passed to it. Within the method, the prompt is then displayed, what the prompt is asking for is input, and then returned to the method call.For example, if the method is public double getOperand(String prompt) within the method you would display the prompt, as in System. out. println(prompt), use the Scanner class to create an object, perhaps called input, and then use the input object to get the value asked for by the prompt. Once you have that value, which in this example would be a double, then return the value to the method that called it.
The call could be something like this: double value = getOperand("What is the first operand?");". But that only works a little. Clearly I'm missing something and no matter what I google, or how many times I read the chapter, I am just not getting this. Everything else up to this point has been easy. and I can create regular methods just fine, the menu method works, but I can't figure out this string method and all the rest build off this method.
View Replies
ADVERTISEMENT
Jul 9, 2014
What's that diameter? Create a new method for the circle class called diameter. Add this method to the circle class described on page 15-1. It should return a double that is the diameter of the circle. No parameters are passed to this method.
In a tester class, test the performance of your new diameter method as follows:
(Your project should have two classes, Tester and Circle.)
here is what i have so far:
public class Circle
{
public Circle (double r)
{
radius = r;
}
public double area()
{
double a = Math.PI * radius * radius;
[Code] ....
View Replies
View Related
Nov 7, 2014
How can I write a method that takes a string with duplicates letters and returns the same string which does not contain duplicates. For example, if you pass it radar, it will return rad. Also i would like to know how can I Write a method that takes as parameters the secret word and the good guesses and returns a string that is the secretword but has dashes in the places where the player has not yet guessed that letter. For example, if the secret word is radar and the player has already guessed the good guesses letters r and d, the method will return r-d-r.
View Replies
View Related
May 13, 2014
I am really struggling to make the Split String method work with another method which is double hours.
HtmlElement span = new HtmlElement(SPAN_OPEN, SPAN_CLOSE);
span.setValue("Drive Time: ");
td.addNestedElement(span);
HtmlElement span2 = new HtmlElement(SPAN_OPEN, SPAN_CLOSE);
span2.addAttribute("class", "drive_time");
String time=String.valueOf(showSet.getTransferHours());
/*Split the Strings into Hours and Minutes*/
[code]...
View Replies
View Related
Aug 11, 2014
I need making the toString() method return a String rather than display a message to the screen. Also, I'm not supposed to call the toString method in my demo class to test it, so what should I do instead?
public class cupDispenser {
String location;
int noOfCups;
cupDispenser(String location,int cups)
{
this.location=location;
this.noOfCups=cups;
}
public String getlocation()
[Code]...
View Replies
View Related
May 19, 2015
I'm trying to create a private method called capitalize() which takes String nameModel in any uppercase/lowercase combination and returns it with the first letter uppercased and all other lowercased. E.g. "stePHeN" returns "Stephen" . This is what I've written so far:
private String makePrettyString(String modelName) {
if (modelName ==null) {
return null;
}else if (modelName =="") {
return "";
} else{
return modelName.substring(0,1).toUpperCase() + modelName.substring(1).toLowerCase();
}
}
Unfortunately it doesn't work and it still returning me the String modelName in its original uppercase/lowercase combination.
View Replies
View Related
Sep 7, 2014
I want to use a method, which takes for example an int and also returns an integer. For example, if the the given integer is strong return a, if it is notstrong return b. How would you write that in a Code?
I want to use that in a more general way. I want to give a method mlong the value X of the type date and let it return an int. Type date consists of 3 int, one of them is the int month.
mlong should return an int depending on the X.moth. at the moment my code looks like this:
// File1:
public class date {
public int day;
public int month;
public int year;
}
// File 2:
public class monthlength {
public int mlong(date X) {
int t;
t = X.month;
if (t == 1 || t == 3 || t == 5 || t == 7 || t == 8 || t == 10 || t == 12)
{ return 31; }
if(t == 4 || t == 6 || t == 9 || t == 11)
{return 30;}
}
}
View Replies
View Related
Mar 17, 2014
I am new to Java and would like to ask how to do this question specifically:
Code a Java method that accepts a String array and a String. The method should return true if the string can be found as an element of the array and false otherwise. Test your method by calling it from the main method which supplies its two parameters (no user input required). Use an array initialiser list to initialise the array you pass. Test thoroughly.
View Replies
View Related
Sep 28, 2014
I am having a problem with the following code. It compiles and runs fine however my output is wrong.
public class SplitString {
public static void main(String[] args) {
String[] string1 = split("ab#12#453", "#");
String[] string2 = split("a?b?gf#e", "[?#]");
for (int i = 0; i < string1.length; i++) {
System.out.print(string1[i] + ",");
[code]....
The split method in the String class returns an array of strings consisting of the substrings split by the delimiters. However, the delimiters are not returned. Implement the following new method that returns an array of strings consisting of the substrings split by the matching delimiters, including the matching delimiters.public static String[] split(String s, String regex)For example, split("ab#12#453", "#") returns ab, #, 12, #, 453 in an array of String, and split("a?b?gf#e", "[?#]") returns a, b, ?, b, gf, #, and e in an array of String.
View Replies
View Related
Apr 2, 2014
How do i take input values for TwoDPoint (which are objects) and return it back in numerical values also print them.
When i create an object in main method and pass values to my function of return type TwoDPoint,it gives error:- found int,int need TwoDPoiint,TwoDPoint.
// Here is what i tried to do:
Created class TwoDPoint that contains two fields x, y which are of type int. Defined another class TestTwoDPoint, where a main method is defined.In the main method created two TwoDPoint objects.
Then I modified the class TestTwoDPoint and add another function to it. This function takes two TwoDPoints as input and returns the TwoDPoint that is farthest from the point (0,0).
Then I added another function to TestTwoDPoint. This function takes two TwoDPoints as input and returns a new TwoDPoint whose x value is the sum of x values of the input TwoDPoint's and whose y value is the sum of the y values of the input TwoDPoint's.
class TwoDPoint {
int x = 2;
int y = 4;
}
class TestTwoDPoint {
public static void main(String args[]) {
TwoDPoint obj1 = new TwoDPoint();
System.out.println(obj1.x);
System.out.println(obj1.y);
[Code] ....
View Replies
View Related
Jul 8, 2014
Write method distance to calculate the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double. Incorporate this method into an application that enables the user to enter the coordinates of the points.
Hints:
- The distance between two points can be calculated by taking the square root of
( x2 - x1 )2 + ( y2 - y1 )2
- Use Math class methods to compute the distance.
- Your output should appear as follows:
Type the end-of-file indicator to terminate
On UNIX/Linux/Mac OS X type <ctrl> d then press Enter
On Windows type <ctrl> z then press Enter
Or Enter X1: 1
Enter Y1: 1
Enter X2: 4
Enter Y2: 5
Distance is 5.000000
Type the end-of-file indicator to terminate
On UNIX/Linux/Mac OS X type <ctrl> d then press Enter
On Windows type <ctrl> z then press Enter
Or Enter X1: ^Z
View Replies
View Related
May 27, 2014
I'd like to know how to return a new array, I wrote in a method below the main method. I want to print the array but system.out.print doesn't work for arrays apparently. What structure i should use?
View Replies
View Related
Oct 30, 2014
Alright, I don't understand how to link my compress method to my return statement method "getPText". Also in my compression I only want it to compress for 3 or more consecutive letters.
import java.util.Scanner;
class RunLengthCode {
String pText;
String cText;
void setPText(String PText) {
pText = "";
}
[Code]...
View Replies
View Related
Dec 25, 2014
I need to write a method that will consume string representation of Object type and will return one object of this type. How to set return type for the method in this case?
Here is exmaple :
public <?> identifyType(String typeString){
if (typesString.matches("String")){
return new String("");
}else if (typeString.matches("Integer")){
return new Integer(0);
}
//....etc..}
View Replies
View Related
May 8, 2014
I am trying to convert the double 4270571936.0000000000d to a hex string using Double.toHexString() and the answer I'm getting is 0x1.fd17834p31, what does p stands for?
The answer I'm expecting to get is 0x41efd17834000000 so not sure why it won't give me the correct answer?
The following floating point Double to hex calculator shows the write answer right Floating Point to Hex Converter
View Replies
View Related
Oct 4, 2014
//Students Full Name
firstName = JOptionPane.showInputDialog("Enter student " +
"first name.");
lastName = JOptionPane.showInputDialog("Enter student " +
"last name.");
// Get test grade (numbers)
[b]test1 = JOptionPane.showInputDialog("Enter test1 grade")[/b];
The line in bold is where that error comes up. I know it something simple but I can't remember. I declared both firstName and lastName as Strings and then the test1 I declared as double. I had a similar error in a previous assignment where I had a integer(age) input and then i had an output statement asking for a name all I needed to do was put keyboard.nextLine(); after my age input and I was fine.
View Replies
View Related
Oct 26, 2014
I am making a program where the user types in how many students, the student name and the student result. My problem is typing in a dobule name for instance: Tom Tom.
I have tried both:
String name = input.Next(); -> Only works with one name.
and
String name = input.nextLine(); -> Skips right trough and ask me to type result again.
Here is my code:
Java Code:
import java.util.Scanner;
public class c5e8 {
public static void main(String[]args){
Scanner input = new Scanner (System.in);
int highestResult = 0;
String highestName = " ";
[Code] ....
View Replies
View Related
May 2, 2014
I am supposed to write a program on PuTTY using UNIX (I have Windows 8), but I am not comfortable with it yet, so I am using Java through NetBeans (IDE 7.4).
The program has to follow these instructions (ignore the Linux part of the instructions, the rest is in bold):
Write a program on the Linux system using the putty utility. The program should get strings of data from the command line (that is, look for the data in the "args" array of strings). Use a loop to convert each of the strings in the array into a double and add the number to a total. Print the total after all of the strings have been processed.
The program will use try-catch to catch any error that occurs. If an error occurs, the program will print a message saying that the error occurred. The program can end at that point.
You should create the Java program using the nano editor. The input data should be a list of numbers on the line that runs the program.
The problem so far is that I keep getting an error when converting a String value into a new double value. I have yet to code the try-catch method in my program
Java Code:
import java.util.*;
public class Program13Strings {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("How many lines of data do you wish to enter?");
int size = scan.nextInt();
[Code] ....
*NOTE: right where my code says double newDouble = Double.valueOf(newResponse); is where the error is occurring.
*ERROR: Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1241)
at java.lang.Double.valueOf(Double.java:504)
at program13strings.Program13Strings.main(Program13St rings.java:21)
Java Result: 1
How can this be fixed so I don't get this error?
View Replies
View Related
May 21, 2015
I stumbled upon a method that im not sure how to handle (yet).Below the code:
public DateTime() {
this.day = day(milliseconds);
this.month = month(milliseconds);
this.year = year(milliseconds);
this.hour = hour(milliseconds);
this.minute = minute(milliseconds);
[code]...
The two last methods stumped me. The return type to each is "DateTime", according to JUnit complaints.I know that I can use the "this" keyword to reference to the object. But how do I get these two methods to return the correct result?
View Replies
View Related
May 27, 2015
I've a question on rounding doubles on 0.05 As far as i know there is no class method that is able to do this. To achieve this rounding i have the following code:
Example:
164.67 -> 164.70
173.33 -> 173.35
0.02 -> 0.05
double calculatedQuantity = 0.0;
// Formula to calculate the average working hours in a month
int totalWeeksInYear = 52;
int totalMonthsInYear = 12;
[Code].....
View Replies
View Related
Apr 23, 2015
This may be a multipart question. Basically I have to write a program that accepts a string, converts it to a double splits it and then performs a calculation.
public static void main(String[] args) {
String input = ""; // initalize the string
boolean isOn = true; // used for the while loop...when false, the program will exit.
String exitCommand = "Exit"; // exit command
String[] token = input.split(("(?<=[-+*/])|(?=[-+*/])"));
[Code] ....
This is the error I get:
Enter a math problemException in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecim al.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at Calculator.main(Calculator.java:22)
[Code] .....
How do I go about actually fixing it. Without that line commented out I get this:
Enter a math problem
2+2 <-What I entered
[Ljava.lang.String;@135fbaa4
Also, how would I go about using the submethods to check for valid operands and operators (also part of the problem) I have the actual lists made obviously, but am unsure how to get those to work with the problem.
View Replies
View Related
Jul 5, 2014
I have a double primitive and gave it a huge value. I am curious if valueOf could ever potentially cause data loss. I tried a simple test and it seems it never loses any data:
Java Code:
public class DoubleStringTest {
public static void main(String[] args) {
double val = 1029.129348558634;
System.out.println(val);
System.out.println(String.valueOf(val));
}
} mh_sh_highlight_all('java');
Does this always hold true?
View Replies
View Related
Nov 23, 2014
import java.lang.Math;
import static java.lang.Math.random;
import java.util.Scanner;
public class LineofCoordinates
{
public static void main( String[] args, String x, String random, String exit, String y, String y2, String x2)
[Code] ....
View Replies
View Related
Apr 28, 2014
I am working with java project which is kind of charting room..but the problem is when am writing the query for listing the message in the conversation the error prevail in my eclipse...string literal is not properly closed by double quote...this is my java file
<%
String uname=session.getAttribute("username").toString();
String pword=session.getAttribute("password").toString();
java.util.Date dat=new Date();
int x=1;
try{
[code]....
View Replies
View Related
Jul 11, 2014
string literal is not properly closed by a double quote
View Replies
View Related
Jun 19, 2014
I am working on a project that just calculates simple interest based upon a principal and a percent interest rate written as .xxxx from user.
I need the Loan amount and the final interest calculation to show up as a currency with commas in appropriate areas, the Rate to be expressed as X.xxx% instead of .xxxx
I keep getting this error when I compile:
C:JavaInterestCalculator.java:46: error: incompatible types: String cannot be converted to double
principal = formatter.format(principal);
^
C:JavaInterestCalculator.java:49: error: incompatible types: String cannot be converted to double
rate = formatter.format(rate);
^
C:JavaInterestCalculator.java:52: error: incompatible types: String cannot be converted to double
totalInterest = formatter.format(totalInterest);
^
3 errors
Tool completed with exit code 1
And here is my code
import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
// class declaration
public class InterestCalculator
{
// main method declaration
[Code] .....
View Replies
View Related