【问题标题】:Why do I get InputMismatchException in my Java programme?为什么我的 Java 程序中会出现 InputMismatchException?
【发布时间】:2017-12-04 17:54:13
【问题描述】:

我用 Java 制作了一只狗 kennel/pound,它正在工作(在 Eclipse 中)。但是当我测试它时,我得到了这个InputMismatchException。 我处理switch-statement 和案例的方式有问题吗?或者我的Scanner 的东西?该程序正在编译,所以我不明白。 作业中的要求之一是程序接受这些命令:

  • 注册新狗
  • 增加年龄
  • 列出狗
  • 移除狗
  • 退出

另一个要求是测试程序必须识别单词“Error”。 请帮帮我!!!

这里是 Dog 类:

import java.util.*;

public class Dog {

    private String dogName;
    private String dogRace;
    private int dogAge;
    private double dogWeight;

    public Dog(String name, String race, int age, double weight){
    this.dogName = name;
    this.dogRace = race;
    this.dogAge = age;
    this.dogWeight = weight;
    }

    public String getDogName (){ 
        return this.dogName;
    }
    public String getDogRace (){
        return this.dogRace;
    }
    public void birthday(){
        dogAge = dogAge+1;
    }
    public int getDogAge(){
        return this.dogAge;
    }
    public double getDogWeight(){
        return this.dogWeight;
    }
    public double getDogTailLength(){
        if (!getDogRace().equalsIgnoreCase("Tax"))
        if(!getDogRace().equalsIgnoreCase("Dachshund")){
            return ((dogAge * dogWeight)/ 10);

        }
        return 3.7;
    }

    public String toString(){
        return "Name: " + getDogName() + ", Race: " + getDogRace() + ", Age: " + getDogAge() + ", Weight: " + 
                getDogWeight() + ", Tail: " + getDogTailLength();

    }
}

这里是主类:

import java.util.*;

public class Main {

    public static Scanner scan = new Scanner(System.in);

    private ArrayList <Dog> dogList = new ArrayList<Dog>();

    public ArrayList<Dog> getDogList(){
        return this.dogList;
    }

    public String dogMenu(){
        return "Choose a commande below: \n1) Register new dog \n2) Increase age \n3) List dogs \n4)"
                    + " Remove dog \n5) Exit ";
    }
    public String error(){
        return "ERROR: please choose a number between 1-5";
    }
    public void addDog(){
        System.out.println("1- Enter the dogs name: ");
        String name = scan.next();
        System.out.println("2- Enter the dogs race: ");
        String race = scan.next();
        System.out.println("3- Enter the dogs age: ");
        int age = scan.nextInt();
        System.out.println("4- Enter the dogs weight: ");
        double weight = scan.nextDouble();
        Dog newDog = new Dog(name, race, age, weight);
        getDogList().add(newDog);
        System.out.println(newDog);

    }

    public void ageDog(){
        System.out.println("Which dog would you like to age? (State the name): ");
        String write = scan.next();
        for(Dog d: getDogList()){
            if(d.getDogName().equalsIgnoreCase(write)){
                d.birthday();
            }else{
                System.out.println("ERROR: The dog doesn't exist in the kennel");

            }
        }
    }

    public void dogTail(){
        System.out.println("State the tail length: ");
        double dogTailLengthIn = scan.nextDouble();
        for(Dog d1: getDogList()){ 
            if(d1.getDogTailLength()>= dogTailLengthIn){
                System.out.println(d1);
            }
        }
        if(getDogList().isEmpty()){
            System.out.println("ERROR: There are no dogs!!!");

    }   

    }
    public void deleteDog(){
        System.out.println("Which dog do you want to delete? (State the name): ");
        String nameIn = scan.next();
        boolean delete = false; 
        for(int a = 0; a <getDogList().size();a++){
            if(getDogList().get(a).getDogName().equalsIgnoreCase(nameIn)){
                getDogList().remove(a);
                delete = true;
            }
        }
        if(delete){
            System.out.println("The dog " + nameIn + " is deleted from the register.");
        }else{
            System.out.println("The dog " + nameIn + " doesn't exist in the register.");
        }
    }
    public void exit(){
        System.out.println("Thank you. Hope to see you soon!");
        scan.close();
        System.exit(0);
    }
    public static void main(String[] args){

        /*      Dog betty = new Dog("pudel", "Betty", 4, 22, 1.5); 

        Dog jonte = new Dog("rotweiler", "Jontis", 8, 60, 2);

        Dog jonas = new Dog("chihuahua", "Jonis", 2, 5, 0.3);*/

        Main kennel = new Main();

        while (true){ 
            System.out.print(kennel.dogMenu());
            int write = scan.nextInt();

            switch(write){

            case 1: 
                kennel.addDog();
                break; 

            case 2:
                kennel.ageDog();
                break;

            case 3:
                kennel.dogTail();
                break;

            case 4:
                kennel.deleteDog();
                break;

            case 5:
                kennel.exit();
            default: 
                System.out.println(kennel.error());
            }
        }
    }
}

