嗨,我正在尝试输入 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 anif
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/