0

I've created an ArrayList of doubles that is supposed to store values for all the doubles that the scanner detects, in cell++. However, when I run the code, the program keeps asking for a next input forever, and I don't know why.

For example if my input is 2, 3, 9, I want the program to store value 2 to the first cell of the arraylist, value 3 to the second and value 9 to the third. The problem is, if i fill in 2, 3, 9 in my interactions pane, it keeps asking for a next input forever.

  ArrayList<Double> doubleList;
  doubleList = new ArrayList<Double>();

  while (scanner.hasNextDouble()) {
      doubleList.add(scanner.nextDouble());
  }
Ken
  • 343
  • 7
  • 20
  • What makes it stop? You just want 3 inputs? – Jean Logeart Sep 19 '14 at 21:16
  • What is the type of scanner? – ChoChoPK Sep 19 '14 at 21:20
  • @ChoChoPK: `Scanner` is `Scanner`. There's no other type binding done to it. It also doesn't *really* matter if it's coming from a file or STDOUT. – Makoto Sep 19 '14 at 21:20
  • It should stop when there is no next double. I have to code a program that is able to work when there are 3 inputs as well as when there are 500 inputs. – Ken Sep 19 '14 at 21:21
  • @Makoto : This problem and the one in the `Scanner issue when using nextLine after nextXXX` post are different, this is not a duplicate. He is not calling nextLine(), he just misuses nextDouble(). – Dici Sep 19 '14 at 21:21
  • @Ken : You just need ton input anything that is not a double to stop the loop (for example, type "."). – Dici Sep 19 '14 at 21:26
  • @Dici : Unfortunately I can't do that, as my code is checked and graded by an automatic program whose input only consists of doubles. – Ken Sep 19 '14 at 21:29
  • Maybe I figured out, putting break; at the end of the while thread stops the loop. – Ken Sep 19 '14 at 21:43
  • `break` will unconditionally jump out of loops, which is probably not what you want. – Makoto Sep 19 '14 at 21:45
  • That's true, it now only saves the first double into the arraylist. Do you possibly know of any other way to do it? – Ken Sep 19 '14 at 21:47
  • It waits for input on stdin but it won't wait for input while reading a file, it will stop at EOF. – headsvk Sep 19 '14 at 21:48

1 Answers1

0
Is this what you want to do?  Hope it helps.

I have a test.txt file 
and it has 
2
3
4
9

running will give you output:

[2.0]
[2.0, 3.0]
[2.0, 3.0, 4.0]
[2.0, 3.0, 4.0, 9.0]



  public class test2 {

  public static void main(String[] args)  throws FileNotFoundException
  {
    ArrayList<Double> doubleList;
      doubleList = new ArrayList<Double>();
      File myFile = new File("C:\\test.txt");
      Scanner scanner = new Scanner(myFile);

      while (scanner.hasNext() ) {
          if (scanner.hasNextDouble())
              doubleList.add(scanner.nextDouble());
          System.out.println(doubleList.toString());

      }
   }


  }