// ConsoleDemo.java
import java.io.Console;
public class ConsoleDemo
{
public static void main(String[] args) throws Exception
{
Console console = System.console();
if (console == null)
{
System.out.println("Unable to fetch console");
return;
}
System.out.print("Enter username:");
String user = console.readLine();
System.out.print("Enter password:");
char ch[] = console.readPassword();
String password = String.valueOf(ch);
System.out.println("Username: "+user);
System.out.println("Password:"+password);
}
}
Methods | Return |
---|---|
int nextInt() | It scans the next token of the input as an int. if the input is not an Integer it throws an exception. |
long nextLong() | It scans the next token of the input as a long value. |
float nextFloat() | It scans the next token of the input as a float value. |
double nextDouble() | It returns the next token as a double value. |
String next() | It returns the next complete token from the scanner as a string. |
String nextLine() | If the scanner has an input at another line, it returns true, otherwise false. |
boolean hasNextInt() | If the next token of the Scanner has an int value, it returns true. |
boolean hashNextFloat() | If the next token of the Scanner has a float value, it returns true. |
void close() | This method is used for close the Scanner. |
// ScannerDemo.java
import java.util.Scanner;
public class ScannerDemo
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = scn.nextInt();
System.out.print("Enter second number: ");
int b = scn.nextInt();
int result = a + b;
System.out.println("Sum of given number: "+result);
scn.close();
}
}