我有以下代码,我应该通过 system.in 给出输入,但是,程序跳过第一个输入,但读取第二个输入,它跳过第三个输入,但读取第四个输入,所以在。我无法弄清楚问题所在。 这是我的代码:
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class problem1a {
private static HashMap<String,Integer> ales;
private static int counter = 0;
private static ArrayList<String> names;
private static ArrayList<String> city;
private static ArrayList<Integer> count;
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(System.in);
// initialize name,line variables
names = new ArrayList<String>();
ales = new HashMap<String,Integer>();
//store the names of the city and the corresponding student
while(sc.hasNextLine() ){
String s = removeNumbers(sc.nextLine());
Integer c = ales.get(s);
if(c == null){
ales.put(s, 1);
}
else{
ales.put(s, c.intValue() + 1);
}
if(sc.nextLine().equals(""))
break;
System.out.println(ales.toString());
}
}
}
这是我的输入和输出:
input: 3456345 Delft Jan
input: 435243 Delft Tim
{Delft Jan=1}
input: 54322 Delft Tim
input: 3453455 Delft Tim
{Delft Tim=1, Delft Jan=1}
input: 3456345 Delft Jan
input: 3456345 Delft Jan
{Delft Tim=1, Delft Jan=2}
有人可以向我解释一下出了什么问题吗?
我解决了这个问题,问题是根据我在循环内使用 sc.nextLine() 两次的评论,这就是为什么它会错过第一个输入并读取第二个输入。
新的正确代码是这样的,它工作得很好,所以谢谢你们。
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(System.in);
// initialize name,line variables
names = new ArrayList<String>();
ales = new HashMap<String,Integer>();
//store the names of the city and the corresponding student
while(sc.hasNextLine() ){
String s = removeNumbers(sc.nextLine());
Integer c = ales.get(s);
if(c == null){
ales.put(s, 1);
}
else{
ales.put(s, c.intValue() + 1);
}
if(s.equals(""))
break;
System.out.println(ales.toString());
}
}
最佳答案
那是因为您在循环内调用了 sc.nextLine()
两次。
每行应该只调用一次:
String nextLine = sc.nextLine();
String s = removeNumbers(nextLine);
...
if("".equals(nextLine)) {
break;
}
关于java - 扫描仪system.in,不读取第1、3、5等输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20048451/