如何在5次尝试后中断循环?

huangapple go评论63阅读模式
英文:

How to break the loop after 5 attempts?

问题

// 文件名:SmallIO.java

import java.util.Scanner;

public class SmallIO {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        String a = "";   // 初始化为空字符串

        while (true) {
            // 一个无限循环,使用 Ctrl-C(从命令提示符)退出

            System.out.println("输入一行:");

            a = keyboard.nextLine();

            System.out.println("您的行: " + a);

            System.out.println();
        } // 循环结束

    } // main 方法结束

} // 类结束
英文:
//File name: SmallIO.java

import java.util.Scanner;

public class SmallIO{

	public static void main(String[] args){

		Scanner keyboard = new Scanner (System.in);

		String a = "";   // initialise to empty string

		while (true){
			//an infinite loop, use Ctrl-C (from command prompt) to quit

			System.out.println("Enter a line:");

			a = keyboard.nextLine();

			System.out.println("Your line: " + a);

			System.out.println();
		}//end of while

	}//end of main

}//end of class

答案1

得分: 3

有多种方法,最简单的方法之一是使用实际的for循环:

for (int i = 1; i <= 5; i++) {....}

这与以下代码相同:

int i = 1;
while (i <= 5) {.... i++; }
英文:

There are multiple ways, the simplest one would be to use an actual for loop:

for (int i = 1; i &lt;=5; i++) {....}

This is the same as:

int i = 1;
while (i &lt;= 5) {.... i++; }

答案2

得分: 1

打破循环(任何循环),使用break语句。

要在5次迭代后中断循环,您可以使用计数器

这是结合break使用计数器的一种方法

int counter = 0;
while(true) {
    counter++;
    if (counter == 5) break;
}
英文:

To break a loop(any loop), you use the break statement.

To break a loop after 5 iterations, you use a counter

This is one of the way to use a counter in combination with break

int counter = 0;
while(true) {
    counter++;
    if (counter == 5) break;
}

huangapple
  • 本文由 发表于 2020年9月7日 22:49:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63779901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定