如何检查if else条件中的else语句

huangapple go评论61阅读模式
英文:

how to check the else statement in if else condition

问题

package react;

import java.util.Scanner;

public class Intputfromuser {

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

        System.out.println("请输入一个数字,与数字5进行比较:");
        Scanner input = new Scanner(System.in);
        int a;
        
        if (input.hasNextInt()) {
            a = input.nextInt();
            if (a == 5) {
                System.out.println("您输入的与数字5相同。");
            } else if (a < 5) {
                System.out.println("您输入的数字小于5。");
            } else {
                System.out.println("您输入的数字大于5。");
            }
        } else {
            System.out.println("您输入了无效的内容,必须输入一个整数。");
        }
    }
}

请注意,我进行了一些修改,以确保仅在用户输入整数时才继续,否则会触发else语句。

英文:
package react;

import java.util.Scanner;

public class Intputfromuser {

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

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

	}
}

how to get only integer from the user if the user enters any thing except integer then else statement should run

答案1

得分: 0

使用input.nextLine()代替,并将其解析为一个字符串。

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

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

public static void main(String[] args) {
    System.out.println("输入一个数字以与数字5进行比较");

    Scanner s = new Scanner(System.in);

    String userInput = s.nextLine();

    try {
        int option = Integer.parseInt(userInput);

        if (option == 2)
        {
            System.out.println("您输入了相同的值");
        }
        else if (option < 2)
        {
            System.out.println("您的数字小于2");
        }
        else if (option > 2)
        {
            System.out.println("您输入了大于2的数字");
        }
    } catch (NumberFormatException e) {
        System.out.println("无效输入!");
    }
}

希望这有所帮助!

英文:

Use input.nextLine() instead and parse it to a String.

To avoid a ParseException, surround it by using a try { ... } catch() { ... } block.

In the catch block you can e.g. print a message informing the user of the wrong input.

public static void main(String[] args) {
    System.out.println(&quot;enter a number to compare with number 5 &quot;);

    Scanner s = new Scanner(System.in);

    String userInput = s.nextLine();

    try {
        int option = Integer.parseInt(userInput);

        if (option == 2)
        {
            System.out.println(&quot;U Have Entered The same value&quot;);
        }
        else if (option &lt; 2)
        {
            System.out.println(&quot;Ur number is Smaller than 2&quot;);
        }
        else if (option &gt; 2)
        {
            System.out.println(&quot;U Have Entered the number Greater than 2&quot;);
        }
    } catch (NumberFormatException e) {
        System.out.println(&quot;Invalid input!&quot;);
    }
}

Hope this sort of helped!

答案2

得分: 0

你还可以创建一个方法来收集输入并在循环中使用,就像这样:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.print("输入一个要与数字5比较的数字: ");

        int userInput = getInteger();


        if (userInput == 2)
        {
            System.out.println("您已输入相同的值");
        }
        else if (userInput < 2)
        {
            System.out.println("您的数字小于2");
        }
        else {
            System.out.println("您已输入大于2的数字");
        }
    }

    static int getInteger() {
        boolean correct = false;
        Scanner input = new Scanner(System.in);
        int userInput = 0;
        do {
            try {
                userInput = input.nextInt();
                correct = true;
            } catch (Exception e) {
                System.out.println("输入不正确");
                System.out.println("请再试一次: ");
            } finally {
                input.nextLine();
            }
        }
        while (!correct);
        input.close();
        return userInput;
    }
}

使用scanner.nextInt()scanner.nextDouble()时,需要在其后调用scanner.nextLine()来清除输入。否则,您将陷入无限循环。

英文:

You can also create method to collect input and make it inside loop like this:

   import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.print(&quot;enter a number to compare with number 5: &quot;);

        int userInput = getInteger();


        if (userInput == 2)
        {
            System.out.println(&quot;U Have Entered The same value&quot;);
        }
        else if (userInput &lt; 2)
        {
            System.out.println(&quot;Ur number is Smaller than 2&quot;);
        }
        else {
            System.out.println(&quot;U Have Entered the number Greater than 2&quot;);
        }
    }

    static int getInteger() {
        boolean correct = false;
        Scanner input = new Scanner(System.in);
        int userInput = 0;
        do {
            try {
                userInput = input.nextInt();
                correct = true;
            } catch (Exception e) {
                System.out.println(&quot;Incorrect input&quot;);
                System.out.println(&quot;Please try again: &quot;);
            } finally {
                input.nextLine();
            }
        }
        while (!correct);
        input.close();
        return userInput;
    }
}

