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

我的扫描仪出现问题,这是我需要它来“重置”无效字符。

我的代码:

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”这样的无效字符上“重置”,因为Scanner仅接受数字。

谢谢您的帮助!

最佳答案

如果我对您的理解正确,那么这就是您要寻找的东西,
如果用户输入无效字符而不是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();
            }

        }

    }
}


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

09-29 21:06