![](/img/trans.png)
[英]If and else statements not working in onClick() method in java
[英]if and else statements not working java
您好,我尝试输入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语句中犯了一个错误。
没有
;
if
if (num1 >= 1 && num1 <= 10) {//no semicolon
System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
...
}
如何再次询问用户输入的值是否不在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到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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.