Error when typing error number - java

Someone can explain my problem? When i try inputting comma number, i always get
Exception in thread "AWT-EventQueue-0"
java.lang.NumberFormatException: For input string: "1.2"
my code:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String showInputDialog = JOptionPane.showInputDialog("Enter Line: ");
int liningg = Integer.parseInt(showInputDialog);
double volume = liningg*liningg*liningg;
JOptionPane.showMessageDialog(null, "Last result are: "+volume );
}

NumberFormatException For input string: "1.2"
"1.2" is not an integer, so it can't be parsed as an integer value.
Maybe you want:
double liningg = Double.parseDouble(showInputDialog);

Related

I am getting the error message java.lang.NumberFormatException: For input string: "" and I am not sure why and how to fix it

I am pretty new to Java and I am doing this project. I keep getting the following error message while I click a jButton (submitButton) in the runtime, and I am not sure why as it is not telling which line the problem is at.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Below is my code, I was wondering if anybody could help? Maybe help me find the error, or tell me what the error message means. Thank you!
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fullName = nameText.getText();
String email = emailText.getText();
String address = addressText.getText();
String phoneNumber = phoneText.getText();
// sets either true or false to membershipSelected if a plan is selected
boolean membershipSelected = standardMembership.isSelected() || silverMembership.isSelected() || goldMembership.isSelected();
double total = 0;
// checks if the text entered in phone number text field can be parsed to an integer
// this is only possible if it is a number, if it is a string, then error pop-up appears
try {
int phone = Integer.parseInt(phoneText.getText());
}
catch(Exception e) {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid phone number, please try again!");
}
// checks if email text field does not contain "#" or a domain
if(!email.contains("#") || !email.contains(".com") && !email.contains(".de") && !email.contains(".co.uk")){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid email address, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if length of phone number is 11, if not shows error pop-up
int phoneLength = Integer.parseInt(phoneText.getText());
if(phoneLength != 11){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This phone number is not long enough, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if a plan is selected, if not shows error pop-up
if(membershipSelected){
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
else {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "Please select a membership!");
}
// sets the final overview to an empty string that can be added to with selections later
String overview = "";
if (standardMembership.isSelected()){
overview = overview + " " + standardMembership.getText() + '\n';
total = 200;
}
if (silverMembership.isSelected()){
overview = overview + " " + silverMembership.getText() + '\n';
total = 450;
}
if (goldMembership.isSelected()){
overview = overview + " " + goldMembership.getText() + '\n';
total = 600;
}
}
You have two places where you perform Integer.parseInt(phoneText.getText());
At the first time, the parsing is surrounded by a try-catch block and that handles the NumberFormatException that would be thrown in case phoneText.getText() is empty or not a number.
The second time, the parsing is not surrounded by any try-catch. This time the NumberFormatException thrown is unhandled and hence you are seeing the Exception.
You should ideally parse the phoneText.getText() once and have your conditions modified accordingly.

Java number format exception.

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "P35.00"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at OrderSystems.OrderSystem.jButton3MouseClicked(OrderSystem.java:419)
at OrderSystems.OrderSystem.access$900(OrderSystem.java:14)
at OrderSystems.OrderSystem$10.mouseClicked(OrderSystem.java:241)
I keep getting this error after i clicked the jButton3. heres my codes.
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
double sub = Double.parseDouble(sub_field.getText());
double vat = Double.parseDouble(vat_field.getText());
double allTotal = (sub + vat);
String iTotal = String.format("%.2f", allTotal);
total_field.setText(iTotal);
}
This is the code for the sub_field and vat_field
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
double ham = Double.parseDouble(ham_field.getText());
double burger = Double.parseDouble(burger_field.getText());
double bacon = Double.parseDouble(bacon_field.getText());
double bac = bacon * 5;
double harm = ham * 10;
double burg = burger *20;
double sub = harm + burg + bac;
String sub_com = String.format("P%.2f", sub);
sub_field.setText(sub_com);
}
java.lang.NumberFormatException is pretty clear: "P35.00" is not a number.
This Exception is thrown when the paramether for the parsing Double.parseDouble is not what it is excpecting.
Try out removing the P from 35.00 and see if it works.
It is also common practice to surround it with a try-catch block to prompt to the user what went wrong.
It is crashing because your input string is "P35.00" and you try to parse that into a double. Remove the 'P' and it should work because the compiler will not parse a P into a double.

Input data: java.lang.NumberFormatException: For input string: "2 "

