简体   繁体   中英

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

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
    }   

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") );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM