0

I have made a part of code where the user can enter some information to a class from the keyboard.

    Students newStudent = new Students(System.in); 
    System.out.println("Enter username");
    String username=newStudent.toString();
    System.out.println("Enter name");
    String name=newStudent.toString();
    System.out.println("Enter surname");
    String surname=newStudent.toString();
    System.out.println("Enter department name");
    String department=newStudent.toString();
    System.out.println("Enter registration number");
    String registrationNumber=newStudent.toString();
    System.out.println("Your information is:"+username + name + surname + department + registrationNumber);
    newStudent.close();

Now I want using the try-catch to check if the username,name,surname,dept name are strings and registration number is int but I can't seem to understand how try catch works.What should I write?

Natasa
  • 13
  • 6

1 Answers1

0

at first you've to read about try-catch blocks and how do they work you can find a lot of topics of this here !

I understand that you want to achieve validation using try-catch so you can do the following:-

int x;
Scanner sc=new Scanner(System.in);
try{
x=sc.nextInt();
}
catch(Exception e){
e.printStackTrace();
}

in the example above if the user entered a String an exception would be thrown immediately and if he entered the data type correctly (integer) the code will works fine

Jamal Alkelani
  • 606
  • 7
  • 19