首页 > 解决方案 > 我如何编写“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 语句中添加什么来完成它?

标签: javaif-statement

解决方案


如果您的范围内还包括 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);

推荐阅读