'Scanning multiple lines using single scanner object
I a newbie to java so please don't rate down if this sounds absolute dumb to you
ok how do I enter this using a single scanner object
5
hello how do you do
welcome to my world
6 7
for those of you who suggest
scannerobj.nextInt->nextLine->nextLine->nextInt->nextInt,,,
check it out, it does not work!!!
thanks
Solution 1:[1]
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Please specify how many lines you want to enter: ");
String[] input = new String[in.nextInt()];
in.nextLine(); //consuming the <enter> from input above
for (int i = 0; i < input.length; i++) {
input[i] = in.nextLine();
}
System.out.printf("\nYour input:\n");
for (String s : input) {
System.out.println(s);
}
}
Sample execution:
Please specify how many lines you want to enter: 3
Line1
Line2
Line3
Your input:
Line1
Line2
Line3
Solution 2:[2]
public class Sol{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Solution 3:[3]
By default, the scanner uses space as a delimiter. In order to scan by lines using forEachRemaining, change the scanner delimiter to line as below.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
scanner.forEachRemaining(System.out::println);
}
Solution 4:[4]
try this code
Scanner in = new Scanner(System.in);
System.out.printf("xxxxxxxxxxxxxxx ");
String[] input = new String[in.nextInt()];
for (int i = 0; i < input.length; i++) {
input[i] = in.nextLine();
}
for (String s : input) {
System.out.println(s);
}
Solution 5:[5]
You can try only with lambda too:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.forEachRemaining(input -> System.out.println(input));
}
Solution 6:[6]
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int first = console.nextInt();
String second = console.nextLine();
String third = console.nextLine();
int fourth = console.nextInt();
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println(fourth);
}
so you get them in line by line
Solution 7:[7]
may be we can use this approach:
for(int i = 0; i < n; i++)
{
Scanner sc1 = new Scanner(System.in);
str0[i] = sc1.nextLine();
System.out.println(str0[i]);
}
that is we create the scanner object every time before we read the nextLine. :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ifloop |
Solution 2 | |
Solution 3 | |
Solution 4 | Jay kumar |
Solution 5 | Jouberto Fonseca |
Solution 6 | Ignatiy Kruglov |
Solution 7 | Sudarshan |