问题来了:

Choose a commande below:
1) Register new dog
2) Increase age
3) List dogs
4) Remove dog
5) Exit

[IN:wrong command]
    java.util.concurrent.TimeoutException [LOOKING FOR: Any of [[fel case insensitive], [error case insensitive]]]
    [ERR: Exception in thread "main" java.util.InputMismatchException
      at java.util.Scanner.throwFor(Scanner.java:864)
      at java.util.Scanner.next(Scanner.java:1485)
      at java.util.Scanner.nextInt(Scanner.java:2117)
      at java.util.Scanner.nextInt(Scanner.java:2076)
      at Main.main(Main.java:96)]

我在每种情况下都得到了这个!

【问题讨论】:

  • 请将完整的堆栈跟踪添加到您的问题中,并指出是哪一行引发了异常。
  • 我真的很陌生...但是我在下面的评论中链接了一张图片!
  • 它给你的错误是什么输入?
  • 您是按字面意思输入“注册新狗”吗?
  • @rebecka544 这不是评论,而是答案,你不应该把你的问题放在任何一个地方。你需要edit你的问题来添加信息。另请记住,您的错误图片与您的错误不同。您需要将格式正确的文本粘贴到您的问题中,而不仅仅是一张图片。

标签: java eclipse methods switch-statement java.util.scanner


【解决方案1】:

您得到InputMismatchException,因为您正在输入String,但int write = scan.nextInt(); 期望来自userint 值,所以mismatchdatatype。如果您输入选项编号而不是 string,您的代码将正常工作,但您仍然需要为输入 Error 更改它

【讨论】:

  • 叫我笨蛋……但我不明白。:(我该怎么办??
  • 我没有看到有这个问题的代码。你能指出你在哪里看到的吗?
  • @isaace 在Main 类的main 方法中,程序在int write = scan.nextInt(); 行期待用户的integer input 只要用户的输入不是@987654334 @,它会给InputMismatchException,就像Error一样
  • @rebecka544 您还需要更改代码以处理 String 输入。使用`String write = scan.next();`并改变你的switch w.r.t逻辑。 String 输入。我建议使用BufferReader 而不是Scanner
【解决方案2】:

我的最佳猜测是,当 VPL 测试您的程序时,它会提供无效输入来测试您是否正确处理了无效输入。而你不是。

如果您已经了解了 trycatch 块,这将是实施这些知识并捕获错误以便正确处理它的好时机。

【讨论】:

  • 是的,我知道 try and catch,但不知道该放在哪里...我不太擅长这个,我是初学者...
  • try 块应包含可能导致错误的代码行(即包含scan.nextInt(); 的行)。 catch 块应该包含说明如果遇到错误该怎么办的代码。 (我假设您应该像在 default 案例中那样做 System.out.println(kennel.error());。)
【解决方案3】:

您收到 InputMismatchException 是因为您在 Main 类中向用户请求一个 int。检查您的 public static void main(String[] args) 中的以下行

int write = scan.nextInt();

如果您输入除整数以外的任何其他内容,它将引发异常。 您可以添加一个 try catch 块来处理不需要的输入。它应该如下所示。这将处理非整数的输入,并为用户提供选择正确输入的选项。

public static void main(String[] args) {
    Main kennel = new Main();
    while (true) {
        try {
            System.out.print(kennel.dogMenu() + "\n");
            int write = scan.nextInt();
            switch (write) {
            case 1:
                kennel.addDog();
                break;
            case 2:
                kennel.ageDog();
                break;
            case 3:
                kennel.dogTail();
                break;
            case 4:
                kennel.deleteDog();
                break;
            case 5:
                kennel.exit();
            default:
                System.out.println(kennel.error());
            }

        } catch (InputMismatchException e) {
            System.out.println(kennel.error());
            scan.nextLine();
        }
    }
}

我不确定,您所说的“另一个要求是测试程序必须识别“错误”一词。请帮助我!!!”是什么意思。如果您能提供更多意见,我可以尝试提供帮助。

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 2015-01-12
    • 2014-11-30
    • 2021-08-11
    • 2012-10-06
    • 2021-07-13
    相关资源
    最近更新 更多