I'm trying to read a list of tokens from a text file into separate variables by using a while loop.
Each line in the text file goes: String, Double, Int, Int, Boolean, and there are 11 lines, but I receive an InputMisMatchException for the double line after the String line.
The txt file reads as
AC 120.99 423 70 false
Toaster 18.99 101 30 true
Toaster 11.97 201 100 false
Yoyo 5.99 223 68 false
etc.
I've tried reading the file with .hasNext and .hasNextLine. When changing the double to String I get the error for the next Int and changing that to String again takes the error to the next Int but changing that does not move the exception further.
while (infp.hasNextLine() && count < LIMIT) {
String Product_description = infp.next();
double cost_per_item = infp.nextDouble(); //line 43
int product_id = infp.nextInt();
int quantity_at_hand = infp.nextInt();
boolean domestic_origin = infp.hasNext();
items[count] = new Item(Product_description, cost_per_item,
product_id, quantity_at_hand,
domestic_origin);
count++;
}
It's supposed to read all the tokens into variables and just create separate objects for each line in the text file. But from the error I believe it is only reading the first String then throwing the exception for the double.
The exception on line 43:
Exception in thread "main"
java.util.InputMismatchException at
java.util.Scanner.throwFor(Unknown Source) at
java.util.Scanner.next(Unknown Source) at
java.util.Scanner.nextDouble(Unknown Source) at DB_Master.main(DB_Master.java:43)
as you know nextDouble method is teruning a double value
double nextDouble()
Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException is thrown.
try give input in this format
like: 34,2 instead of 34.2
or try convert your Scanner with locale
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method
The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's DecimalFormat object, df, and its and DecimalFormatSymbols object, dfs.
for more ref see java docs
still not working try parsing by checking input type.
//************************************************************************
// MixedTypeInput
// This application demonstrates testing before reading to be
// sure to use the correct input method for the data.
//************************************************************************
import java.io.*;
import java.util.Scanner;
public class MixedTypeInput
{
public static void main(String[] args)
{
double number;
Scanner in = new Scanner(System.in);
System.out.println("Enter your gross income: ");
if (in.hasNextInt())
{
number = (double)in.nextInt();
System.out.println("You entered " + number);
}
else if (in.hasNextFloat())
{
number = (double)in.nextFloat();
System.out.println("You entered " + number);
}
else if (in.hasNextDouble())
{
number = in.nextDouble();
System.out.println("You entered " + number);
}
else
System.out.println("Token not an integer or a real value.");
}
}
Related
When I run this code the console throws a NoSuchElementException. Why is that? Isn't the file being opened? The error says it corresponds to the line 34. Why?
Is Scanner reading the input from the file? Please help.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class standardDeviation {
public static void main(String[] args) throws FileNotFoundException{
// TODO Auto-generated method stub
File myFile = new File("input_data.txt");
PrintWriter output = new PrintWriter(myFile);
output.print("78.76 96.7 65.65 95.64 68.5 6.54 54.6");
output.close();
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String fileName = input.nextLine();
double sd = deviation(myFile);
System.out.println("The standard deviation of the values in this file is: " + sd);
}
public static double deviation(File myFile) throws FileNotFoundException{
Scanner in = new Scanner(myFile);
int i = 0;
double sum = 0;
double sigmaXI2 = 0;
while(i != -1){
double num = in.nextDouble();
sum += num;
sigmaXI2 += Math.pow(num, 2);
i++;
}
double sigmaXI_2 = Math.pow(sum, 2);
double s = Math.sqrt((sigmaXI2 - (sigmaXI_2)/i)/(i-1));
return s;
}
}
When do you expect the end of loop?
while(i != -1)
i keeps increasing and no there is no break.
According to JavaDoc of Scanner.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. If the translation is successful, the scanner
advances past the input that matched.
If the next token matches the Float regular expression defined above
then the token is converted into a double value as if by removing all
locale specific prefixes, group separators, and locale specific
suffixes, then mapping non-ASCII digits into ASCII digits via
Character.digit, prepending a negative sign (-) if the locale specific
negative prefixes and suffixes were present, and passing the resulting
string to Double.parseDouble. If the token matches the localized NaN
or infinity strings, then either "Nan" or "Infinity" is passed to
Double.parseDouble as appropriate. Returns:the double scanned from the
input Throws: InputMismatchException - if the next token does not
match the Float regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
When all token is exhausted due to infinite loop, NoSuchElementException is thrown.
To solve the problem, use hasNextDouble() method as the checking condition.
I have been trying to write a sentinal controlled while loop in java to add numbers, which are taken as input by the user. The loop must end when the user
enters "add".
The code is given below, the code does not show any compile error but there's a runtime Error. I would like to know what was the mistake I have done.
Thank you
// Sentinal while is used if we dont know how many numbers we are going to add
import javax.swing.JOptionPane;
public class sentinalWhile {
public static void main(String[] args)
{
String numberStr;
double number,total=0;
final String SENTINAL = "add";
numberStr = JOptionPane.showInputDialog("Enter a number to add (press add to quit):");
number = Double.parseDouble(numberStr);
while(numberStr.compareTo(SENTINAL)!=0)
{
total += number ;
numberStr = JOptionPane.showInputDialog("Enter a number to add(-999 to quit)");
number = Double.parseDouble(numberStr);
}
JOptionPane.showMessageDialog(null, "The total is:"+" "+total);
System.exit(0);
}
}
Error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "add"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at sentinalWhile.main(sentinalWhile.java:11)
You need to remove "add" from the end of the string that you receive from the input dialog.
numberStr = numberStr.substring(0, numberStr.lastIndexOf("add"));
Then try to parse the double out of this string.
number = Double.parseDouble(numberStr);
Note that if the user enters a non-number string in the input dialog (e.g. 234sdfsf5500add), you will still get that exception. However, it will work fine for the normal inputs (100add).
I'm new to Java. I am trying to scan input from the user and then print the input. However, I got the following error when I tried to run the code.
Erorr:
Thread [main] (Suspended (exception IllegalFormatConversionException))
Code:
package dumb;
import java.util.Scanner;
public class Try001 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input value for variable i:");
int i = sc.nextInt();
System.out.printf("Value for i scanned: %d",sc.next());
}
}
Input:
5
Why did I get this error and how can I fix it?
Your problem is that you get a String by sc.next() and with %d you say the program that it expects an integer.
So you have to change it e.g. to
System.out.printf("Value for i scanned: %d",sc.nextInt());
But i think you just want to print the first user input and not a second one. So you just have to print the value of variable i:
System.out.printf("Value for i scanned: %d",i);
Change sc.next to sc.nextInt. The reason being, %d indicates that you are going to display something which is a "decimal" aka number value. Sc.next gives you a string. %d cannot acceept a string data type.
Also, get rid of int i = sc.nextInt() because it is redundant.
So, I am working on a code for class and can't figure what is wrong. The code compiles and when I enter the file I'm searching for, I get this message:
Enter the name of the file: FanData.txt
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at FanDriver.fillArray(FanDriver.java:76)
at FanDriver.main(FanDriver.java:35)
Press any key to continue . . .
I'm using TextPad as my compiler and the text file is in the project. The following is the code that I have written (ignore the methods being called in the quotes as they are something I need to do afterwards):
import java.io.*;
import java.util.Scanner;
public class FanDriver
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String args[]) throws IOException
{
// Constant for the amount of elements of the array
final int MAXSIZE = 100;
// Declaring variables
int amountFans = 0;
// Declaring and initializing our array of fans
Fan[] fans = new Fan[MAXSIZE];
// Calling all of our methods
amountFans = fillArray(fans, MAXSIZE);
/**
listFanData(fans, amountFans);
bubbleSortByAge(fans, amountFans);
listFanData(fans, amountFans);
bubbleSortByFan(fans, amountFans);
listFanData(fans, amountFans);
searchByAge(fans, amountFans);
searchByFan(fans, amountFans);
*/
}
public static int fillArray(Fan[] array, int MAXSIZE) throws IOException
{
// Declaring variables
int counter = 0;
int age;
String name;
// Getting the file name
System.out.print("\nEnter the name of the file: ");
String fileName = keyboard.nextLine();
// Opening the file
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
// Making sure the file was successfully opened
if (!file.exists())
{
System.out.println("\nERROR: FILE DOESN'T EXIST. CLOSING PROGRAM NOW.");
// Exiting the program
System.exit(0);
}
// Reading all of the amounts from the file
while (inputFile.hasNext() && counter < MAXSIZE)
{
name = inputFile.nextLine();
age = inputFile.nextInt();
array[counter] = new Fan(name, age);
// Adding to our counter
counter = counter + 1;
}
//Closing file
inputFile.close();
return counter;
}
}
I do not have the code for the Fan class, just the class itself.
The file we are retrieving is the file FanData.txt, which looks like this:
Chris P. Cream
5
Scott Free
9
Lou Tenant
3
Trish Fish
12
Ella Mentry
4
Holly Day
3
Robyn DeCradle
12
Annette Funicello
4
Elmo
7
Grover
3
Big Bird
9
Bert
7
Ernie
3
Grover
9
The text file is line-by-line. One line is a name and the next is a number. I don't know how to format it correctly on here.
Any help would be greatly appreciated.
I am not sure about the delimiter in your input file.
The way you had instantiated your "Scanner"(without specifying any explicit delimiter) shall use default delimiter i.e. a whitespace character.
It seems that the "nextLine()" method in your case is not returning a "line".
It is rather returning a number or string(may be, you need check your file for that) which is not matching with the pattern followed by your Scanner.
The error is because of the type mismatch. After your first read scanner will be pointing to a non Integer value.
try to print your name before doing
age = inputFile.nextInt();
you will get to know the issue.
Above mentioned are means to understand the mistake.
Solution for your problem
Try :
age = Integer.parseInt(inputFile.nextLine()); // instead of age = inputFile.nextInt();
Exception is because of type mismatch as you are reading a text value from textfile and directly assigning to an int type.
Exception will be resolved if you parse the value as an integer as below
Integer.valueOf(inputFile.nextLine());
I recently began to program in Java, and i ran into a little problem:
I already made a String to Double line, but it doesn't seems to work proberly. As you see, the string I want to convert into a Double is one of following: USD, GPB and EURO. I know you can't convert text into a Double, but I already told Java the values of the Strings.
When I run the program below, I get this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "usd" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at java.lang.Double.parseDouble(Unknown Source) at Valuta.main(Valuta.java:22)
Why does that happen?
import java.util.Scanner;
public class Valuta {
public static void main(String[] args){
double euro, usd, gpb, done;
Scanner input = new Scanner(System.in);
euro = 7.46;
usd = 5.56;
gpb = 8.84;
System.out.println("DKK to ??");
System.out.println("USD,GPB or EURO?");
String temp = input.nextLine();
System.out.println("amount of dkk??");
Double dkk = input.nextDouble();
System.out.println("mhm");
double donee = Double.parseDouble(temp);
done = dkk*donee;
System.out.println(done);
I think what you want is to be able to associate user input for System.out.println("USD,GPB or EURO?"); to
euro = 7.46;
usd = 5.56;
gpb = 8.84;
One of hte ways to do it is to create a look up Map like this:
Map<String, Double> lookUpMap = new HashMap<String, Double>(){{
put("EURO", new Double(7.46));
put("USD", new Double(5.56));
put("GPB", new Double(8.84));
}};
Then parse user input and look up Double value:
lookUpMap.get(userInput)
The problem is you parse the currency as a double input. This line:
double donee = Double.parseDouble(temp);
should be select the proper conversion factor for the currency. You can do that with a simple if/else, a map or whatever:
double donee;
if ("usd".equalsIgnoreCase(temp) {
donee = usd;
} else if ("gbp".equalsIgnoreCase(temp)) {
donee = gbp;
/* more cases ... */
} else {
throw new RuntimeException("unknown currency");
}
You probably should move that up to before you get the number input, since if it causes an error the number input can't be processed anyway.
You have a couple of problems in this program. First to fix you're error you need to declare type double for the USD, GBP, and EURO variable names that you have there. Second you are going to need to do an if else if else block to determine what conversion to do.
double total;
if(temp.equalsIgnoreCase("USD")){
total = dkk*usd;
}else if(temp.equalsIgnoreCase("GBP"){
total = dkk*gbp;
}else {
total = dkk*euro;
}
System.out.println("This is your converted total " + total);
That will do the conversion that you want it to do. You should also take out Double.parseDouble(temp) because turning that string into a double isn't going to help you.