我最近才刚开始使用Java,这很糟糕。我真的很紧张。我需要弄清楚如何使用do-while
循环将用户输入的1到10之间转换为星号。如果您能向我展示如何做到这一点,我将不胜感激。
System.out.println( "Enter number between one and ten: " );
示例:input = 7
预期输出:*******
如果数字不在1到10之间,则显示“重试”并再次询问
public class JavaApplication12 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println( "Enter number between one and ten: " );
int count = in.nextInt();
int counter = 0;
if (count<1||count>10) {
System.out.println("Try again");
count = in.nextInt();
System.out.print("*");
counter++;
}else{
do {
System.out.print("*");
counter++;
} while (counter < count);
}
}
}
答案 0 :(得分:1)
这很容易。您需要在此处使用counter
之类的变量,然后循环直到打印所有星星。最重要的是do while
至少运行一次,因此您需要将counter
初始化为零才能正常工作。相反,您可以从1开始并将条件更改为while (counter <= count)
。
希望这就是您想要的:
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println( "Enter number between one and ten: " );
int count = in.nextInt();
int counter = 0;
do {
System.out.print("*");
counter++;
} while (counter < count);
}
答案 1 :(得分:0)
您必须在if
块中删除多余的行。您的代码很好。
import java.util.Scanner;
public class JavaApplication12 {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println( "Enter number between one and ten: " );
int count = in.nextInt();
int counter = 0;
if (count<1||count>10) {
System.out.println("Try again");
}else{
do {
System.out.print("*");
counter++;
} while (counter < count);
}
}
}