Missing last input in java -


with inputs such as; 1 2 3 4, arranged in column, code misses read last number. wrong? here code:

public static void main(string[] args) {     scanner sc = new scanner(system.in);     while(sc.hasnextint()){         system.out.println(sc.nextint());     }    sc.close(); } 

the problem 'sc.hasnextint()' since there isn't int after last entry, program not print it. if change call 'hasnextint()' 'hasnext()' code should work (as final newline character read).

you'll note following code has blank space @ end of input string. similar , use while sc.hasnext(). on other hand, structure code differently don't print based on existence of next character/int in input string.

import java.util.*;  public class scannerdemo {  public static void main(string[] args) {    string s = "hello world! 3 + 3.0 = 6 ";    // create new scanner specified string object   scanner scanner = new scanner(s);    while (scanner.hasnext()) {      // check if scanner's next token int      system.out.println("" + scanner.hasnextint());       // print scanned      system.out.println("" + scanner.next());   }    // close scanner   scanner.close();   } } 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -