【问题标题】:how to check the else statement in if else condition如何在 if else 条件下检查 else 语句
【发布时间】:2023-02-06 17:59:33
【问题描述】:
package react;

import java.util.Scanner;

public class Intputfromuser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        
        System.out.println("enter a number to compare with number 5 ");
        Scanner input= new Scanner(System.in);
        int a=input.nextInt();
        if(a==2)
        {
            System.out.println("U Have Entered The same value");
        }
        else if(a<2)
        {
            System.out.println("Ur number is Smaller than 2");
        }
        else if(a>2)
        {
            System.out.println("U Have Entered the number Greater than ");
        }
        else {
            System.out.println("U Have Enterer Invalid Input");
        }

    }
}

如果用户输入除整数以外的任何内容,如何仅从用户那里获取整数,然后应该运行 else 语句

【问题讨论】:

  • 将输入解析为一个整数,在其周围放置一个 try-catch,然后将您要放入 else 的内容放入您的 catch 块中
  • 您是否尝试运行它并输入非整数?

标签: java


【解决方案1】:

请改用 input.nextLine() 并将其解析为字符串。

为避免 ParseException,请使用 try { ... } catch() { ... } 块将其包围。

在 catch 块中,您可以例如打印一条消息,通知用户输入错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    相关资源
    最近更新 更多