Java Keyboard example

This is a little Java program which asks user to input two numbers and prints the sum of the numbers. After that user enters two strings and the program checks if are the same. I suppose you know how to use this code but in case you don't just copy it to a file named demokeyboard.java , compile it (javac demokeyboard.java) and run it (java demokeyboard).

import java.util.Scanner;

class demokeyboard {
public static void main(String[] arg) {
//read from System.in = normally keyboard
Scanner keyboard = new Scanner(System.in);

System.out.print("Give two integers : ");
int x,y;
//read the two ints
System.out.println("You wrote "+x +" and "+y);
System.out.println("x plus y = "+(x+y));

System.out.print("\nGive a string : ");
//read two strings
String name=keyboard.nextLine();
name =keyboard.nextLine();
System.out.print("Give another string: ");
String name2 = keyboard.nextLine();
//compare the strings
if (name.equals(name2)) System.out.println("Same");
else System.out.println("Not Same");

No comments:

Related Posts Plugin for WordPress, Blogger...