Question

sectionScan = new Scanner(wholeLine);
sectionScan.useDelimiter(",");

//Print each part of bat code
while (sectionScan.hasNext())
{
    System.out.println("\t" + sectionScan.next());
    score = sectionScan.next();

    if ("h".equals(score))
        hit++;
    else if ("o".equals(score))
        out++;
    else if ("w".equals(score))
        walk++;
    else if ("s".equals(score))
        sacrifice++;  
}

I am running the above code to scan line like this:
Willy Wonk,o,o,h,o,o,o,o,h,w,o,o,o,o,s,h,o,h

but it causes error unless I take out the System.out.println();

It's from one of my homework, it doesn't require me to have that error line, but I am just curious as to what cause it and how should I fix it?

Was it helpful?

Solution

when ever you use sectionScan.next(); , it will read the next one ,

you could get the temp String like this:

String temp=sectionScan.next();

and you could do what ever you want to do with that temp

another solution is that to use split method like this :

String []score=wholeLine.split(",");

so you have an array that splited by , so you can iterate trough that array like this:

for(String str:score){
        //do what ever you want to do with str
    }

OTHER TIPS

You are consuming the next element in your println.

System.out.println("\t" + sectionScan.next());

Instead store the next() value once and reuse it.

score = sectionScan.next();
System.out.println("\t" + score);

When you do the println you are actually invoking the next method twice, but you only check once, in the while condition, if there are elements left. So, per iteration you are retrieving two elements. Eventually, when there is only one element left, you get an exception in your second attempt to invoke the method next.

You should invoke the next method only once and cache the value in a variable, which you ca later use for any other purposes.

try changing it to

score = sectionScan.next();
System.out.println("\t" + score);

You are calling sectionscan.next() twice for every one time you check sectionscan.hasNext() which means you will eventually end up calling .next() when there is no next element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top