Java method not continuing past while loop -


when run code, lines after while loop never executed. i've done testing inside loop itself, , far can tell loop completing, method never moves on following line.

i aware there multiple similar topics, seem reference proper string comparisons , infinite loops.

example input be:

maria 1 2 3 4 

output should be:

maria's gpa 2.50. 

any appreciated.

public static void printgpa(){   scanner console = new scanner(system.in);    string studentname = "";   int counter = 0;   int gpa = 0;    system.out.print("enter student record: ");    while (console.hasnext()){     if (console.hasnextint()){       gpa += console.nextint();       counter += 1;     } else {       studentname = console.next();     }   }    system.out.print(studentname + "'s gpa ");   system.out.printf("%.2f.", ((double)gpa / (double)counter));       } 

while (console.hasnext()){ blocking call waits input. if stream not terminated assumed there more. system.in reads keyboard , stream should never closed , therefor "hasnext()" call wait indefinitely.

the fix this:

scanner sc = new scanner(system.in); system.out.print("enter student record: "); string str = sc.nextline(); stringtokenizer st = new stringtokenizer(str);  while (st.hasmoretokens()) {     string token = st.nexttoken();     // try parse token integer try-catch integer.parseint()     try {         int num = integer.parseint(token);         gpa += num;         counter++;     } catch (numberformatexception e) {         // if fails, assume it's name of student         studentname = token;     } }  // read single line , we're not asking how more there is. 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -