【问题标题】:While loop and if statement troubleWhile循环和if语句的麻烦
【发布时间】:2013-04-17 22:09:32
【问题描述】:

当我在终端窗口中输入帐号时出现此错误

我输入的数据是正确的,我在account中输入了“ste251”之类的字符串,在balance中输入了一个int之类的500。

此外,当我尝试在抛出不匹配异常时停止循环时,我得到:

Java.util.inputMismatchException: null (in Java.util.scanner)

java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at WriteAccountBalances.writeToFile(WriteAccountBalances.java:58)

【问题讨论】:

  • 我很确定你之前已经问过这个问题了......
  • 真的需要帮助的人

标签: input while-loop try-catch


【解决方案1】:

来自the docs for InputMismatchException

由 Scanner 抛出以指示检索到的令牌与预期类型的​​模式不匹配,或者令牌超出预期类型的​​范围。

这几乎说明了所有需要说的。检查意外输入。

【讨论】:

    【解决方案2】:

    调用这些 nextInt() 或 next() 方法之一时,您会收到此错误,因为输入值与 next*() 方法的模式不匹配。尝试通过放置断点来调试您的代码,您会很容易发现。

    它应该继续询问帐号和余额,直到 用户输入大写 X

    这样写:

       while(true){
        //....
        //...
           System.out.print("Enter account number or X for exit: ");
            String option= myScanner.nextLine();
            if("X".equals(option)){
              break;
            }
            //....
           //...
        }
    

    PS: 千万不要用这种try/catch

      try {
            output.println(account + " " + balance);
        }
        catch (NullPointerException e)
        {
            System.out.println("PrintWriter is not assigned");
        }
    

    改为使用 if 语句检查:

    if(output!=null){
            output.println(account + " " + balance);
        }else{
            System.out.println("PrintWriter is not assigned");
        }
    

    【讨论】:

    • 真的很抱歉,但我很抱歉,这是完成的代码还是我是否适合我现有的代码,我不太明白你在做什么?
    • 这个比较笼统,你可以很容易地适应你的条件,更多地尝试谷歌搜索:)
    【解决方案3】:

    由于您的整个代码似乎不可用,因此像我这样的第三方进来并重建整个示例会很烦人。相反,由于这是一个微不足道的案例,我将为您提供一个类似的、完整且易于理解的示例,我已经碰巧拥有了。此代码以类似于您需要的方式输入;您应该能够根据您的具体要求对其进行修改。

    //Filename: "Hotel.java"
    import java.util.*;
    
    class Customer
    {
        private String name;
        private int room;
    
        public void setName(String name)
        {
            this.name=name;
        }
    
        public String getName()
        {
            return this.name;
        }
    
        public void setRoom(int room)
        {
            this.room=room;
        }
    
        public int getRoom()
        {
            return this.room;
        }
    }
    
    class Hotel
    {
        public static void initialize(Customer RoomList[])
        {
            for(int i=0; i<RoomList.length; i++)
            {
                RoomList[i]=new Customer();
                RoomList[i].setName("EMPTY");
                RoomList[i].setRoom(i+1);
            }
        }
    
        public static void viewList(Customer RoomList[])
        {
            for(int i=0; i<RoomList.length; i++)
            {
                if(RoomList[i].getName()=="EMPTY")
                    System.out.println("Room number "+RoomList[i].getRoom()+" is vacant.");
                else
                    System.out.println("Room number "+RoomList[i].getRoom()+" is ocupied by "+RoomList[i].getName()+".");
            }
            System.out.println();
        }
    
        public static boolean addCustomer(Customer RoomList[], String name)
        {
            for(int i=0; i<RoomList.length; i++)
                if(RoomList[i].getName().equals("EMPTY"))
                {
                    RoomList[i].setName(name);
                    return true;
                }
            return false;
        }
    
        public static void showEmptyRooms(Customer RoomList[])
        {
            System.out.println("Available rooms are:");
            for(int i=0; i<RoomList.length; i++)
                if(RoomList[i].getName()=="EMPTY")
                    System.out.println(RoomList[i].getRoom());
            System.out.println();
        }
    
        public static boolean deleteCustomer(Customer RoomList[], String name)
        {
            for(int i=0; i<RoomList.length; i++)
                if(RoomList[i].getName().equals(name))
                {
                    RoomList[i].setName("EMPTY");
                    System.out.println("Deletion successful.\n");
                    return true;
                }
            return false;
        }
    
        public static int getIndex(Customer RoomList[], String name)
        {
            for(int i=0; i<RoomList.length; i++)
                if(RoomList[i].getName().equals(name))
                    return i;
            return -1;
        }
    
        public static void main(String[] args)
        {
            Customer[] RoomList = new Customer[12];
            String name;
            initialize(RoomList);
            Scanner input = new Scanner(System.in);
            int option=0;
    
            do
            {
                System.out.println("        Hotel Booking Options");
                System.out.println("=====================================");
                System.out.println("1: To View all rooms");
                System.out.println("2: To Add customer to a room");
                System.out.println("3: To Display empty rooms");
                System.out.println("4: To Delete customer from a room");
                System.out.println("5: Find room from customer name");
                System.out.println("0: Exit");
    
                System.out.print("\nEnter your choice: ");
                option = input.nextInt();
                System.out.println();
    
                switch(option)
                {
                    case 1:
                    {
                        viewList(RoomList);
                        break;
                    }
                    case 2:
                    {
                        System.out.print("Customer's name: ");
                        name=input.next();
                        System.out.println();
                        if(!addCustomer(RoomList, name))
                            System.out.println("No rooms available!");
                        break;
                    }
                    case 3:
                    {
                        showEmptyRooms(RoomList);
                        break;
                    }
                    case 4:
                    {
                        System.out.print("Customer's name: ");
                        name=input.next();
                        System.out.println();
                        deleteCustomer(RoomList, name);
                        break;
                    }
                    case 5:
                    {
                        System.out.print("Customer's name: ");
                        name=input.next();
                        System.out.println();
                        System.out.println("Customer's room: "+RoomList[getIndex(RoomList, name)].getRoom()+"\n");
                        break;
                    }
                    case 0:
                    {
                        System.out.println("\nThank you!\n");
                        break;
                    }
                    default:
                    {
                        System.out.println("Invalid option!\n");
                        break;
                    }
                }
    
    
            }while(option!=0);
        }
    }
    

    编辑

    我试过你的代码;我不确定问题是什么,因为这对我来说似乎工作正常:

    //Filename: "myPrg.java"
    import java.util.*;
    
    class myPrg {
        static Scanner myScanner = new Scanner(System.in);
        static int count = 0;
    
        public static void writeToFile(String account, int balance) {
            while (!account.equals("X")) {
                System.out.print("Enter account balance: ");
                balance = myScanner.nextInt();
                try {
                    System.out.println(account + " " + balance);
                } catch (NullPointerException e) {
                    System.out.println("PrintWriter is not assigned");
                }
                count++;
                System.out.print("Enter account number: ");
                account = myScanner.next();
            }
        }
    
        public static void main(String[] args) {
            System.out.print("Enter account number: ");
            String account = myScanner.next();
            writeToFile(account, 0);
            System.out.println("Code terminated successfully!");
        }
    }
    

    这在终端中给了我以下信息:

    Enter account number: qwerty
    Enter account balance: 123
    qwerty 123
    Enter account number: asdfgh
    Enter account balance: 456
    asdfgh 456
    Enter account number: X
    Code terminated successfully!
    

    【讨论】:

    • 谢谢你,显然我是个新手
    • @user2292357:我已经编辑了我的答案。您的代码似乎运行良好;您可以查看我在下面附上的稍微修改过的版本。
    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 2013-06-09
    • 2016-01-12
    • 1970-01-01
    • 2012-06-18
    • 2015-05-19
    • 2015-03-09
    • 1970-01-01
    相关资源
    最近更新 更多