英文:
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("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");
		}
	}
}
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("enter a number to compare with number 5 ");
    Scanner s = new Scanner(System.in);
    String userInput = s.nextLine();
    try {
        int option = Integer.parseInt(userInput);
        if (option == 2)
        {
            System.out.println("U Have Entered The same value");
        }
        else if (option < 2)
        {
            System.out.println("Ur number is Smaller than 2");
        }
        else if (option > 2)
        {
            System.out.println("U Have Entered the number Greater than 2");
        }
    } catch (NumberFormatException e) {
        System.out.println("Invalid input!");
    }
}
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("enter a number to compare with number 5: ");
        int userInput = getInteger();
        if (userInput == 2)
        {
            System.out.println("U Have Entered The same value");
        }
        else if (userInput < 2)
        {
            System.out.println("Ur number is Smaller than 2");
        }
        else {
            System.out.println("U Have Entered the number Greater than 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("Incorrect input");
                System.out.println("Please try again: ");
            } 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 = "";    // Used to store User input:
// User Prompt with 'quit' capability and entry validation:
while (val.isEmpty()) {
System.out.print("Enter a number to compare with number 5 (q to quit): -> ");
val = input.nextLine().trim(); // Trim in case just a whitespace(s) was entered.
// Was 'q' for quit supplied?
if (val.equalsIgnoreCase("q")) {
/* Yes...then quit. Returning out of main() effectively 
closes this particular application:             */
System.out.println("Quiting - Bye Bye");
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("-?\\d+") || (Long.parseLong(val) < Integer.MIN_VALUE) || 
(Long.parseLong(val) > Integer.MAX_VALUE)) {
// No...Inform User and allow to try again:
System.out.println("Invalid Numerical Entry! {" + val + ") Try again..." 
+ System.lineSeparator());
val = "";   // 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("You have entered The same value.");
}
// Less Than:
else if (a < 5) {
System.out.println("Your number is smaller than 5.");
}
// Greater Than:
else {
System.out.println("You have entered a number greater than 5.");
}
// DONE
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论