英文:
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 <=5; i++) {....}
This is the same as:
int i = 1;
while (i <= 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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论