java - 从txt文件整数读取和打印java
问题描述
我编写了下面的代码,以便从文本文件中读取一些整数,然后在我将值 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。
解决了
解答: 问题在于编码 UTF-8。我应该留下文件 ANSI。我不知道为什么我正在阅读/练习的示例提倡这一点..
解决方案
尝试这个
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 + " ");
}
推荐阅读
- javascript - 检测是否安装了 WhatsApp
- node-red - 节点红色 - 如何使用按钮停止 Bash 节点
- r - 如何在 r 中使用 ggplot2 包进行绘图
- here-api - 航点航向仅适用于第一个航点
- python - 如何强制 Pandas“read_csv”函数保留空白值
- flutter - Flutter 有多个 floatingActionButtons
- pytorch - 试图用另一个相同维度的张量来掩盖张量,得到“索引 1 超出尺寸 1 的维度 0 的范围”
- javascript - 如何在 Sublime Text 3 中使用 JavaScript 增强插件
- node.js - REST url 返回错误或连接失败
- sql - 我从面试中解决这个 SQL 问题的方法正确吗?