关于 java:Scanner 异常 | 珊瑚贝

Scanner exception

1
2
3
4
5
6
7
8
9
10
11
12
public void menu()
 int option=0;
    Scanner b= new Scanner(System.in);
    while (true){

        System.out.println(“Your options is:”);

        option=b.nextInt();
        b.nextLine();
        if(option==1)
            add();
        else


我在我的 main 中调用了函数 add,它以应有的方式获取输入值,但是当它再次出现时,一切都崩溃了。

1
2
3
4
5
6
7
> public void add(){
>       int id;float grade; String name;
>       Scanner z= new Scanner(System.in);
>     //taking values for the 3 vars
>     Student s= new Student(id,name,grade);
>       c.addC(s);
>       z.close();}

addC 在 Ctrl 包中,它看起来有点像这样

1
2
3
4
5
6
7
8
  public void addC(Student s){
        if(findById(s.getId()) != null)
        {System.out.println(“Err!Duplicate id!/n”);
        }else
                if(s.getGrade()>10)
                        System.out.println(“Err!Grade bigger than 10!/n”);  
                else{  
                    x.push(s);}

push() 在那里是因为我尝试在堆栈上实现它。错误行是 option=b.nextInt() 我觉得这是我的错,但作为一个 java-starter 我无法自己弄清楚,有什么想法吗?

  • 你得到的例外是什么?
  • 仅给定随机的代码位,就很难看出发生了什么。最好发布一个 SSCCE,我们可以自己运行并查看错误。
  • Tenner 下注 NoSuchElementException。
  • 首先,您对大括号的使用非常令人讨厌:一次您将它们用于单行块,而另一次您不使用任何。为了尽量减少与此相关的错误,请使用一致的样式。其次,一堆变量没有定义或省略,例如c、x 等 – 所有这一切都让你很难理解你的代码实际上做了什么。
  • @Matt 您可以标记异常堆栈跟踪指示的行吗?


问题是你在同一个流上使用了两个扫描器:System.in.

另请参阅:如何在 System.in 上使用多个 Scanner 对象?

edit:是否可以重复使用第一个 Scanner?这样您就可以在适当的时候关闭扫描仪,而不是在第一个学生输入之后。

  • 我将扫描仪设为全局,问题已解决。谢谢


来源:https://www.codenong.com/19545912/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8795.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?