I have written a program to accept data of two student, but when I run this code the 'name' part is skipped the second time and it start from subjects and gives NameformatException? First run of code is normal but when it goes for second run the name part is skipped and I have to directly enter the Integer value and if I don't I get NumberFormatException.
import java.util.Scanner;
@SuppressWarnings("serial")
class NegativeValueException extends Exception {
public NegativeValueException() {
}
}
@SuppressWarnings("serial")
class ValueOutOfRange extends Exception{
public ValueOutOfRange() {
System.out.println("Value out of range Exception");
}
}
public class Student1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for(int i=0;i<2;i++) {
String[] name = new String[2];
int sub1=0;
int sub2=0;
int sub3=0;
double avg;
try {
System.out.println("Enter the data of Student "+(i+1)+" : ");
name[i] = sc.nextLine();
if(name[i].equals(null))
break;
else
if(sc.hasNextInt())
sub1=sc.nextInt();
else
throw new NumberFormatException();
if(sc.hasNextInt())
sub2=sc.nextInt();
else
throw new NumberFormatException();
if(sc.hasNextInt())
sub3=sc.nextInt();
else
throw new NumberFormatException();
if(sub1<0)throw new NegativeValueException();
if(sub1>100)throw new ValueOutOfRange();
if(sub2<0)throw new NegativeValueException();
if(sub2>100)throw new ValueOutOfRange();
if(sub3<0)throw new NegativeValueException();
if(sub3>100)throw new ValueOutOfRange();
avg = (sub1+sub2+sub3)/3;
System.out.println("Name : "+name[i]);
System.out.println("Marks in subject 1 : "+sub1);
System.out.println("Marks in subject 2 : "+sub2);
System.out.println("Marks in subject 3 : "+sub3);
System.out.println("Average Marks : "+avg);
}catch(NumberFormatException e) {
System.out.println(e);
}catch(NegativeValueException e) {
System.out.println(e);
}catch(ValueOutOfRange e) {
System.out.println(e);
}
}
sc.close();
}
}