【发布时间】:2017-12-04 08:10:39
【问题描述】:
尝试使用允许交换任意两个字符的命令行参数编写一个名为SwapChars.java 的程序。例如,如果程序被称为SwapChars,那么要交换文件test.txt中的所有‘a’和‘b’,我们将输入
java SwapChars test.txt ab
我输入了以下代码,它一直给我一个异常错误,我不确定我哪里出错了......
import java.util.*;
import java.io.*;
public class SwapChars {
public static void main(String[] args) throws IOException {
String a = args[0]; //file name (test.txt entered into command line)
FileReader fr = new FileReader(a);
String b = args[1];//which characters to swap
int t = fr.read();
while(t!=-1)
{
if(t==b.charAt(0))
{
System.out.println(b.charAt(1));
}
else if(t==b.charAt(1))
{
System.out.println(b.charAt(0));
}
else
{
System.out.println((char)t);
}
t=fr.read();
}
// TODO Auto-generated method stub
}
}
异常错误如下:
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at SwapChars.main(SwapChars.java:7)
当我更改代码以消除对以下命令的需求时,我可以获得所需的输出:
import java.util.*;
import java.io.*;
public class SwapCharsTest {
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("test.txt");
String swap = "ab";
int t = fr.read();
while(t!=-1)
{
if(t==swap.charAt(0))
{
System.out.print(swap.charAt(1));
}
else if(t==swap.charAt(1))
{
System.out.print(swap.charAt(0));
}
else
{
System.out.print((char)t);
}
t=fr.read();
}
// TODO Auto-generated method stub
}
}
【问题讨论】:
-
你遇到了什么错误?
-
"...一直给我一个例外..." - 您是否有理由从您的问题中省略了例外?请edit您的帖子并添加完整的堆栈跟踪,包括所有 Caused By 部分(如果有),并识别代码中引发异常的语句。
-
不要使用大引号格式化堆栈跟踪 -- 使用代码格式化
-
你认为
java.io.FileNotFoundException是什么意思? -
抱歉,“更改此程序使其不接收命令” 没有意义。 @Stefan 的回答是正确的,并且还指出了您代码中的另外两个问题。
标签: java file command-line