Important note with scanner.nextInt() or scanner.nextDouble()
you need to call scanner.nextLine() after that to clear input. Otherwise you will end up with endless loop.

答案3

得分: 0

以下是翻译好的代码部分:

public static void main(String[] args) {
    /* 打开键盘输入流。无需关闭此流。
       当应用程序关闭时,JVM会自动关闭它。 */
    Scanner input = new Scanner(System.in);
    
    String val = "";    // 用于存储用户输入:
    // 用户提示,带有退出功能和输入验证:
    while (val.isEmpty()) {
        System.out.print("输入一个数字以与数字5进行比较 (输入q退出): -> ");
        val = input.nextLine().trim(); // 去除可能的空格。
        // 是否提供了 'q' 以退出?
        if (val.equalsIgnoreCase("q")) {
            /* 是的...然后退出。从main()中返回将有效地关闭这个特定的应用程序: */
            System.out.println("退出 - 再见");
            return;
        }
        // 验证输入:
        /* 输入是否是带符号或无符号整数的字符串表示,
           并且提供的值是否在int范围内? */
        if (!val.matches("-?\\d+") || (Long.parseLong(val) < Integer.MIN_VALUE) || 
                                      (Long.parseLong(val) > Integer.MAX_VALUE)) {
            // 否...通知用户并允许重试:
            System.out.println("无效的数字输入! {" + val + ") 请再试一次..." 
                               + System.lineSeparator());
            val = "";   // 清空变量以确保重新循环:
        }
    }
    
    // 如果代码执行到此点,用户输入是有效的!
    // 现在将字符串数值解析为int:
    int a = Integer.parseInt(val);
    
    /* 此时,只有三种可用条件:
       相等,小于和大于(有效性已在 `while` 循环中处理): */
    
    // 相等:
    if (a == 5) {
        System.out.println("您输入了相同的值。");
    }
    // 小于:
    else if (a < 5) {
        System.out.println("您的数字小于5。");
    }
    // 大于:
    else {
        System.out.println("您输入的数字大于5。");
    }
    // 完成
}

希望这对您有所帮助。如果您有任何其他问题,请随时提问。

英文:

Another alternative. Be sure to read the comments in code:

public static void main(String[] args) {
/* Open a keyboard input stream. There is no need to close 
this stream. The JVM will do that automatically when the
application closes.               */
Scanner input = new Scanner(System.in);
String val = &quot;&quot;;    // Used to store User input:
// User Prompt with &#39;quit&#39; capability and entry validation:
while (val.isEmpty()) {
System.out.print(&quot;Enter a number to compare with number 5 (q to quit): -&gt; &quot;);
val = input.nextLine().trim(); // Trim in case just a whitespace(s) was entered.
// Was &#39;q&#39; for quit supplied?
if (val.equalsIgnoreCase(&quot;q&quot;)) {
/* Yes...then quit. Returning out of main() effectively 
closes this particular application:             */
System.out.println(&quot;Quiting - Bye Bye&quot;);
return;
}
// Validate Entry:
/* Is entry a string representation of a signed or unsigned Integer 
value and does the supplied value fall within the relm of an int? */
if (!val.matches(&quot;-?\\d+&quot;) || (Long.parseLong(val) &lt; Integer.MIN_VALUE) || 
(Long.parseLong(val) &gt; Integer.MAX_VALUE)) {
// No...Inform User and allow to try again:
System.out.println(&quot;Invalid Numerical Entry! {&quot; + val + &quot;) Try again...&quot; 
+ System.lineSeparator());
val = &quot;&quot;;   // Empty variable to ensure re-loop:
}
}
// If you make it to this point in code, the User input was valid!
// Now parse the String numerical value to an int:
int a = Integer.parseInt(val);
/* At this point, there are only three usable conditions:
Equal To, Less Than, and Greater Than (validity has
already been handled within the `while` loop:     */
// Equal To:
if (a == 5) {
System.out.println(&quot;You have entered The same value.&quot;);
}
// Less Than:
else if (a &lt; 5) {
System.out.println(&quot;Your number is smaller than 5.&quot;);
}
// Greater Than:
else {
System.out.println(&quot;You have entered a number greater than 5.&quot;);
}
// DONE
}

huangapple
  • 本文由 发表于 2023年2月6日 17:51:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定