0

I am doing a simple task. I am assigning strings, ints, and a double to variables. The variables are being assigned through a scanner reading a text file. The scanner cannot read the double. It throws a input mismatch exception. I have researched stack overflow for the answer and I have tried the following solutions:

The text file reads as follows:

Pebbles Flinstone\n

1 2.2\n

This is a line of text\n

This is my code:

public static void main(String[] args) throws FileNotFoundException {
       File file = new File("input.txt");
       Scanner scanner = new Scanner(file);
       String s1 = scanner.next(); // s1 is assigned to Pebbles
       String s2 = scanner.next(); // s2 is assigned to Flintstone
       int x = scanner.nextInt(); // x is assigned to 1
       double y = scanner.nextDouble(); // y is assigned to 2.2
       scanner.nextLine(); // Advance scanner to beginning of next line
       String s3 = scanner.nextLine();
       scanner.close(); // s3 is assigned to "This is a line of text"
       System.out.print(y);
   }

How do I get the scanner to read 2.2 as a double? Changing the Locale doesn't work. Changing the decimal to a comma does not work either.

Kelli
  • 69
  • 1
  • 8
  • `scanner.nextDouble()`, what else? Check your input and try putting lines of `System.out.println();` to see if you inputted it wrong. – FailingCoder Mar 13 '19 at 17:11
  • 2
    When I run this when reading from the console it works fine. I'm guessing you have a part of the file that isn't properly formatted – GBlodgett Mar 13 '19 at 17:13
  • remove the \n from your input file and it'll work fine. to indicate a new line just hit return (enter) in your file. dont use \n – Makeen A. Sabree Mar 13 '19 at 17:49

0 Answers0