Thursday, March 31, 2016

Getting User Inputs


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'

  1. Open the Eclipse
  2. 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.....)
  1. First it prints a line "Enter your first name..."
  2. Then user can input the name
  3. That input we take into computer by the scanner called 'scan'
  4. That input will save in the fname variable
  5. Then it  prints next line "Enter your second name..."
  6. Then user can input the second name
  7. That input we take into computer by the scanner called 'scan2'
  8. That input will save in the sname variable
  9. Finally it displays/prints "Your name is DavidMiller" or whatever the name is.





No comments:

Post a Comment