![](/img/trans.png)
[英]Running Java program with jar file (Netbeans/Maven) - help needed
[英]Needed help loading in a file into a java program
我正在尝试加载名为Tut16_ReadText.txt的文件,并使其在程序中运行以输出是否沉重的内容。
我收到下面粘贴的错误。 我无法使该程序正常运行。 谁能解释我要使此程序正常工作必须做什么?
谢谢,
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class test1 {
public static void main(String args[]) throws Exception {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText file1");
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("F:/Programming/Java/Week16/Tut16_ReadText.txt"));
String sCurrentLine;
int totalwords = 0, totalchar = 0;
while ((sCurrentLine = br.readLine()) != null) {
String words[] = sCurrentLine.split(" ");
totalwords += words.length;
for (int j = 0; j < words.length; j++) {
totalchar += words[j].length();
}
}
double density = (1.0 * totalchar) / totalwords;
if (totalchar > 0) {
System.out.print(args[0] + " : " + density + " : ");
if (density > 6.0)
System.out.println("heavy");
else
System.out.println("light");
} else
System.out.println("This is an error - denisty of zero.");
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
用法:Tut16_ReadText file1线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:在test1.main处为0(test1.java:28)
您正在尝试访问不存在的数组'args'的索引。
这行:
System.out.print(args[0] + " : " + density + " : ");
正在访问运行程序时需要提供的args [0]。
尝试使用
java test1 yourinputparameter
要运行该程序,它应该可以工作。
也; 在程序开始的这些行中:
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText file1");
}
您应该添加一个
System.exit(0);
因此,如果输入的参数数量不正确,则程序的其余部分将不会运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.