Here is my data from the text file:
21/08/12#ESE-6329#PV/5732#30
27/08/12#PEA-4567#PV/5732#3#
11/09/12#ESE-5577#Xk/8536#2
14/09/12#PNW-1235#HY/7195#2#
And this is a code form the main method:
File orderData = new File("PurchaseOrderData.txt");
Scanner dataScan = new Scanner(orderData);
while(dataScan.hasNextLine())
{
String lineData = dataScan.nextLine();
Scanner lineScan = new Scanner(lineData);
lineScan.useDelimiter("#");
String date = lineScan.next(); // line 259
String id = lineScan.next();
String code = lineScan.next();
String quantityPlus = lineScan.next();
if(!quantityPlus.contains("#"))
management.addNewPurchaseOrder(date, id, code,
Integer.parseInt(quantityPlus)); // line 267
else
{
quantityPlus = quantityPlus.replace("#", "");
management.addNewPurchaseOrder(date, id, code,
Integer.parseInt(quantityPlus));
management.startNewMonth();
}
On the first instance of
management.addNewPurchaseOrder(date, id, code, Integer.parseInt(quantityPlus));
I get this exception:
java.lang.NumberFormatException: For input string: "2 "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Assignment2.MainTest.main(MainTest.java:267)
If I do:
String quantityPlus = lineScan.next();
quantityPlus = quantityPlus.replace(" ", "");
I get the following:
java.util.NoSuchElementException
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Assignment2.MainTest.main(MainTest.java:259)
MainTest.java:259 - String date = lineScan.next();
I've tried to use nextInt() as well, but the result is the same. What is wrong there?
Thanks a lot!
MainTest.java:259 - String date = lineScan.next();
You should check before if the line is not empty this might be why the scanner is throwing an exception
Regarding NoSuchElementException - one of your lines ends prematurely (most likely there's no data after the last #). As you can see from specification this exception is thrown when:
#throws NoSuchElementException if no more tokens are available

How do you include user input in exception message Java?

Is it possible, in Java, to include a user's input into an exception message while also using the valuse as an int or double? For example, they should enter a number (e.g., 5) but instead fat-finger something like (5r).
Is it possible to have a message say something like "You entered 5r, but should have entered a number."?
I tried using the traditional way of getting variables to print in Java here:
try {
System.out.println();
System.out.println("Value: ");
double value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
In this case, I am trying to get value displayed in the Exception message, where value is the user's invalid input.
At value it gives the error cannot find symbol.
Below is the answer I came up with. The reason I choose this answer was because most of your answers produced the output, "You entered 0.0 ..." because the answer must first be a string to be printed in the console. In addition, to be used as a number elsewhere in the program the String has cast to an Object of type Double or Integer :
String value = null; //declared variable outside of try/catch block and initialize.
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextLine(); //Accept String as most of you suggested
Double newVal = new Double(value); //convert the String to double for use elsewhere
exec.ds.push(newVal); //doulbe is getting used where it would be a 'number' instead of string
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number"); //the String valuse is received and printed as a String here, not a 'number'
} //now prints what the users inputs...
This does not work, because value is no longer in scope in the catch block. Instead you can declare it before the try:
double value = 0;
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
} catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
This will however not help if the exception is thrown because of a syntax error in the double. To handle this, you need to read a String and then convert to a double.
Get user input:
String input = '';
try{
Console console = System.console();
input = console.readLine("Enter input:");
}
... then in your catch you could do:
catch (Exception e1) {
System.out.println(e1+ "You entered: " + input + ": You must enter a number");
}
Other than the above, I don't see what the problem is. You can google how to get user input in Java, and then just take the input, put it in a variable, and print it out on error.
In this case - no, as the calling of sc.nextLine() causes the exception to be thrown, so no value is written to variable value.
Moreover, value is a local variable in this case and is unavailable from other blocks of code.
value it gives the error cannot find symbol.
You have declare the value in local block. And you are trying to access it outside the block.
Is it possible to have a message say something like "You entered 5r, but should have entered an number.
Better option is to use flag variable and loop until user enter correct number.
boolean flag = true;
double value = 0;
while(flag)
{
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextDouble();
exec.ds.push(value);
flag = false;
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
}
According to the documentation nextDouble():
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value.
So, if the input cannot be translated into a double, an exception is thrown. If you want to provide the inputted string in the exception message, I suggest you read the line as a string and try to parse it to a double, and if that fails, you can include the read line in the exception message.

Reading from the File

This program has 2 classes with a main method and is supposed to read from a file. My problem is that the line double listPrice = fileScan.nextDouble(); gives an error exception like this Exception in thread "main" java.util.InputMismatchException. The error is in this class:
Here is contents of the file:
Honda Accord
2004 16780.00 10.0
Chrysler SUV
2002 8600.00 0.0
Toyota Camry
2007 21799.99 3.0
Ford Escort
2006 12345.78 5.5
//note there is no space between each line
class Proj1P2CarAryListService
{
private ArrayList<Proj1CarData> carList = new ArrayList<Proj1CarData>();
public Proj1P2CarAryListService()
{
carList = new ArrayList<Proj1CarData>();
}
public void readStoreCarsData()
{
Scanner scan = new Scanner(System.in);
Scanner fileScan;
boolean validName = false;
double discountAmount;
double netPrice;
do
{
System.out.print("Enter file name: ");
String str1 = scan.nextLine();
try
{
fileScan = new Scanner(new File(str1));
validName = true;
while (fileScan.hasNext())
{
String name = fileScan.nextLine();
String modelYear = fileScan.next();
double listPrice = fileScan.nextDouble();
double percentDiscount = fileScan.nextDouble();
discountAmount = listPrice * percentDiscount/100.0;
netPrice = listPrice - discountAmount;
Proj1CarData proj1 = new Proj1CarData(name, modelYear, listPrice, percentDiscount, discountAmount, netPrice);
carList.add(proj1);
System.out.println(proj1.toString());
}// end while
}// end try
catch (FileNotFoundException fnfe)
{
System.out.println("Invalid File name; enter again");
}
} while (!validName);
}//readStoreCarsData
This exception is thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type(Double must be separated by . or , like said jlordo), or that the token is out of range for the expected type. Perhaps it is a file content problem.
The nextDouble() method of Scanner is locale-aware (see Documentation).
This means, if your locale is set to a country where '.' seperates a floating point number following would be a parsable double value: 123.456 while following number will give you a InputMismatchException 123,456. In Europe 123,456 would work, and 123.456 would throw an Exception. Hope it helps...
You might want to consider printing out each line. You might be getting more than you expect.

Categories

Resources