尝试抓取扫描仪 [英] try catch for Scanner

查看:142
本文介绍了尝试抓取扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用扫描器来获取用户输入。如果用户输入一个名称,我将其添加到 ArrayList 中。如果用户没有输入名称,那么我想要抛出一个异常,但是我想继续循环得到答案。

I am using Scanner to get user input. If the user inputs a name, I add that to the ArrayList. If the user does not enter a name then I want to throw an exception, but I want to continue the loop that gets the answer.

for(int i = 0; i < totalLanes; i++){
    runArr.add(this.addRacer());
}

public static String addRacer() throws NullPointerException{
    System.out.print("Enter a name for a racer: ");//Method uses try catch to catch a    NullPointerException.   
    Scanner sc = new Scanner(System.in);
    String rName = null;
    try {            
        if(!sc.nextLine().isEmpty()){
            rName = sc.nextLine();
        }else{
            throw new NullPointerException("name cannot be blank");
        }
    }

    catch (NullPointerException e) {
        System.out.println(e.toString());
        System.out.print("Enter a name for a racer: ");
        addRacer();
    }
    return rName;
}




  • 为什么会无限次递归? >
  • 从用户那里获取输入的最佳方式是什么?
    确保输入有效数据?

  • 提前感谢

    推荐答案

    问题是您读取输入两次。
    我的意思是你的代码中有两个调用 sc.nextLine()方法。
    尝试这样做:

    The problem is that you read input twice. I mean you have two calls of sc.nextLine() method in your code. Try this instead:

    String rName = sc.nextLine();
    try {
        if(rName.isEmpty()){
            throw new NullPointerException("Name cannot be blank.");
        }
    }
    

    这篇关于尝试抓取扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