繁体   English   中英

如何用“X”打破 Java 中的循环?

[英]How to break a loop in Java with 'X'?

如何用字母而不是数字打破 Java 中的循环? 我希望它是“按 X 退出”。这是我下面的代码。

    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
    }   

您必须首先使用scanner.nextLine() 将输入作为字符串获取,因为对字符使用scanner.nextInt() 会导致异常。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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