所以我想有我计划能够接受两个参数:第一个是一个文本文件路径,第二个是一个整数表示有多少行希望看到的。
现在,我的代码可以用文本文件路径参数工作,但我不能去我的整数参数做出了第二种方法。
例如,我尝试运行我的程序是这样的:
运行读TEST.TXT 3
而且它打印在文本文件中,而不是3行,我希望它是一切。
任何帮助,将不胜感激!
import java.io.*;
import java.util.*;
public class Read{
public static void main(String[] args) throws FileNotFoundException{
String in = new String(args[0]);
String input = in;
if (Character.isDigit(in.charAt(in.length() - 1))){
hasNumInput(input);
}else onlyStrInput(input);
}
public static void onlyStrInput(String filename) throws FileNotFoundException{
File file = new File(filename);
Scanner inFile = new Scanner(file);
HashMap<String, Integer> map = new HashMap<>();
String input = "";
while (inFile.hasNext()){
input = inFile.next();
if (!map.containsKey(input)) map.put(input,1);
else map.put(input, map.get(input) + 1);
}
int index = 1;
while (!map.isEmpty()) {
int max = 0;
String maxP = "";
for (Map.Entry<String, Integer> stringIntegerEntry : map.entrySet()) {
Map.Entry entry = (Map.Entry) stringIntegerEntry;
String key = (String) entry.getKey();
Integer value = (Integer) entry.getValue();
//if equals, alphabetically
if (value == max) {
if (maxP.compareTo(key) > 0) {
max = value;
maxP = key;
}
}
if (value > max) {
max = value;
maxP = key;
}
}
System.out.println(index++ + ". " + maxP + " = " + map.get(maxP));
//pop out the max
map.remove(maxP);
}
}
public static void hasNumInput(String in) throws FileNotFoundException{
int indexSpace = in.indexOf(" ");
String strNum = in.substring(indexSpace + 1,in.length());
int num = Integer.parseInt(strNum);
String filename = in.substring(0,indexSpace);
File file = new File(filename);
Scanner inFile = new Scanner(file);
HashMap<String, Integer> map = new HashMap<>();
String input = "";
while (inFile.hasNext()){
input = inFile.next();
if (!map.containsKey(input)) map.put(input,1);
else map.put(input, map.get(input) + 1);
}
int index = 1;
while (!map.isEmpty() && num > 0) {
int max = 0;
String maxP = "";
for (Map.Entry<String, Integer> stringIntegerEntry : map.entrySet()) {
Map.Entry entry = (Map.Entry) stringIntegerEntry;
String key = (String) entry.getKey();
Integer value = (Integer) entry.getValue();
//if equals, alphabetically
if (value == max) {
if (maxP.compareTo(key) > 0) {
max = value;
maxP = key;
}
}
if (value > max) {
max = value;
maxP = key;
}
}
System.out.println(index++ + ". " + maxP + " = " + map.get(maxP));
//pop out the max
map.remove(maxP);
num--;
}
}
}
String[] args
不及格的一切args[0]
,而必须检查数组的长度,然后采取相应的行动。你的hasNumInput
方法应该采取一个int
参数(和当前String
)。就像是,
public static void hasNumInput(String in, int num) throws FileNotFoundException {
File file = new File(in);
Scanner inFile = new Scanner(file);
然后,你main
可能看起来像
public static void main(String[] args) throws FileNotFoundException {
if (args.length > 1) {
hasNumInput(args[0], Integer.parseInt(args[1]));
} else {
onlyStrInput(args[0]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句