java - 我需要 Java 扫描仪 'reset' 修复无效字符

标签 java

我是一个学习编码的新人!

我的扫描仪有问题,我需要它在无效字符上“重置”。

我的代码:

public class Lemonade {

static int m = 150;
private static Scanner scan;

public static void main(String[] args) {

    int day = 1;

    for(int gameover = m; gameover > 0; day++) {
    int Random = (int) (Math.random() * 100);
    if(Random <= 25) {
        System.out.println("Great Chance!");
        System.out.println("--------------------------------");
    }
    else if(Random <= 50) {
        System.out.println("Good Chance!");
        System.out.println("--------------------------------");
    }
    else if(Random <= 75) {
        System.out.println("Bad Chance!");
        System.out.println("--------------------------------");
    }
    else if(Random <= 100) {
        System.out.println("Awful Chance!");
        System.out.println("--------------------------------");
    }

    int count = 0;

    int none = 0;

    scan = new Scanner(System.in);

    System.out.println("Enter a number between 0 and " + m + "!");

    count = scan.nextInt();

    if(count >= none && count <= m) {
        System.out.println("You entered " + count + "!");
        System.out.println("--------------------------------");
        day = day + 1;
        m = m - count;
        System.out.println("Day " + day);
    }
    else {
        System.out.println("Enter a number between 0 and " + m + "."); 
        count = scan.nextInt();
    }

    }
}
}

现在我的问题是如何在“f”等无效字符上“重置”它,因为扫描仪只接受数字。

感谢您的帮助!

最佳答案

如果我理解正确的话,那么这就是您正在寻找的东西, 如果用户输入无效字符而不是 int,则会抛出 InputMismatchException。您可以使用循环,直到用户输入整数

import java.util.Scanner;
import java.util.InputMismatchException;


class Example
{
    public static void main(String args[])
    {
        boolean isProcessed = false;
        Scanner input = new Scanner(System.in);
        int value = 0;
        while(!isProcessed)
        {

            try
            {
                value = input.nextInt();
        //example  we will now check for the range 0 - 150
        if(value < 0 || value > 150) {
            System.out.println("The value entered is either greater than 150 or may be lesser than 0");
        }
        else isProcessed = true; // If everything is ok, Then stop the loop
            }
            catch(InputMismatchException e)
            {
                System.out.print(e);
        input.next();
            }

        }

    }
}

如果这不是您要找的,请告诉我!

关于java - 我需要 Java 扫描仪 'reset' 修复无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45355699/

相关文章:

java - 安卓 : Black screen is coming after splash screen

java - maven 存储库扫描后从 jqassistant 获取注释

java - 在 Java 中抛出检查异常

java - 按特定规则对对象的 List<T> 进行排序?

java - android中的fbconnect在用户墙上发布评论

java - 我想在 TextView 中添加字符串

Java String - 查看一个字符串是否只包含数字和字符而不包含单词?

java - 使用java Spring在post方法中使用一个请求主体到不同的xml

java - 如何为具有不同属性的多个类调用过滤和排序方法?

java - java 中已弃用代码的替代方案?