Java Scanner examples

Long live the Scanner class, a few examples for self-reference. 1. Read Input 1.1 Read input from the console. JavaScanner1.java package com.mkyong.io; import java.util.Scanner; public class JavaScanner1 { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Please enter your name: "); String input = scanner.nextLine(); System.out.println("name : " + input); …

Read more

Java – How to print a name 10 times?

This article shows you different ways to print a name ten times. 1. Looping 1.1 For loop JavaSample1.java package com.mkyong.samples; public class JavaSample1 { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println("Java "); } } } Output Java Java Java Java Java Java Java Java Java …

Read more

Java – How to read input from console using Scanner

This example shows you how to read input from the console using the standard java.util.Scanner class. JavaScanner.java package com.mkyong.io; import java.util.Scanner; public class JavaScanner { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Please enter your name: "); String input = scanner.nextLine(); System.out.println("name : " + input); System.out.print("Please enter your …

Read more

Java 8 Stream – Convert List<List<String>> to List<String>

As title, we can use flatMap to convert it. Java9Example1.java package com.mkyong.test; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class Java9Example1 { public static void main(String[] args) { List<String> numbers = Arrays.asList("1", "2", "A", "B", "C1D2E3"); List<List<String>> collect = numbers.stream() .map(x -> new Scanner(x).findAll("\\D+") .map(m -> m.group()) .collect(Collectors.toList()) ) .collect(Collectors.toList()); collect.forEach(x -> System.out.println(x)); …

Read more

How to get user input in Java

In Java, we can use java.util.Scanner to get user input from console. 1. Scanner 1.1 Read a line. UserInputExample1.java package com.mkyong; import java.util.Scanner; public class UserInputExample1 { public static void main(String[] args) { // auto close scanner try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter something : "); String input = scanner.nextLine(); // Read user …

Read more

Java – How to read input from the console

In Java, there are three ways to read input from a console : System.console (JDK 1.6) Scanner (JDK 1.5) BufferedReader + InputStreamReader (Classic) 1. System.console Since JDK 1.6, the developer starts to switch to the more simple and powerful java.io.Console class. JavaConsole.java package com.mkyong.io; import java.io.Console; public class JavaConsole { public static void main(String[] args) …

Read more