I have the following code, I am suppose to give the input though system.in, however, the program skit the frist input, but it reads the secod one, it skips the 3rd input but it reads the forth one and so on. I can not figure out the problem. here is my code:
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());
}
}
}
so here is my input and the output:
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}
can some one please explain to me what is going wrong?
I fixed the problem, the issue was according to the comments that I was using sc.nextLine() twice inside the loop and thats why it would miss the 1st input and read the second one.
the new correct code is this and it works just fine, so thank you guys.
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());
}
}