嗨我想要输入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 {
???
}
}
}
答案 0 :(得分:2)
你在if语句中犯了错误。
没有
;
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);
答案 1 :(得分:1)
由于您期望1到10之间的数字,但是在得到有效数字之前您不知道要获得多少数字,我建议使用while
循环,如下所示:
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();
while (num1 < 1 || num1 > 10) {
System.out.print("Invalid number, enter another one: ");
num1 = in.nextInt();
}
System.out.println("Input = " + num1);
}
}