【发布时间】:2016-03-02 20:59:31
【问题描述】:
我正在为编程原理 1 做家庭作业,但我正在努力弄明白。
作业状态:
如果文件不存在,则编写一个程序来创建一个新文件(例如,名为 scaled.txt)(如果该文件存在,则终止您的程序而不做任何事情。)。将现有文件中的所有数字与整数(例如 original.txt)乘以 10,并将所有新数字保存在新文件中(例如 scaled.txt)。
例如,如果现有文件(original.txt)是:
26
12
4
89
54
65
12
65
74
3
那么新文件(scaled.txt)应该是:
260
120
40
890
540
650
120
650
740
30
这是我目前写的:
//Bronson Lane 11/28/15
//This program reads a file, multiplies the data in the file by 10, then exports that new data
//to a new file
package hw12;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class HW12Part2 {
public static void main(String[] args) throws Exception{
File file1 = new File("/Users/bronsonlane/Documents/workspace/hw12/original.rtf");
if (!file1.exists()) {
System.out.println("File does not exist");
System.exit(0);
}
int newNum = 0;
Scanner input = new Scanner(file1);
while (input.hasNextInt()) {
int num = input.nextInt();
newNum = num * 10;
}
PrintWriter output;
File file2 = new File("/Users/bronsonlane/Documents/workspace/hw12/scaled.rtf");
if (file2.exists()) {
System.exit(0);
}
output = new PrintWriter(file2);
while (input.hasNextInt()) {
int num = input.nextInt();
newNum = num * 10;
output.println(newNum);
}
output.close();
}
}
我现在的问题是控制台正在输出:
文件不存在
不管文件在那里。
我认为这是让它打印到新文件的最佳方法,但显然不是,因为它根本不起作用。
我知道我缺少一些完成该计划的关键要素,但我就是想不通。
*编辑 1:更新代码和新问题 *编辑2:Doh!我愚蠢地把错误的文件路径。一切正常,程序按预期运行。
【问题讨论】:
-
您应该说明您遇到的具体问题。它在输出什么吗?输出有问题吗?等
-
@Pushkin 啊,是的。谢谢你。我现在将编辑帖子。
-
调用
nextInt()时,你应该使用hasNextInt(),而不是hasNextLine()
标签: java java.util.scanner java-io printwriter