In this Post we're gonna learn how to get user inputs to our program. Ex :- When we are creating calculator you need to get inputs from the user.
OK Let's create a simple program to display your name using 'Scanners'
- Open the Eclipse
- Then let's code...
In here we're gonna import a package called 'util'. It has the this object called 'Scanner'. OK What is this Scanner ? It's really not like a scanner... it only allows the user to enter text into the computer as a String.
import java.util.*;
public class main {
public static void main(String []args){
System.out.println("Enter your first name...");
Scanner scan = new Scanner(System.in);
String fname = scan.nextLine();
System.out.println("Enter your second name...");
Scanner scan2 = new Scanner(System.in);
String sname = scan.nextLine();
System.out.println("Your name is " +fname + sname);
}
}
(Don't copy & paste this code, try understand and write it again for your best.....)
- First it prints a line "Enter your first name..."
- Then user can input the name
- That input we take into computer by the scanner called 'scan'
- That input will save in the fname variable
- Then it prints next line "Enter your second name..."
- Then user can input the second name
- That input we take into computer by the scanner called 'scan2'
- That input will save in the sname variable
- Finally it displays/prints "Your name is DavidMiller" or whatever the name is.
No comments:
Post a Comment