3

I'm trying to handle a user input and allow for only floats to be entered. The number of floats that can be entered is unlimited, but if two consecutive non-floats are entered the program will end. When the program ends it will print the sum of all the numbers.

The problem is that whenever I run this it immediately runs through the while loop and increases the count to 2 and breaks the loop. You're only able to enter one non-float before it cancels out.

     while(true){
        try{
            sum+= inRead.nextFloat();
        }
        catch (InputMismatchException e){
            if (count == 2){
                System.out.println(sum);
                break;
            }
            else{
                count+=1;
            }
        }
    }

EDIT: As a few of you had pointed out that count should be initialized before the while loop

    Scanner inRead = new Scanner(System.in);
    float sum = 0;
    int count = 0;
    while(true){
        try{
            sum+= inRead.nextFloat();
        }
        catch (InputMismatchException e){
            if (count == 2){
                System.out.println(sum);
                break;
            }
            else{
                count+=1;
            }
        }
    }

4 Answers4

1

Try this:

    Scanner inRead = null;
    float sum = 0;
    int count = 0;
    while(true){
        try{
            inRead = new Scanner(System.in);
            sum+= inRead.nextFloat();
            if(count == 1) {
                count = 0;
            }
        }
        catch (InputMismatchException e){
            if (count == 1){
                System.out.println(sum);
                break;
            }
            else{
                inRead = null;
                count+=1;
            }
        }
    }

The counter increments 2 in your code because when you encounter an InputMismatchException in a nextFloat() method. the second nextFloat() you will encounter will not work because you need to create a new Scanner for that because it causes an error earlier in your loop, and I add if(count == 1) when you need to reset it to 0 so it can satisfy your problem to stop and add all when two consecutive non-float will be inputted.

msagala25
  • 1,716
  • 2
  • 16
  • 23
  • Thank you so much. Out of curiosity, why do you do `Scanner inRead = null` and then `inRead = new Scanner(System.in)` ? –  Feb 06 '17 at 05:05
  • So we avoid to create many Objects of `Scanner`, that's why we put `null` on it when we know we will create another one for it. – msagala25 Feb 06 '17 at 05:08
  • Creating a new `Scanner` every time seems entirely unnecessary. If you need to skip the next token just call [`.next()`](http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#next--). `Scanner` may even buffer some of `System.in`, meaning you could potentially lose inputs. There should only be one object reading from stdin. – dimo414 Feb 06 '17 at 05:16
  • Thank you for the downvote mr. @dimo414 . This is the only way I can answer it, Atleast I resolved it on my own and helped him. maybe my answer is not perfect but you can respect the answers of others too. Im not like the others like you that is fully experience In this, like others I want to learn much as well. Thanks. – msagala25 Feb 06 '17 at 06:18
  • I'm sorry you're offended, downvoting is not a sign of disrespect. Creating a new `Scanner` every time is simply a bad idea, and I offered a suggestion for a way to avoid this buggy practice in my comment, so that you could learn. There's no need to downvote other peoples' answers just because you got downvoted - we're all here to help. – dimo414 Feb 06 '17 at 07:12
0

You should initialize count to 0 before while loop starts and everything goes fine. If you have initialized count to 1 then, when non float number is entered then the count becomes 2 and next time if you enter non float number then the loop terminates.

msucil
  • 670
  • 1
  • 5
  • 13
0

Perhaps you reused the variable count from somewhere earlier in your code causing it to break early due to an incorrect value.

You should initialize count to 0 and only increment when a non-float number is entered.

Posting more of your code could help solve the problem.

23k
  • 1,247
  • 3
  • 15
  • 46
-1

The accepted answer is broken, as constructing additional Scanner instances may actually discard parts of the input. I would strongly suggest only ever using one object to read from System.in, since it's possible (and common) for a input-reader object like Scanner to buffer data internally from the source, and replacing that object with a new instance discards any input the first object already buffered.

It's also not necessary to get the behavior you want. Instead use .next() to skip the next token if it's not valid, and use .hasNextDouble() to determine if the next token is a valid double (rather than catching the InputMismatchException).

try (Scanner in = new Scanner(System.in)) {
  double sum = 0;
  boolean lastInputBad = false;
  while (true) {
    if (in.hasNextDouble()) {
      sum += in.nextDouble();
      lastInputBad = false;
    } else if (lastInputBad) {
      break; // break the loop on a subsequent bad input
    } else {
      in.next(); // skip first bad input
      lastInputBad = true;
    }
  }
  System.out.println("Sum of valid inputs: " + sum);
}

Note also that I used double, rather than float. There's essentially no reason to use float in modern code; just stick to double.

Community
  • 1
  • 1
dimo414
  • 42,340
  • 17
  • 131
  • 218