How do I fix a mismatch exception in Java? - java

I keep getting an error called "java.util.Mismatchexpection: null". I'm not sure how to fix this. It points to the grade = fileInput.nextInt(); line.
Here are the classes I'm using:
import java.util.Scanner;
import java.io.*;
public class Students
{
public static void printAllStudents(Student[] students){
for(int i=0;i<students.length;i++)
{
System.out.println(students[i]);
}
}
public static void printAllStudentsByFirstName(Student[] students,String firstName){
String name=firstName.split(" ")[1];
int len=name.length();
for (int i=0;i<students.length;i++){
try{
if(students[i].getFname().substring(0, len).equalsIgnoreCase(name)){
System.out.println(students[i]);
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
public static void printAllStudentsByLastName(Student[] students,String lastName){
String name=lastName.split(" ")[1];
int len = name.length();
for(int i=0;i<students.length;i++){
try{
if(students[i].getLname().substring(0, len).equalsIgnoreCase(name)){
System.out.println(students[i]);
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
public static void printAllStudentsByGrades(Student[] students,String interval){
int start=Integer.parseInt(interval.split(" ")[1]);
int end=Integer.parseInt(interval.split(" ")[2]);
for(int i=0;i<students.length;i++){
if(students[i].getGrade()>=start && students[i].getGrade()<=end){
System.out.println(students[i]);
}
}
}
public static void sort(Student[] students)
{
int n = students.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (students[i].getGrade() > students[k].getGrade())
{
Student temp=new Student();
temp = students[k];
students[k]=students[i];
students[i]=temp;
}
}
}
printAllStudents(students);
}
public static void main (String[] args) throws IOException
{
String first_name, last_name, line = "";
int grade, lines = 0, i;
char ch;
Scanner sc = new Scanner(System.in);
Scanner fileInput = new Scanner(new File("students.txt"));
//Counting the number of lines in the file.
while (fileInput.hasNext())
{
line = fileInput.next();
lines++;}
fileInput = new Scanner(new File("students.txt"));
//Declaring Student array of size lines.
Student[] students=new Student[lines];
i = 0;
while (fileInput.hasNext())
{
first_name = fileInput.nextLine();
last_name = fileInput.nextLine();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name, grade);
students[i++] = st;
}
System.out.println("Please choose from below operations: ");
System.out.println("1. printall");
System.out.println("2. firstname <name>");
System.out.println("3. lastname <name>");
System.out.println("4. interval m n");
System.out.println("5. sort");
System.out.println("6. end");
while (true)
{
System.out.println("Enter choice:");
String choice = sc.nextLine();
if(choice.equals("printall"))
printAllStudents(students);
else if(choice.indexOf("firstname")==0)
printAllStudentsByFirstName(students, choice);
else if(choice.indexOf("lastname") == 0)
printAllStudentsByLastName(students, choice);
else if(choice.indexOf("interval") == 0)
printAllStudentsByGrades(students, choice);
else if(choice.equals("sort"))
sort(students);
else if(choice.equals("end"))
break;
}
}
}
public class Student
{
private String fname, lname;
private int grade;
public Student()
{
super(); //gives us the ability to override
}
public Student (String fname, String lname, int grade)
{
this.fname = fname;
this.lname = lname;
this.grade = grade;
}
public String getFname() {
return fname;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String toString()
{
return fname + " " + lname + "\t" + grade;
}
}
Any help will be much appreciated.

A MismatchException is triggered when the Scanner runs into unexpected input. In your case, the Scanner is picking up null when it is expecting int input for fileInput.nextInt().
This has to do with the formatting of student.txt and how you're parsing it; try running the code in debug, step-by-step, in your IDE (if you're using one) to pinpoint how to fix your text-file parsing.

Related

Program only reading title of file and nothing else

My program is only reading the name of the file and none of the contents inside. I get an ElementDoesNotExist error every time. The file is in the same folder, and I have no idea why it won't read the contents. I understand that this program is inefficient, and it's my first time using File IO in Java.
import java.util.*;
import java.io.*;
public class Project4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the year: ");
int fileYear = input.nextInt();
String userFile = "";
if (fileYear == 2001)
{
userFile = "BabyNames2001.txt";
}
else if (fileYear == 2002)
{
userFile = "BabyNames2002.txt";
}
else if (fileYear == 2003)
{
userFile = "BabyNames2003.txt";
}
else if (fileYear == 2004)
{
userFile = "BabyNames2004.txt";
}
else if (fileYear == 2005)
{
userFile = "BabyNames2005.txt";
}
else if (fileYear == 2006)
{
userFile = "BabyNames2006.txt";
}
else if (fileYear == 2007)
{
userFile = "BabyNames2007.txt";
}
else if (fileYear == 2008)
{
userFile = "BabyNames2008.txt";
}
else if (fileYear == 2009)
{
userFile = "BabyNames2009.txt";
}
else if (fileYear == 2010)
{
userFile = "BabyNames2010.txt";
}
File theFile = new File(userFile);
ArrayList<BabyName> theBabies = loadNames("BabyNames2001.txt", fileYear);
System.out.print("Enter the gender: ");
String babyGender = input.next();
System.out.print("Enter the name: ");
String babyName = input.next();
findName(babyName, fileYear, theBabies);
}
private static ArrayList<BabyName> loadNames(String fileName, int checkYear)
{
ArrayList<BabyName> babies = new ArrayList<BabyName>();
int currentYear = checkYear;
String chooseFile = fileName;
Scanner reader = new Scanner(chooseFile);
while (reader.hasNext())
{
BabyName boy = new BabyName();
BabyName girl = new BabyName();
boy.setYear(currentYear);
girl.setYear(currentYear);
boy.setGender("M");
girl.setGender("F");
String currentRank = reader.next();
boy.setRank(currentRank);
String boyName = reader.next();
int boyTotal = reader.nextInt();
String girlName = reader.next();
int girlTotal = reader.nextInt();
girl.setRank(currentRank);
boy.setName(boyName);
girl.setName(girlName);
boy.setTotal(boyTotal);
girl.setTotal(girlTotal);
babies.add(boy);
babies.add(girl);
}
return babies;
}
private static BabyName findName(String name, int year, ArrayList<BabyName> babies)
{
ArrayList<BabyName> theBabies = babies;
BabyName tempBaby = new BabyName();
String findName = name;
int findYear = year;
for (int baby = 0; baby < 2000; baby++)
{
if (findName == theBabies.get(baby).getName())
{
tempBaby = theBabies.get(baby);
}
}
return tempBaby;
}
}
class BabyName
{
private String rank;
private int year;
private String name;
private String gender;
private int total;
BabyName()
{
}
public String getRank()
{
return rank;
}
public int getYear()
{
return year;
}
public String getName()
{
return name;
}
public String getGender()
{
return gender;
}
public int getTotal()
{
return total;
}
public void setRank(String newRank)
{
this.rank = newRank;
}
public void setYear(int newYear)
{
this.year = newYear;
}
public void setName(String newName)
{
this.name = newName;
}
public void setGender(String newGender)
{
this.gender = newGender;
}
public void setTotal(int newTotal)
{
this.total = newTotal;
}
}
Your problem is here:
Scanner reader = new Scanner(chooseFile);
The Scanner class has multiple overloaded constructors. chooseFile is a String, so you are calling Scanner(String) when what you probably want is Scanner(File). Because of this your code does not read any files, it is reading the literal string "BabyNames2001.txt".
The solution is to simply pass a File instead of a String, or something along the lines of:
Scanner reader = new Scanner(new File(chooseFile));

adding a else if function for resulting in passed or failed

I'm learning java language and I saw this code. I was wondering if I can add an if else condition that if the grade is below 80, it will print failed and else passed. Like.
System.out.print("Your Grade is ");
if(avg>80)
{
System.out.print("A");
I searched for other links but I can't find anything. I hope someone can help me. Thanks in advance.
import java.util.*;
public class UserInteraction {
public static void main(String[] args) {
UserChoiceManager userChoiceManager = new UserChoiceManager();
UserChoice choice = UserChoice.UNKNOWN;
do {
choice = userChoiceManager.manage();
} while (choice != UserChoice.EXIT);
System.out.println("Thank you for using the system!");
}
}
enum UserChoice {
UNKNOWN(0),
ENTER_SUBJECT(1),
DISPLAY_DATA(2),
CALCULATE_AVERAGE_GRADE(3),
EXIT(4);
private int id;
public int getId() {
return id;
}
UserChoice(int id) {
this.id = id;
}
public static UserChoice getById(int input) {
for (UserChoice value : UserChoice.values()) {
if (value.getId() == input) {
return value;
}
}
return UserChoice.UNKNOWN;
}
}
class Subject {
private String name;
private int grade;
public Subject(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
class UserChoiceManager {
private final static int SUBJECT_COUNT = 3;
private Subject[] subjects = new Subject[SUBJECT_COUNT];
private Scanner scan = new Scanner(System.in);
public UserChoiceManager() {
}
public UserChoice manage() {
System.out.println(printHelp());
UserChoice choice = getUserChoiceById(scan);
if (choice == UserChoice.ENTER_SUBJECT) {
choice = enterSubjects(choice);
}
if (choice == UserChoice.DISPLAY_DATA) {
printSubjectsAndGrades();
}
if (choice == UserChoice.CALCULATE_AVERAGE_GRADE) {
printAverageGrade();
}
return choice;
}
private static String printHelp() {
StringBuilder usage = new StringBuilder("\nUsage:\n");
usage.append(UserChoice.ENTER_SUBJECT.getId()).append(". Enter a subject name and a corresponding grade").append("\n");
usage.append(UserChoice.DISPLAY_DATA.getId()).append(". Display all grades").append("\n");
usage.append(UserChoice.CALCULATE_AVERAGE_GRADE.getId()).append(". Calculate the average grade").append("\n");
usage.append(UserChoice.EXIT.getId()).append(". Exit system");
return usage.toString();
}
private UserChoice getUserChoiceById(Scanner scan) {
return UserChoice.getById(scan.nextInt());
}
private UserChoice enterSubjects(UserChoice choice) {
System.out.println("Enter " + subjects.length + " subjects and their corresponding grades:");
System.out.println();
for (int i = 0; i < subjects.length; i++) {
String subjectName = scanSubjectName();
int grade = scanGrade();
subjects[i] = new Subject(subjectName.toLowerCase(), grade);
}
System.out.println("Thank you!");
System.out.println();
return choice;
}
private String scanSubjectName() {
Scanner temp = new Scanner(System.in);
String subjectName = "";
do {
System.out.println("Subject:");
subjectName = temp.nextLine();
if (subjectName.equals("")) {
System.out.println("Empty subject name! Try again.");
}
} while (subjectName.equals(""));
return subjectName;
}
private int scanGrade() {
int grade = 0;
do {
Scanner temp = new Scanner(System.in);
System.out.println("Grade:");
try {
grade = temp.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid grade. Enter numeric value! Try again.");
}
} while (grade == 0);
return grade;
}
private void printAverageGrade() {
System.out.println("Total of grades: " + getSum(subjects));
System.out.println("Count of grades: " + subjects.length);
System.out.println("Your average grade is: " + getAverage(subjects));
System.out.println();
}
private void printSubjectsAndGrades() {
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for (int p = 0; p < subjects.length; p++) {
System.out.println(subjects[p].getName() + "\t" + "\t" + subjects[p].getGrade());
}
}
public static double getAverage(Subject[] subjects) {
int sum = 0;
for (Subject s : subjects)
sum += s.getGrade();
return ((double) sum) / subjects.length;
}
public static double getSum(Subject[] subjects) {
int sum = 0;
for (Subject s : subjects) {
sum += s.getGrade();
}
return sum;
}
}
I tried adding some if functions in print out tag but it's not working.
Change your implementation of printAverageGrade to this, and the program will print out what you want:
private void printAverageGrade() {
System.out.println("Total of grades: " + getSum(subjects));
System.out.println("Count of grades: " + subjects.length);
double average = getAverage(subjects);
System.out.println("Your average grade is: " + average);
System.out.print("Your Grade is ");
if (average > 80) {
System.out.println("A");
} else {
System.out.println("Failed");
}
System.out.println();
}

how we can call the object of second call in the first class in java

here i have a code which i am giving u please correct my code and run it when i enter the extend or make object of attendence class in the student class then attendence class is not worked
import java.util.Scanner;
public class Attendence {
private int c;
public Attendence(){
}
public void project(){
System.out.println("Enter the total no of students of the class");
Scanner input=new Scanner(System.in);
int c=input.nextInt();
String[][] array=new String[c][6];
for(int i=0; i<c; i++){
for(int j=0;j<6;j++){
array[i][j]=input.next();
}}
System.out.println("RollNO \t Name \t Class \t Attendence Mark \tTeacher Name \tSubject Name");
for(int k=0; k<c; k++){
for(int l=0;l<6;l++){
System.out.print(array[k][l]+ "\t\t" );
}
System.out.println("\n");
}
}}
here this is second class
import java.util.Scanner;
public class student extends Attendence {
private int password;
private String ID;
public student(int passsword , String ID){
super();
this.password= password;
this.ID=ID;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public void mainfunction(){
Scanner input=new Scanner(System.in);
System.out.println("enter the password");
int password=input.nextInt();
System.out.println("enter the ID");
String ID=input.next();
if(password==123 || ID=="abc"){
System.out.println("u enter right password and ID so you can acess the Attendance sheet");
}
else
System.out.println("u enter wrong password and ID so you can't acess the Attendance sheet");
}
#Override
public String toString(){
return this.getPassword()+ this.getID()+super.toString();
}
public static void main(String[] args) {
Attendence z = new Attendence();
student a=new student(123, "abc");
//a.mainfunction();
a.mainfunction();
z.project();
}
}
Call the Attendance class in if loop(if password and ID is correct)..and close the input(Scanner) object..
Student.class
import java.util.Scanner;
public class Student extends Attendence {
private int password;
private String ID;
public Student(int passsword, String ID) {
super();
this.ID = ID;
}
public static void main(String[] args) {
Student a = new Student(123, "abc");
a.mainfunction();
}
public void mainfunction() {
Scanner input = new Scanner(System.in);
System.out.println("enter the password");
int password = input.nextInt();
System.out.println("enter the ID");
String ID = input.next();
if (password == 123 || ID == "abc") {
System.out.println("u enter right password and ID so you can acess the Attendance sheet");
Attendence z = new Attendence();
z.project();
} else {
System.out.println("u enter wrong password and ID so you can't acess the Attendance sheet");
}
input.close();
}
#Override
public String toString() {
return this.getPassword() + this.getID() + super.toString();
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
}
Attendance.class
import java.util.Scanner;
public class Attendence {
public void project() {
System.out.println("Enter the total no of students of the class");
Scanner input = new Scanner(System.in);
Integer c = input.nextInt();
String[][] array = new String[c][6];
for (int i = 0; i < c; i++) {
System.out.println("Enter the Roll No,Name,Class,Attendance Mark,Teacher Name,Student Name for student "+(i+1));
for (int j = 0; j < 6; j++) {
array[i][j] = input.next();
}
}
System.out.println("RollNO \t Name \t Class \t Attendence Mark \tTeacher Name \t Subject Name");
for (int k = 0; k < c; k++) {
for (int l = 0; l < 6; l++) {
System.out.print(array[k][l] + "\t\t");
}
System.out.println("\n");
}
input.close();
}
}
It is working as expected.
I tried to execute your code got following output . check it this is what you expect.
enter the password
123
enter the ID
abc
u enter right password and ID so you can acess the Attendance sheet
Enter the total no of students of the class
1
2
xyz
2
2
2
abc
RollNO Name Class Attendence Mark Teacher Name S
ubject Name
2 xyz 2 2 abc
or else ask precisely what you exactly want.

my psvm class doesnt run the other classes and methods

My program is not running. It must be something with calling in the classes from my psvm.
I have inserted my main class and I want the class with the following methods to run. It runs the program, but the class: course with its methods is not activated.
public class main {
public static void main(String[] args) {
Course task1 = new Course();
task1.Assignment1();
}}
The other class
public class Course {
CourseGrades[] course;
public void Assignment1() {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to students database");
System.out.println("Enter a to enter a student");
char choice = sc.next().charAt(0);
if (choice > 'z' || choice > 'a') {
System.out.println("Invalid choice");
} else {
switch (choice) {
case 'a':
numbers();
break;
case 'b':
entering();
break;
case 'c':
printCourse();
break;
}
}
}
public void numbers() {
System.out.println("Enter how many courses taken ");
Scanner numbers = new Scanner(System.in);
int courses = numbers.nextInt();
CourseGrades[] course = new CourseGrades[courses];
}
public void entering() {
for (int i = 0; i < course.length; i++) {
System.out.println("Enter coursename");
Scanner sc = new Scanner(System.in);
sc = new Scanner(System.in);
String courseName = sc.nextLine();
course[i] = new CourseGrades();
course[i].setName(courseName);
System.out.println("Enter grade");
Scanner grade = new Scanner(System.in);
course[i].setGrade(i);
}
}
public void printCourse() {
System.out.println("Printing out courses and grades");
for (int i = 0; i < course.length; i++) {
System.out.println(" name 2" + course[i].getName() + " grade" + course[i].getGrade());
}
}
}
Getters and setters
public class CourseGrades {
private String name;
private int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
If you have multiple classes in your code then you should always save with the class which having main() method (in this case Main.java), and that class only should be contains public access specifier. I run same code in my IDE. i am run your code successfully in MY IDE:
See the code:
public class Main {
public static void main(String[] args) {
Course task1 = new Course();
task1.Assignment1();
}
}
// The other class
class Course {
CourseGrades[] course;
public void Assignment1() {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to students database");
System.out.println("Enter a to enter a student");
char choice = sc.next().charAt(0);
if (choice > 'z' || choice > 'a') {
System.out.println("Invalid choice");
} else {
switch (choice) {
case 'a':
numbers();
break;
case 'b':
entering();
break;
case 'c':
printCourse();
break;
}
}
}
public void numbers() {
System.out.println("Enter how many courses taken ");
Scanner numbers = new Scanner(System.in);
int courses = numbers.nextInt();
CourseGrades[] course = new CourseGrades[courses];
}
public void entering() {
for (int i = 0; i < course.length; i++) {
System.out.println("Enter coursename");
Scanner sc = new Scanner(System.in);
sc = new Scanner(System.in);
String courseName = sc.nextLine();
course[i] = new CourseGrades();
course[i].setName(courseName);
System.out.println("Enter grade");
Scanner grade = new Scanner(System.in);
course[i].setGrade(i);
}
}
public void printCourse() {
System.out.println("Printing out courses and grades");
for (int i = 0; i < course.length; i++) {
System.out.println(" name 2" + course[i].getName() + " grade" + course[i].getGrade());
}
}
}
// Getters and setters
class CourseGrades {
private String name;
private int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
Results:
Welcome to students database
Enter a to enter a student
a
Enter how many courses taken
3

Java: how to return an Array?

this is the code, from what I understand, it is suppose to work.
Also when I debug my program, it seems that the array is being filled with the objects that the same method is creating.
But still, when I try to print it, it shows me "null" back agian, like the "return" does not work.
Why is it happening?
public class Course {
String courseName;
String teacherName;
int gradeAv;
static int counter;
static int maxNumOfStudents;
Student studentsArray[] = new Student[5];
int numOfStudents = studentsArray.length;
public Course() {
}
public Course(String courseName) {
this();
this.courseName = courseName;
}
public Course(String courseName, String teacherName) {
this(courseName);
this.courseName = courseName;
this.teacherName = teacherName;
}
public Student[] addStudent(String name, int age, int grade) {
for (int i = 0; i < 5; i++) {
studentsArray[i] = new Student(name, age, grade);
age += 10;
grade += 10;
}
return studentsArray;
}
public void printStudentArray(Student studentArray[]) {
studentArray = this.studentsArray;
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i]);
}
}
public int gradeAv() {
for (int i = 0; i < studentsArray.length; i++) {
int temp = 0;
if (studentsArray[i].grade > temp) {
gradeAv = temp;
System.out.println(gradeAv);
}
}
return gradeAv;
}
public void printCourse() {
System.out.println("Course: ");
System.out.println("Course Name: " + courseName + ". "
+ "Teacher's Name: " + teacherName + ". "
+ "Number Of Students: " + numOfStudents + ". ");
}
}
This is my main class:
public class MainClass {
public static void main(String[] args) {
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.printStudent();
System.out.println();
stud.printCourse();
System.out.println();
cour.printStudentArray(cour.studentsArray);
System.out.println();
// cour.gradeAv();
}
}
in
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.addStudent("Joe", 23, 100); will not add any students to your course. stud is an instance of a completely different class, Student, and the implementation of Student is not in the code you've posted.
call the addStudent method of cour instead of the one for stud
cour.addStudent("Joe", 23, 100);
instead
I would also like to add that there are a lot of curious elements to your code, some of which people have brought up in the comments. It would be tedious to list them all. I'd take a look-through, just to make sure you're not doing redundant things.
Try this for example:
Course class:
import java.util.ArrayList;
import java.util.List;
public class Course {
private List<Student> students = new ArrayList<Student>();
private String teacherName;
private String subjectName;
public Course(String subjectName, String teacherName) {
this.subjectName = subjectName;
this.teacherName = teacherName;
}
public void addStudent(Student student) {
students.add(student);
}
public float getAverageGrade() {
float grade = 0;
for (Student student : students) {
grade += student.getGrade();
}
return grade / students.size();
}
public void printCourse() {
System.out.println("Course "+subjectName+" taught by "+teacherName);
System.out.println("Students:");
printStudents();
System.out.println("Aberage grade: "+getAverageGrade());
}
public void printStudents() {
for (Student student : students) {
System.out.println(student.getName()+"\t age "+student.getAge()+" \t grade "+student.getGrade());
}
}
}
Student class:
public class Student {
private String name;
private int age;
private int grade;
public Student(String name, int age, int grade) {
this.grade = grade;
this.age = age;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}

Categories

Resources