Small programming question here.
I'm trying to get line 43
System.out.print("Please Enter the Manufacturer of Your Doughnut:");
user input to paste directly into line 46
System.out.print("Please Enter the Manufacturer of Your Doughnut:");
but my compiler keeps giving me this error:
Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at Torus.main(Torus.java:46)
For example, if the user wanted to input that their doughnuts were from McDonald's, line 46 would automatically spit out McDonald's.
Well with input.nextDouble() the compiler is expecting a Double-Datatype. You need to get a string as manufacturer. I Think input.nextLine() should do it.
Change manufacturer type from double to String and then use:
manufacturer = input.nextLine();
If you need the manufacturer variable to store a name, it should be of type String not double.
Change your declaration to
String manufacturer;
and to accept input use
manufacturer=input.nextLine(); //returns String
Related
I have an interview task where I was given a text file with file.in format, the task said that my program should be using standard data input and output (I assume console). The input file goes something like this:
249089
439506849 989399339
773359725 989399094
33290819 989399230
771114928 989399164
823133180 989399164
615096154 989399094
340750872 989399164
41881535 989399230
637599407 989399339
510268939 989399506
46219619 989399544
221332387 989399659
236968778 989399824
902942034 989399945
936095694 989400101
**end to the line 249090**
The first number is the number of objects
The second is two numbers, but for the purpose of the task I only use the second one
For the purpose of parsing the numbers I use for loop and code below:
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)))
String line = bufferedReader.readLine();
System.out.println(line);
StringTokenizer stringTokenizer = new StringTokenizer(line, " ");//
stringTokenizer.nextToken();
int height = Integer.parseInt(stringTokenizer.nextToken());
I use IntelliJ build in console and when I paste into console i get like a couple thousands results in starting from the end, so the first number is wrong, and when i run my program i get Runtime Error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "84 995058150"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at pl.artur.Main.getNumberOfBuildings(Main.java:23)
at pl.artur.Main.main(Main.java:14)
Is there a way to get around it using standard input?
This has nothing to do with where the input comes from; as the stack trace shows, the exception is thrown by the Integer.parseInt method on the string "84 995058150". This string clearly does not represent a (singular) integer. If the StringTokenizer.nextToken method returns this string, then it is StringTokenizer that's the problem. As David Conrad notes in the comments, the documentation says:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
The String.split method will split line into the two parts, so you can then call Integer.parseInt on the part you want:
String line = bufferedReader.readLine();
String[] parts = line.split(" ");
int height = Integer.parseInt(parts[1]);
Ok, I resolved the issue.
The solution was to set the bigger buffer size for the console in IntelliJ settings:
I think you cannot convert or parse string including empty spaces between them to Integer.
// This string cannot be parsed to Integer directly.
// Because an empty space is included between `84` and `995058150`.
String s = "84 995058150";
If you want to parse this, you should use trim() method. example:
int intValue= Integer.parseInt(s.trim());
I hope this answer will be helpful for you.
I'm attempting to take a substring of a string txt and then set another portion of that string to a value, however whenever I try to set voltage[t] with the double value of the substring, I'm getting an empty string error. Here's the part of the code where I'm getting the error:
if(txt.substring(0,1).equals("1")) {
//Voltage button pressed(S3)
//=====================================================================
text3.setText(txt.substring(1));
voltage[t] = (Double.parseDouble(text3.getText()));
}
Anyone know why this error would be occurring? Any help would be appreciated. Thanks!
Edit:
Here is the exact exception I'm receiving:
Caused by: java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at UartApp$11.run(UartApp.java:728)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
The error occurs on line 728
Also, here's the code I'm using to convert the int and adding the "1". The microcontroller is programmed in C:
char *p, text[32];
int i = readADC(POT);
sprintf(text,"1%d", i);
p = text;
UartTxString(p); //Sends string out
If the code you provided is complete and representable, then Double.parseDouble(...) would throw an exception indicating an empty string if and only if txt is the string "1" (and nothing else).
Assuming you want to get the double value of "1", then the way you would fix this is by changing text3.setText(txt.substring(1)); to text3.setText(txt.substring(0,1));.
If instead what you want to do is to get the double value of anything in the string after the leading "1", then I think you may have a problem elsewhere in your code--wherever it is that you set the value of txt. If so, could you post that code as well so that we can take a look?
(I think what may be happening is that you intended to prepend "1" to txt, but instead accidentally replaced the value of txt with "1" entirely)
EDIT:
The problem may be with text3 instead.
Try this. Replace
voltage[t] = (Double.parseDouble(text3.getText()));
with
voltage[t] = (Double.parseDouble(txt.substring(1)));
EDIT #2:
If the above replacement did not fix the problem, then it must be true that txt is exactly the string "1" (and nothing else) within this scope. The problem may lie in how you are prepending the '1' to txt.
i'm using Jframe as my front-end for an inventory system i have developed. I'm getting a "java.lang.NumberFormatException: For input string:"6seater"" but the variable is declared as a string so i'm a bit confused as to why this error is coming up
private String Eng_num, Chasis_num, make, model, year_of_car,capacity,description;
private Integer status,Sup_id;
public void actionPerformed(ActionEvent e)
{
Insert I = new Insert();
try
{
Chasis_num = textField_1.getText();
Eng_num = textField_9.getText();
year_of_car = textField_10.getText();
model = textField_11.getText();
make = textField_12.getText();
capacity = textField_14.getText();//error is at this line
description = textField_16.getText();
Sup_id = Integer.parseInt(""+textField_13.getText().toString());
status = Integer.parseInt(""+textField_15.getText().toString());
I.insertVehicle(Eng_num, Chasis_num, make, model, year_of_car, capacity, Sup_id, status, description);
}
I even try to put .toString and still getting the same error
capacity = textField_14.getText();
I don't think this is the cause of your exception.
java.lang.NumberFormatExceptionOnly occur when you try to parse String into any kind of Number.
So, i'm guessing, this exception was thrown somewhere you try to convert 6seater to Int or some other number format.
I'm getting a "java.lang.NumberFormatException: For input string:"6seater"" but the variable is declared as a string so i'm a bit confused as to why this error is coming up.
The error is happening because you have tried to parse the characters 6seater as an integer. It isn't an integer. An integer consists of the characters 0 through 9, possibly with a - character at the front. Any other character, and the value will be rejected ...
(The problem is nothing to do with the type that getText() returns. The problem is the value that you are giving to the parseInt method. It is not clear where the parseInt call is. A stacktrace would answer that ... but you didn't provide one.)
Also, you say:
capacity = textField_14.getText();//error is at this line
Actually, it isn't. That line cannot possibly throw a NumberFormatException. In reality, the error could be happening at one of these lines:
Sup_id = Integer.parseInt(""+textField_13.getText().toString());
status = Integer.parseInt(""+textField_15.getText().toString());
or it could be happening within the the insertVehicle method that you are calling here:
I.insertVehicle(Eng_num, Chasis_num, make, model,
year_of_car, capacity, Sup_id, status, description);
I should also point out that you have made some egregious Java style errors in your code:
Java class, method or variable names should never contain _ as a separator. Use "camel case".
A Java variable name should never start with an uppercase letter.
(If you instructor doesn't deduct "style" marks for this, he/she should. If your code reviewers don't pick this up, they are not doing their job properly. If this code was intended to be delivered to a paying customer, they would have reason to complain about the code quality ...)
Recently, while coding I came upon the following error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
at java.lang.String.charAt(String.java:686)
at TestAssign2.main(TestAssign2.java:119)
The error appears when I add the line - firstLetter=userName.charAt(0); to the code and program displays the error message after the user enters all the values asked. Before this line was entered, it all worked fine.
while(uProgStart.equals(PROGSTART))
{
System.out.println("What is your name?");
userName=sc.nextLine();
junk = sc.nextLine();
System.out.println("What is the year of your birth?");
birthYear = sc.nextInt();
junk = sc.nextLine();
System.out.println("What is the date of your birth? (dd.mm)");
birthDDMM = sc.nextDouble();
junk = sc.nextLine();
day=(int)birthDDMM;
month=(int)Math.round(100*birthDDMM)%100;
//Begins calculation of Dss Score
if(birthYear%CYCLE_LENGTH!=SNAKE_YEAR)
{
DssScore=DssScore+1;
}
if(month<SPRING_BEGINNING||month>SPRING_END)
{
DssScore=DssScore+2;
}
firstLetter=userName.charAt(0);
if(firstLetter==(LOWER_S)||firstLetter==(UPPER_S))
{
DssScore=DssScore+4;
}
The idea of the line was to see if the name entered by the user begins with either the letter 's' or 'S'.
All the variables have been declared, I just haven't included them for the sake of keeping this post a little succinct.
I think you are pressing enter key by mistake without giving a chance to enter any input and it forces username variable be empty. I reproduced this error like mentioned above.Sometime when you deal with scanner, it happens like that.
So in your code, check whether the username is null or not before doing any operation.
The call to sc.nextLine() for assigning userName prior to the charAt call likely returns an empty string (eg. if you scan a blank line).
You may want to use if to make sure that the next line really exists.
Something like this:
if(sc.hasNextLine()) {
userName = sc.nextLine()
} else {
System.out.println("OMG... Where is my line?")
}
This most likely not a good fix for your problem, but based on the limited information we have it's difficult to suggest anything better.
The real problem is most likely elsewhere in your logic.
Please help me for conversion my line of codes are mention below:
String deptName = "IT";
String dept_test = request.getParameter("deptName").trim();
System.out.println("Dept name vlue is"+dept_test);
// problem here for casting...
int dept_id = Integer.parseInt(dept_test);
I don't see any casting problems. If your text doesn't contain a parseable number you will get a NumberFormatException which you may need to catch with a try/catch block. What exactly is the problem you are having?
From looking at your code the most you get will be an error parsing the input (including if it is none. What may be an issue is that the variable deptName is never used. Did you mean to make the second line
String dept_test = request.getParameter(deptName).trim();
(notice no quotes) instead?