【问题标题】:reading and printing from txt file integers java [duplicate]从txt文件整数读取和打印java [重复]
【发布时间】:2018-12-15 19:58:03
【问题描述】:

我编写了下面的代码,以便从文本文件中读取一些整数,然后在我将值 10 添加到每个整数之后,在新的 txt 中打印每个整数。 "-1" int 作为指针显示结束。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class SmallChallengeCh {
    public static void main(String[] args){
        Scanner in = null;
        PrintWriter pw = null;
        try{
            File f = new File("C:\\Users\\paioa\\primlnl.txt");
            in  = new Scanner(f);
            pw = new PrintWriter(new FileOutputStream("C:\\Users\\paioa\\primOut.txt"),true);

            int num = in.nextInt();
            while(num != -1 ){
                num = num + 10;
                System.out.print(num + " ");
                pw.print(num + " ");
                num = in.nextInt();
            }
        }catch(FileNotFoundException e1){
            System.out.println("The file does not exist");
        }finally {
            try{
                if(in != null) in.close(); else throw new Exception("NULL");
                if(pw != null) pw.close();else throw new Exception("NULL");
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
    }
}

但是我收到以下错误

**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 gr.aueb.elearn.ch6.SmallChallengeCh.main(SmallChallengeCh.java:18)
Process finished with exit code 1**

但我不明白为什么。 inputmismatchexception 是由于我的文件可能不包含整数,但这不是真的,这里是 txt。

Input of txt file, also saved with coding UTF-8


已解决

回答:问题在于编码 UTF-8。我应该留下文件 ANSI。我不知道为什么我正在阅读/练习的示例提倡这一点..

【问题讨论】:

  • 失败的次数是多少?或者,在出错之前打印了多少个数字?
  • 这段代码对我来说工作正常,没有任何问题输出19 18 20
  • 我刚刚根据您的输入运行了这段代码,它运行良好。请edit您的问题提供有关如何重现您的问题的更多信息。
  • @AKSW 它不会在控制台中打印任何数字。只需在我在代码中给出的路径上创建一个空白的 primOut.txt。

标签: java exception text readfile


【解决方案1】:

试试这个

int num;
while(in.hasNextInt()){
    num = in.nextInt();
    num = num + 10;
    System.out.print(num + " ");
    pw.print(num + " ");
}

如果您只想读取“-1”之前的整数,则必须执行类似的操作

int num;
while(in.hasNextInt()){
    num = in.nextInt();
    if(num == -1)
        break;
    num = num + 10;
    System.out.print(num + " ");
    pw.print(num + " ");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多