How to break a loop in Java with 'X'?

Viewed 68

How do I break the loop in Java with a letter instead of a number? I want it to be "Press X to exit" .This is my code below.

    System.out.println("Average Demo using do Loop");
    System.out.println();
    System.out.println("Calculates an average of all numbers: Enter 'X' when finished");
    do {
        System.out.print("Enter number ");
        input = scnr.nextInt();
        sum = sum + input;
        count++;
    }
    while (input != 1);
    avg = sum / (count - 1);
    System.out.println("The average of all numbers is " + avg);
    System.out.println();
    System.out.println();


    
    count = 0;
    input = 0;
    avg = 0;
    sum = 0;
    
    System.out.println("Average Demo using a While Loop");
    System.out.println();
    System.out.println("Calculates an average of all numbers: Enter 'X' when finished");
    // end of do...while loop
    while (input != 1) 
    {
        System.out.print("Enter number ");
        input = scnr.nextInt();
        sum = sum + input;
        count ++;
    }
    avg = sum / (count - 1);
    System.out.println("The average of all numbers is " + avg);
    System.out.println();
    //end of while loop
    for (int i = 0; i < 10; i++)
    {
        for (int y = 0; y <= i; y++)
        {
            System.out.print("*");
        }
        System.out.println();
        //end of for loop
    }   
1 Answers

You'll have to use scanner.nextLine() to get the input as a string first, as using scanner.nextInt() for character will cause an exception.

do {
   System.out.print("Enter number ");
   string input = scnr.nextLine();
   if(input.equals("x") || input.equals("X") ) {
      break;
   else {
      int num = Integer.parseInt(input);
      sum = sum + num;
      count++;
   }
} while ( ! input.toUpperCase.equals("X") );
Related