我最近刚开始使用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);
}
}
}
发布于 2018-10-18 05:34:31
这很简单。你需要在这里使用像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);
}
发布于 2018-10-18 14:21:02
您必须删除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);
}
}
}
https://stackoverflow.com/questions/52863900
复制相似问题