In: Computer Science
Hi I am quite confused with how to use scanner for my java project? Can someone help me with this? Thanks
/* BELOW DOWN IS SIMPLE PROGRAM WHICH USE SCANNER CLASS TO INPUT STRING AND INTEGER */
import java.util.Scanner; // FIRST IMPORT THIS CLASS
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // DECLARE ITS OBJECT
System.out.print("Enter name: ");
String name = sc.nextLine(); // FOR STRING INPUT USE .nextLine()
method
System.out.print("Enter first Integer: ");
sc = new Scanner(System.in); // to clear buffer
int a = sc.nextInt(); // for integer input use .nextInt()
input
System.out.print("Enter second Integer: ");
sc = new Scanner(System.in);
int b = sc.nextInt();
System.out.println("Sum is: "+ (a+b));
}
}
/* OUTPUT*/
/* TYPE OF INPUT YOU WANT YOU CAN CALL METHOD FROM SCANNER CLASS
FOR EG: TO TAKE CHARACTER INPUT USE .next() */'
/* THIS IS LIST OF VARIOUS METHOD */
import java.util.Scanner;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
// Initialize Scanner
object
Scanner scan = new
Scanner("Vince1;Gandhi;Albert");
// declare the delimiter to be used
by Scanner object
scan.useDelimiter(";");
/*Initialize the String
pattern which
signifies that the String token
contains
characters of the alphabet
only*/
Pattern pattern =
Pattern.compile("[A-Za-z]*");
while(scan.hasNext()){
// check if the
token consists of declared pattern
if(scan.hasNext(pattern)){
System.out.println(scan.next());
}
else
scan.next();
}
// closing the scanner
stream
scan.close();
}
}
/* YOU NEED PATTERN CLASS TO MATCH REGEX */