java - 我如何编写“If/else Statement”来为用户提供答案?
问题描述
我在编写以用户回答为条件的 if/else 语句时遇到问题。我要求用户输入一个介于 1 和 8 之间的数字,如果用户输入一个介于该范围之间的数字,则答案将存储在变量中,如果答案超出范围,程序会说:“位置无效。” 像这样的东西:
System.out.println("Choose a number (Between 1 to 8)");
if(---------------){
ubNum = input.nextInt();
}else{
System.out.println("Enter a valid number please");
}
我需要在 if 语句中添加什么来完成它?
解决方案
如果您的范围内还包括 1 和 8 数字,那么这里是代码
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
System.out.println("Choose a number (Between 1 to 8)");
Scanner sc=new Scanner(System.in);
int a = sc.nextInt();
if (a >= 1 && a <= 8)
System.out.println("No. is valid");
else
System.out.println("Enter a valid number please");
}
}
编辑1:
如果用户输入的值在给定范围内,则该值将存储在整数变量中res
,使用它您可以对存储在变量中的值执行任何进一步的计算res
。
If the number entered by user is not in the given range then default value(i.e 0) will be printed along with the message "Enter a valid number please"
.
int res = 0;
int a = sc.nextInt();
if (a >= 1 && a <= 8)
res=a;
else
System.out.println("Enter a valid number please");
System.out.println(res);
推荐阅读
- css - Highcharts 标签文本未正确呈现
- javascript - 如何从 mongodb 中的给定数组中检索可用的“startTime”键的完全匹配值?
- javascript - 使用模糊事件,我如何确保模糊事件在提交按钮之前发生?
- python - 使用 acs5.get 在 python 中访问人口普查 acs5 中位数收入块组数据
- logging - Paramiko 日志记录配置
- sql-server - 在我的金额字段中查找任何连续整数的 SQL 查询
- laravel - 未捕获的反射异常:805
- java - 使用 freemarker 模板发生错误配置失败
- xamarin - 是否有一次多次调用应用程序 OnStart 方法。如果是,为什么建议将 AppCenter.Start 放在那里?
- swift - 如何检查窗口是否打开?