gpt4 book ai didi

java - if 和 else 语句在 java 中不起作用

转载 作者:行者123 更新时间:2023-12-01 22:03:38 30 4
gpt4 key购买 nike

嗨,我正在尝试输入 1 到 10 之间的整数。如果用户不这样做,则希望程序再次运行。我相信我需要使用 else if 语句来调用我的函数,但我不知道如何在 java 中调用函数。

这是迄今为止我的代码:

import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){

Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
if (num1 >= 1 && num1 <= 10); {
System.out.println("Input = " + num1);
}

else if {
???
}


}

}

最佳答案

if-else 始终有效。

您在 if 语句中犯了一个错误。

there is no ; for an if

if (num1 >= 1 && num1 <= 10) {//no semicolon
System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
...
}

What happens if I put a semicolon at the end of an if statement? .

<小时/>

如果输入不在 1 到 10 之间,如何再次询问用户?

循环直到得到你想要的:)

Scanner sc = new Scanner(System.in);
int num = 0;
while(true)
{
num = sc.nextInt();
if(num > 0 && num < 11)
break;
System.out.println("Enter a number between 1 and 10");
}
System.out.println(num);

关于java - if 和 else 语句在 java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33232218/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com