Session 15
Session 15
Session 15
Input/Output
Input in Java
• Using Scanner Class
• Using BufferedReader Class
import java.util.Scanner; // Import the Scanner class
class MyClass
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String s = myObj.nextLine();
System.out.println("Username is: " + s);
}
}
import java.util.Scanner; // Import the Scanner class
class MyClass
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter a number");
Int i = myObj.nextInt();
System.out.println(“Number is: " + i);
}
}
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args)
{
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(“Name is “+ name);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args)
{
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
int x=Integer.parseInt(s);
System.out.println(“Value is “+ x);
}
}
Exception Handling
• Exception is a run-time error which arises during the execution of java
program
• An exception can occur for many different reasons, including the
following-
• A user has entered invalid data
• A file that needs to be opened cannot be found
• A network connection has been lost in the middle of communications
• JVM has run out of memory
Exception Handling