Home > OS >  Program that continues loop after invalid input?
Program that continues loop after invalid input?

Time:09-26

I am trying to create a program that asks the user for an exponent and then takes the exponent and does the operation (e^exponent). If the user inputs a value that is not a double, the program prints "Invalid input.", and continues asking for an exponent. However, I cannot get this code to work and when I type a non-double into the debugger it infinitely prints "Enter exponent: Invalid input".

importjava.util.Scanner;
class loops{
   public static void main(String[] args) {
   double exponent;
   Scanner s = new Scanner(System.in);
   do {
     System.out.print("Enter exponent: ");
     if(s.hasNextDouble()){
        exponent = s.nextDouble();
        double result;
        result = Math.exp(exponent);
        String x;
        x = "Result = "   String.format("%.4f", result);
        System.out.print(x);
        System.out.print('\n');
        System.out.println();
     }
     else {
        System.out.println("Invalid input.");
     }
  }while (true);

CodePudding user response:

The input caught by the scanner is not reset when you get to the else clause. Adding s.next(); before printing « Invalid Input » should solve your problem.

  • Related