Home > front end >  How do I exit a for or a while loop with user input in java
How do I exit a for or a while loop with user input in java

Time:11-03


import java.util.Scanner;
public class Main {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("-------Welcome to the Radius calculator-------");

        String input = new String (" ");
        while(input.equals("END")==false) {

            for (int i = 1; i < 5; i  )
                for (int e = 5; e > 0; e--)
                {
                    {
                        System.out.println("-----------------------------");
                        System.out.println("Hey you can use this calcultor "   e   " more time(s) till yoh have to purchase our full version only 3.99");
                    }
                    System.out.println("Please enter your Radius if not just type in END at any stage during the program");
                    Double num =sc.nextDouble();

                    System.out.println("Enter 1 if you would like to get the area");
                    System.out.println("Enter 2 if you would like to get the circumfrence");

                    int num1 = sc.nextInt();

                    if (num1 == 1) {
                        System.out.println("The area of the circle with the radius "   num   " is :"   (Math.PI) * (num * num));
                    } else if (num1 == 2) {
                        System.out.println("The circumfrence of the circle with the radius "   num   " is :"   (2) * (Math.PI) * (num));

                    } else {
                        System.out.println("No answer for you boss");
                        System.out.println("Try again!");
                    }
                    System.out.println("You have used this calculator effiently "   i   " time(s)");
                    System.out.println("-----------------------------");


                }
        }

    }
}

Heres my code it works but when i type in END an ERROR comes up.(https://i.stack.imgur.com/ZZxEW.png)](https://i.stack.imgur.com/ZZxEW.png)

If theres any othere tips to make my code for effecient would be much appriciated too.

CodePudding user response:

You forgot to ask for the end input during the loops.
The best way to ask for an input of different types is to use BufferedReader Class

BufferedReader reader =new BufferedReader(newInputStreamReader(System.in));
String input = null;
try {
    input = reader.readLine();
} catch (IOException ex) {
    throw new RuntimeException(ex);
}
if (input.equals("END")) {
    break;
}

After that you can use :
Integer.parseInt(input); to cast from String to Integer
And don't forget to clean and simplify your code.

  • Related