Flow
Flow

Reputation: 169

Reading user input

I'm trying to ask the user to enter any number of numbers up to 5, each number seperated by space.

for example

enter up to 5 numbers : 3 4 5

I'm going to add them in the integer sum and then later divide them by counter

to get the average of these numbers.

However, my loop does not seem to end. What's wrong with my code?

    int counter = 0 , sum = 0;

    Scanner scan = new Scanner(System.in);

    System.out.println("enter up to 5 numbers");

    while(scan.hasNextInt());{
    counter++;
    sum += scan.nextInt();
    }
    System.out.println(counter);
    System.out.println(sum);

Upvotes: 0

Views: 433

Answers (6)

JayQ
JayQ

Reputation: 11

  DataInputStream in = new DataInputStream(System.in);
  String[]label = {"quiz #","Total","Average"};
  int counter = 0;
  int theSum = 0;

   System.out.print("Enter up to 5 number : ");
   String[]tempNum = in.readLine().trim().split("\\s+");
   System.out.println();

 while (counter <= tempNum.length)
 {
    if ( counter == tempNum.length)
    {
     System.out.printf("%10s %12s\n",label[1],label[2]);
     counter = 0;
     break;
    } else {
     System.out.printf("%10s",label[0] + (counter+1) );
    }
    counter++;  
 }

 while(counter <= tempNum.length)
 {
    if ( counter == tempNum.length)
    {System.out.printf("%10d %10.2f\n",theSum,(double)(theSum/counter));
    } else 
    {System.out.printf("%10d",Integer.valueOf(tempNum[counter]));
     theSum += Integer.valueOf(tempNum[counter]);
    }
    counter++;
 }

Upvotes: 0

Gaurang Jadia
Gaurang Jadia

Reputation: 1516

If you want to read entire line and then do arithmetic operation later then you dont need to have while loop with hasNextInt() method.

I would suggest you to read line then split by space and iterate over string array. Check out code snippet.

package com.gaurangjadia.code.java;

import java.util.Scanner;

public class SO19204901 {

    public static void main(String[] args) {
        int counter = 0,
                sum = 0;

        System.out.println("enter up to 5 numbers");

        Scanner scan = new Scanner(System.in);

        String strInput = scan.nextLine();

        String[] arrayNumbers = strInput.split(" ");

        for (int i = 0; i < arrayNumbers.length; i++) {
            int n;

            try {
                n = Integer.parseInt(arrayNumbers[i]);
            }
            catch (NumberFormatException e) {
                n = 0;
            }

            sum = sum + n;
            counter++;
        }

        System.out.println(sum);

    }

}

Upvotes: 0

YaleCheung
YaleCheung

Reputation: 630

int counter = 0 , sum = 0;

Scanner scan = new Scanner(System.in);

System.out.println("enter up to 5 numbers");

while(scan.hasNextInt()){
    counter++;
    sum += scan.nextInt();
    if(counter >=5)
        break;
}
System.out.println(counter);
System.out.println(sum);
scan.close();

First, you need to remove ';' located after while(scan.hasNextInt()) and before {; For the ; means the while statement is complete. Second, when you use your code, you need CTRL + Z to end up your input. By adding

if(counter >=5)
    break;

your input will end up when you input 5 numbers.

Upvotes: 0

kshirish
kshirish

Reputation: 1549

Everything in your code is fine except the semicolon(;) just after the while loop, of course it will lead to an infinite loop.

Upvotes: 0

Dolda2000
Dolda2000

Reputation: 25865

Scanner.hasNextInt() does not do what you seem to think it does. It does not tell you whether there is an integer available in already typed input (it does not have any conception of what has "been typed"), but rather whether the input waiting can be read as an integer. If there is no input already waiting, it will block until there is, so your loop is simply sitting there forever, blocking for more input.

What you probably want to do instead is to read a whole line, and then split it explicitly into space-separated parts, and only then parse those as integers. For example, like this:

String input = scan.nextLine();
for(String part : input.split(" "))
    sum += Integer.parseInt(part);

Serge Seredenko's answer is also correct, however, but that's another problem.

Upvotes: 0

Serge Seredenko
Serge Seredenko

Reputation: 3541

You put a ; between while and {, so it loops. Remove it.

Upvotes: 1

Related Questions