java - Accepting multiple integers on a single line using Scanner -
java - Accepting multiple integers on a single line using Scanner -
the user needs come in number of integers. rather them come in integer @ time, want create can come in multiple integers on single line, want integers converted in array. example, if user enters: 56 83 12 99
want array created {56, 83, 12, 99}
in other languages python or ruby utilize .split(" ")
method accomplish this. no such thing exist in java knowledge. advice on how take user input , create array based on that, on single line?
using scanner.nextint()
method trick:
input:
56 83 12 99
code:
import java.util.scanner; class illustration { public static void main(string[] args) { scanner sc = new scanner(system.in); int[] numbers = new int[4]; for(int = 0; < 4; ++i) { numbers[i] = sc.nextint(); } } }
at @user1803551's request on how scanner.hasnext()
can accomplish this:
import java.util.*; class example2 { public static void main(string[] args) { scanner sc = new scanner(system.in); arraylist<integer> numbers = new arraylist<integer>(); while (sc.hasnextint()) { // loop breaks there no more int input. numbers.add(sc.nextint()); } } }
java string java.util.scanner
Comments
Post a Comment