0

I'm creating a simple average calculator using user input on Eclipse, and I am getting this error: " java.util.NoSuchElementException: No line found " at

String input = sc.nextLine();

Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.

import java.util.Scanner;

public class AverageCalculator {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the numbers you would like to average. Enter \"done\"");
        String input = sc.nextLine();
        float num = sc.nextFloat();
        float sum = 0;
        int counter = 0;
        float average = 0;
        while(input != "done"){
            sum += num;
            counter ++;
            average = sum / counter;
        }
        System.out.println("The average of the "+ counter + " numbers you entered is " + average);

    }

}

Thanks a lot:)

Selina
  • 11
  • 3
  • add condition to enter count of number and move sc.nextLine() into loop to accept all number, or can use nextFloat in loop – sanjeevRm Apr 01 '21 at 04:43
  • Maybe parse the input, be it a float or String, to a float. If it parses, then continue with averaging, else, see if it equals “done” by using sc.nextLine() and break the loop if it is “done”. – LuckyBandit74 Apr 01 '21 at 04:45
  • 1
    Also make sure to use the correct comparator for Strings which would be input.equals(“done”). You can put a ! before the word “input” to signify “not” – LuckyBandit74 Apr 01 '21 at 04:46
  • Could you elaborate on "add condition to enter count of number", please? sanjeevRm – Selina Apr 01 '21 at 04:47
  • first input to be how many numbers to be considered for average – sanjeevRm Apr 01 '21 at 04:57
  • float count = sc.nextFloat(); for(float i=0; i – sanjeevRm Apr 01 '21 at 05:06

3 Answers3

3

First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.

When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.

Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".

Like this:

Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
    if (sc.hasNextDouble()) {
        double num = sc.nextDouble();
        sum += num;
        counter++;
    } else {
        String word = sc.next();
        if (word.equalsIgnoreCase("done"))
            break; // exit the forever loop
        sc.nextLine(); // discard rest of line
        System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
    }
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);

Sample Output

Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

So there are a few issues with this code:

  1. Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.

  2. You aren't updating the input variable in the loop, it will only ask for one input and stop.

  3. And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).

To implement the changes:

import java.util.Scanner;

public class AverageCalculator {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the numbers you would like to average. Enter \"done\"");
        
        float sum = 0;
        int counter = 0;

        String input = sc.nextLine();
        while (true) {
            try {
                //Try interpreting input as float
                sum += Float.parseFloat(input);
                counter++;
            } catch (NumberFormatException e) {
                //Turns out we were wrong!
                //Check if the user entered done, if not notify them of the error!
                if (input.equalsIgnoreCase("done"))
                    break;
                else
                    System.out.println("'" + input + "'" + " is not a valid number!");
            }
            // read another line
            input = sc.nextLine();
        }
        
        // Avoid a divide by zero error!
        if (counter == 0) {
            System.out.println("You entered no numbers!");
            return;
        }

        // As @Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
        float average = sum / counter;
        System.out.println("The average of the "+ counter + " numbers you entered is " + average);

    }

}
Maxim Khanov
  • 434
  • 2
  • 8
  • 1
    There is no need to cast `counter` to `float`. The language will implicitly do that for you. It's called [numeric promotion](https://docs.oracle.com/javase/specs/jls/se15/html/jls-5.html#jls-5.6-500). – Andreas Apr 01 '21 at 05:22
  • Silently ignoring errors is a very bad idea. – Andreas Apr 01 '21 at 05:24
  • @Andreas, although I usually would agree, and actually, I like your solution better (I didn't know about hasNextDouble). I would argue that since I am only catching a NumberFormatException in a code block that will specifically do string to float conversion, it's not the biggest sin. – Maxim Khanov Apr 01 '21 at 05:31
  • 1
    Me dumb user. Me enters `1 S 6 O done`, and since 1 + 5 + 6 + 0 = 12 and 12 / 4 = 3, I expect the program to tell me the average is 3, but it says the average is 3.5 *(since `(1+6)/2 = 3.5`)*. Me not understand. --- Now, if the program had not silently ignored the errors and had told me that `S` and `O` are not valid numbers and have been ignored, I would understand, but it didn't tell me that. --- Dumb program not working, me sad! – Andreas Apr 01 '21 at 05:38
  • @Andreas, lol who would've known I'd be learning UI principles when posting an answer! – Maxim Khanov Apr 01 '21 at 05:46
0
import java.util.Scanner;

public class AverageCalculator {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");        
        
        String input = scanner.nextLine();
        float num = 0;
        float sum = 0;
        int counter = 0;
        float average = 0;
        while(!"done".equals(input)){           
            num = Float.parseFloat(input);  // parse inside loop if its float value
            sum += num;
            counter ++;
            average = sum / counter;
            input = scanner.nextLine();  // get next input at the end
        }
        System.out.println("The average of the "+ counter + " numbers you entered is " + average);

    }

}
Jimmy
  • 995
  • 9
  • 18