Hello everyone,
I need some help understanding some concepts and possibly with my logic on this problem. We are supposed to create a program that asks users for their name, id, and grade average. The set is supposed to be where the exception is thrown. When the user enters their name and it is not a String it needs to throw an error via the try catch method. Same with the other values. I have listed my questions below and will comment out my code to give you an idea of where I am having issues. I really need help, but I by no means want it done for me. I am trying to understand the concepts, so I can understand this class( which I am having a lot of trouble with)
In order to test the student's name as to whether it is a string or not do I use and if statement or simply the try catch? I tried to do this from some examples I have seen floating around, but it is erroring out or returning the wrong output.
Would I use a if else like if its a string then it returns this message or just the try catch?
Can you use multiple try/ catch in one program?
Am I on the right track or completely off base in my code?
import java.util.Scanner;
public class tryCatchTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
studentInfo studentInfoObject = new studentInfo();
System.out.println("What is your name?");
String tempName = input.nextLine();
studentInfoObject.setName(tempName);
studentInfoObject.validName();
try {
int y = Integer.parseInt(tempName);
System.out.println(y);
}
catch(NumberFormatException e) {
System.out.println("Your name is not a valid. Please enter a string");
}
System.out.println("Please enter your id number:");
int tempId = input.nextInt();
studentInfoObject.setId(tempId);
studentInfoObject.validId();
try {
int x = Integer.parseInt(tempId);
System.out.println(x);
}
catch(NumberFormatException e) {
System.out.println("Your id is not a valid. Please enter an integer");
}
}
}
public class studentInfo {
private String studentName;
private int studentId;
private float gradeAvg;
public void setName(String name){
studentName = name;
}
public String getName(){
return studentName;
}
public void validName(){
System.out.printf("Your name is being validated %s", getName());
}
public void setId(int id){
studentId = id;
}
public int getId(){
return studentId;
}
public void validId(){
System.out.printf("Your id is being validated %s", getId());
}
public void setAverage(float average){
gradeAvg = average;
}
public float getAverage(){
return gradeAvg;
}
public void validAverage(){
System.out.printf("Your average is being validated %s", getAverage());
}
public studentInfo() {
}
}
please be gentle lol. I am an artist and coding is just not my forte, but my major requires it unfortunately. Thank you ahead of time for any help.