【发布时间】:2018-07-08 17:57:30
【问题描述】:
对于以下问题,我无法通过命令行将文件解析为输入。
考虑两个关于学生的文件,分别包含他们的姓名和密码,以及姓名和电子邮件地址。有人可能希望将这些组合起来以得到一个包含姓名、电子邮件和密码的文件(按字母顺序)。
输入将通过 STDIN 输入,格式如下:
NUMBER OF RECORDS
NAME1 FIELD1
NAME2 FIELD1
...
NAMEN FIELD1
NAME1 FIELD2
NAME2 FIELD2
...
NAMEN FIELD2
您的输出应采用以下形式:
NAME1' FIELD1 FIELD2
NAME2' FIELD1 FIELD2
...
NAMEN' FIELD1 FIELD2
输出的排序位置(因此是 ')。 因此,例如,给定以下输入:
3
a 1
c 2
b 3
b 4
c 5
a 6
您的程序应提供以下输出:
a 1 6
b 3 4
c 2 5
我的代码如下:
import java.util.*;
import java.io.*;
public class Combiner
{
public static void main(String[] args) throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
Scanner scanner = new Scanner(System.in);
//first line number of students
int numOfStudents = scanner.nextInt();
scanner.nextLine();
// ins1 is the array of inputs of name and UN
String[] ins1 = new String[numOfStudents];
//ins2 is the array of inputs of name and Password
String[] ins2 = new String[numOfStudents];
//collect all inputs of Student Name, UN
for (int i = 0; i < numOfStudents; i++)
{
ins1[i] = stdin.readLine();
}
//collect all inputs of Student Name, Password
for (int i = 0; i<numOfStudents; i++)
{
ins2[i] = stdin.readLine();
}
//sort both arrays
Arrays.sort(ins1);
Arrays.sort(ins2);
for(int i =0; i<numOfStudents; i++)
{
//gets the last word from each element of ins2
String toAdd = getLast(ins2[i]);
//concats that to each element of ins 1
ins1[i]= ins1[i] + " " + toAdd;
}
//print the result
for(int i =0; i<numOfStudents; i++)
{
System.out.println(ins1[i]);
}
}
public static String getLast(String x)
{
//splits x into an array of words seperated by a space
String[] split = x.split(" ");
//gets the last element in that array
String lastWord = split[split.length - 1];
return lastWord;
}
}
当我从命令行输入时,我得到了所需的输出。但是当我使用对诸如 C:\Users\Stephen\Documents\3 之类的文件的引用时,它只是一个包含
的文件3
a 1
c 2
b 3
b 4
c 5
a 6
抛出异常
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.ThrowFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Combiner.main(Combiner.java.10)
第 10 行是
int numOfStudents = scanner.nextInt();
我不知道它有什么问题,当通过我的 IDE 控制台或命令行单独添加每一行时它会起作用
【问题讨论】:
-
你确定 3 是输入文件中的第一件事吗?它之前没有任何新行或空格吗?
-
是的,我在尝试使用的每个文件上都遇到了同样的错误,包括讲师提供的文件
-
然后使用 nextLine() 并打印出你得到的东西。我怀疑这是一个数字。看看它是什么,这应该可以帮助你弄清楚你从第一行的文件中得到了什么
-
你曾经在课堂上使用过哈希集和/或数组列表吗?因为 HashSet
> 的数据结构将是一个很好的数据结构来表示您正在解析和存储的输入 -
为什么要使用扫描仪?如果您使用“stdin”读取第一行,它的表现是否更好(从文件中读取)?使用: int numOfStudents = Integer.valueOf(stdin.readLine()).intValue();
标签: java file parsing command-line command