如果用户输入的数字大于10,如果用户输入的数字小于10,则必须显示4次“大于10”,如果用户输入的数字小于10,则必须显示4次。
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
int i = 0;
System.out.print("Please enter a number: ");
num = sc.nextInt();
if(num < 10)
{
while(i < 7)
{
System.out.println("Less than 10");
i++;
}
}我知道我在某个地方搞砸了反变量'i‘,但我已经看了这么久了,我的大脑被炸了。有人能在这个问题上提供帮助吗?还有是的。我只限于if语句和while循环。
发布于 2014-10-27 14:40:28
在大于10的情况下使用另一个" if“(因为您只喜欢使用if)结构。对于给定的输入,它将只输入一个if结构。(您还可以选择使用"else if")
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
int i = 0;
System.out.print("Please enter a number: ");
num = sc.nextInt();
if(num < 10)
{
while(i < 7)
{
System.out.println("Less than 10");
i++;
}
}
if(num>10)
{
while(i < 4)
{
System.out.println("greater than 10");
i++;
}
}
}发布于 2014-10-27 14:38:19
您将重复“小于”但“大于”的过程。创建另一个if语句,检查它是否大于10,然后继续进入while循环进行4次迭代。
没有必要重置i,因为如果输入大于10,它就不会迭代。
发布于 2014-10-27 14:40:12
尝试添加一个else语句:
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
int i = 0;
System.out.print("Please enter a number: ");
num = sc.nextInt();
if(num < 10)
{
while(i < 7)
{
System.out.println("Less than 10");
i++;
}
}
else if(num > 10)
{
while(i < 4)
{
System.out.println("Less than 10");
i++;
}
}
}https://stackoverflow.com/questions/26589948
复制相似问题