KaiquanMah's picture
Scanner reader = new Scanner(System.in);
5ce8dad verified
raw
history blame
2.83 kB
// use Scanner class
// to read user input
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
System.out.print("Input your name:");
Scanner reader = new Scanner(System.in);
String name = reader.nextLine();
System.out.println("Greetings, " + name);
}
}
Example output:
Input your name: Mike Madeup
Greetings, Mike Madeup
//eg2
// int in user input
//Integer.valueOf
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner reader= new Scanner(System.in);
System.out.print("Give the first number: ");
int first = Integer.valueOf(reader.nextLine());
System.out.print("Give the second number: ");
int second = Integer.valueOf(reader.nextLine());
int sum = first + second;
System.out.println("Sum: " + sum);
}
}
Example output:
Give the first number: 5
Give the second number: 11
Sum: 16
//eg3
//double in user input
//Double.valueOf
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Give the first number: ");
double first = Double.valueOf(reader.nextLine());
System.out.print("Give the second number: ");
double second = Double.valueOf(reader.nextLine());
System.out.print("Give the third number: ");
double third = Double.valueOf(reader.nextLine());
double average= (first + second + third) / 3;
System.out.println("Average: " + average);
}
}
Example output:
Give the first number: 2
Give the second number: 4.5
Give the third number: 7
Average: 4.5
"""
Write a program that asks the user to enter their name and then prints a welcome message to the user, as shown in the example below.
In the example, the user's input is given in bold. Note that the output must be exactly as shown in the example.
Input your name: Ethan Example
Welcome to the course, Ethan Example!!!
"""
import java.util.Random;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
final Random r = new Random();
Scanner reader = new Scanner(System.in);
System.out.print("Input your name: ");
String name = reader.nextLine();
System.out.println("Welcome to the course, " + name + "!!!");
}
}
"""output
Testing with input Ethan Example
Input your name: Ethan Example
Welcome to the course, Ethan Example!!!
Testing with input Niko Nonexistent
Input your name: Niko Nonexistent
Welcome to the course, Niko Nonexistent!!!
Testing with input Maddie Madeup
Input your name: Maddie Madeup
Welcome to the course, Maddie Madeup!!!
"""