2️⃣

5.2 Different Types of Input

Chapter Table of Contents

🔍
Ch. 5 Scanner

Section Table of Contents

 
As you have already learned, Strings are not the only data type in Java. What do we do if we want to get a number from the user? Well, Scanner has other methods besides nextLine() which help you to read all different kinds of input.
As you can see from the code below, the nextDouble() and nextInt() methods allow you to read double and int from user input.
import java.util.Scanner; public class DifferentInput { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("What's your name? "); String name = reader.nextLine(); // nextline is for reading Strings Sysyem.out.print("What's the value of pi, as precisely as you can enter? "); double pi = reader.nextDouble(); // nextDouble is for reading doubles System.out.print("What your favorite integer? "); int favoriteInteger = reader.nextInt(); // nextIint is for reading ints System.out.println("Name: " + name); System.out.println("Pi: + pi); System.out.println("Favorite integer: " + favoriteInteger); } }
 
You can look at other Scanner methods to read even more data types
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.