扫描器,nextInt和InputMismatchException

编程入门 行业动态 更新时间:2024-10-24 21:20:15
本文介绍了扫描器,nextInt和InputMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图读取一个文本文件,然后使用Java中的nextInt()函数在循环中打印出整数。我的文本文件格式为: $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ d 5000 6

这里是我的代码:

public static void main(String [] args)throws FileNotFoundException { String fileSpecified = args [0] +.txt; FileReader fr = new FileReader(fileSpecified); BufferedReader br = new BufferedReader(fr); 扫描仪输入=新扫描仪(br); (in.hasNextLine()){ System.out.println(next int =+ in.nextInt()); while(in.hasNextLine $ / code $ / pre $ b $我得到的错误是:

pre $ 异常在线程mainjava.util.InputMismatchException $ b $在java.util.Scanner.throwFor(未知源)在java.util.Scanner.next(未知源)$ b $在java.util.Scanner.nextInt(未知源)$ b $在java.util.Scanner.nextInt(未知源)

每当我在任何程序中使用nextInt()时,都会得到这个错误。

while(in.hasNext)

()){ System.out.println(letter =+ in.next()); System.out.println(integer1 =+ in.nextInt()); System.out.println(integer2 =+ in.nextInt()); }

I'm trying to read a text file and then print out the integers in a loop using the nextInt() function in Java. The text file I have is of the form:

a 2000 2 b 3000 1 c 4000 5 d 5000 6

Here is my code:

public static void main(String[] args) throws FileNotFoundException { String fileSpecified = args[0] + ".txt"; FileReader fr = new FileReader(fileSpecified); BufferedReader br = new BufferedReader (fr); Scanner in = new Scanner (br); while (in.hasNextLine()) { System.out.println ("next int = " + in.nextInt()); } }

The error I always get is:

Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source)

I get this error everytime I use nextInt() in any program.

解决方案

You probably want something like this instead:

while (in.hasNext()) { System.out.println("letter = " + in.next()); System.out.println("integer1 = " + in.nextInt()); System.out.println("integer2 = " + in.nextInt()); }

更多推荐

扫描器,nextInt和InputMismatchException

本文发布于:2023-08-07 06:51:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1317593.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:扫描器   nextInt   InputMismatchException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!