my psvm class doesnt run the other classes and methods - java

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

Related

How do i clear screen?

After user enter Status and enter how can i make everything on the top disappear and just show whatever's below that. I do want the inputs to be visible anymore. How can i implement this? Can someone help me fix my code, I previously tried a system out flush but it did not work. Thank you very much.
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Car> cars = new ArrayList<>();
int choice;
Car car = new Car();
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("\n1 - Insert car\n2 - Edit car\n3 - Exit");
System.out.println("Enter your choice: ");
choice = scanner.nextInt();
switch (choice){
case 1:
car = new Car();
scanner = new Scanner(System.in);
System.out.println("Enter Plate number: ");
car.setPlateNumber(scanner.nextLine());
System.out.println("Enter Brand: ");
car.setBrand(scanner.nextLine());
System.out.println("Enter Model: ");
car.setModel(scanner.nextLine());
System.out.println("Enter type: ");
car.setType(scanner.nextLine());
System.out.println("Enter Color: ");
car.setColour(scanner.nextLine());
System.out.println("Enter Price: ");
car.setPrice(scanner.nextDouble());
scanner = new Scanner(System.in);
System.out.println("Enter Status: ");
car.setStatus(scanner.nextLine());
cars.add(car);
System.out.println("\nCar saved successfully!!");
break;
case 2:
car = new Car();
scanner = new Scanner(System.in);
System.out.println("Enter car Plate Number: ");
car.setPlateNumber(scanner.nextLine());
if(!car.editCarRecord(cars))
System.out.println("Car not found!!");
break;
case 3:
return;
default:
System.out.println("Invalid option!!");
}
}
}
}
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Car {
private String plateNumber;
private String brand;
private String model;
private String type;
private String colour;
private String status;
private double price;
public Car() {
// Define this if we want default values
}
public Car(String pn, String br, String mo, String ty, String co, String st, double pr) {
plateNumber = pn;
brand = br;
model = mo;
type = ty;
colour = co;
status = st;
price = pr;
}
public void setPlateNumber(String pn) {
plateNumber = pn;
}
public void setBrand(String br) {
brand = br;
}
public void setModel(String mo) {
model = mo;
}
public void setType(String ty) {
type = ty;
}
public void setColour(String co) {
colour = co;
}
public void setStatus(String st) {
status = st;
}
public void setPrice(double pr) {
price = pr;
}
public String getPlateNumber() {
return plateNumber;
}
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public String getType() {
return type;
}
public String getColour() {
return colour;
}
public String getStatus() {
return status;
}
public double getPrice() {
return price;
}
public boolean editCarRecord(ArrayList<Car> list){
Scanner scanner = new Scanner(System.in);
int choice;
for(int i=0; i<list.size(); i++) {
if (list.get(i).getPlateNumber().compareToIgnoreCase(this.getPlateNumber()) == 0) {
System.out.println("Car record matched!!");
System.out.println(list.get(i).toString());
while(true) {
System.out.println("1 - Edit Status\n2 - Edit Price\n3 - Edit Color\n4 - Back to main menu");
System.out.println("Enter your choice: ");
choice = scanner.nextInt();
if (choice == 1) {
System.out.println("Enter new Status: ");
list.get(i).setStatus(scanner.nextLine());
System.out.println("Status updated Successfully!");
} else if (choice == 2) {
System.out.println("Enter new Price: ");
list.get(i).setPrice(scanner.nextDouble());
System.out.println("Price updated Successfully!");
} else if (choice == 3) {
System.out.println("Enter new Color: ");
list.get(i).setColour(scanner.nextLine());
System.out.println("Color updated Successfully!");
} else if (choice == 4) {
return true;
} else {
System.out.println("Invalid choice!!");
}
}
}
}
return false;
}
public String toString() {
return "Plate number: " + plateNumber
+ "\nBrand: " + brand
+ "\nModel: " + model
+ "\nType: " + type
+ "\nColour: " + colour
+ "\nStatus: " + status
+ "\nPrice: " + price;
}
}

Unable to display all the elements of an arraylist

Menu driven program for adding and displaying employee details.
Taking input from the user for employee details.
Store it into array list and display it.
I have added the entries to a list but always the last entered data replaces all the elements in the list.
Taking input in switch case 1 and add it to an arraylist and displaying it in another case:
class Employee
{
Scanner sc = new Scanner(System.in);
int empid,n;
String empname, empdesignation, empdept, empproject;
public Employee() { }
public Employee(int id,String name,String desig,String dept,String proj)
{
this.empid=id;
this.empname=name;
this.empdesignation=desig;
this.empdept=dept;
this.empproject=proj;
}
public void setEmpNo() {
System.out.print("Enter the number of employees: ");
n = sc.nextInt();
}
public int getEmpNo() {
return n;
}
public int getID() {
return empid;
}
public void setID(int id) {
this.empid = id;
}
public String getName() {
return empname;
}
public void setName(String name) {
this.empname = name;
}
public String getDept() {
return empdept;
}
public void setDept(String dept) {
this.empdept = dept;
}
public String getDesig() {
return empdesignation;
}
public void setDesig(String desig) {
this.empdesignation = desig;
}
public String getProject() {
return empproject;
}
public void setProject(String proj) {
this.empproject = proj;
}
public void displayemp(int id, String name,
String dept, String designation, String project)
{
System.out.print("\n============================================================\n");
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Department: " + dept);
System.out.println("Designation: " + designation);
System.out.println("Project: " + project);
System.out.print("\n============================================================\n");
}
}
public class trying
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int ch = 0, id, n, abc, count = 0, pcount = 0;
final int maxEmp=1000;
String name, designation, dept, pname, mgrname, project;
Employee emp5 = new Employee();
Project proj5 = new Project();
List<Employee> list = new ArrayList<Employee>();
List<Project> list1 = new ArrayList<Project>();
switch (ch) {
case 1:
emp5.setEmpNo();
int a = emp5.getEmpNo();
for (int i = 1; i < a+1; i++)
{
System.out.print("Enter ID: ");
id = sc.nextInt();
emp5.setID(id);
sc.nextLine();
System.out.print("Enter Name: ");
name = sc.nextLine();
emp5.setName(name);
System.out.print("Enter Department: ");
dept = sc.nextLine();
emp5.setDept(dept);
System.out.print("Enter Designation: ");
designation = sc.nextLine();
emp5.setDesig(designation);
System.out.print("Enter Project: ");
project = sc.nextLine();
emp5.setProject(project);
list.add(emp5);
}
break;
case 5:
System.out.println("Showing Employee Details:");
for(Employee e:list)
{
System.out.println(e.empid+" "+e.empname+" "+e.empdept+" "
+e.empdesignation+" "+e.empproject);
}
break;
}
} while (!(ch <= 0 || ch > 7));
}
I need to display all the entries of the array list, but the last entered data get repeatedly displayed.
Employee emp5 = new Employee();
This will fo inside the for loop after :
for (int i = 1; i < a+1; i++) {
Employee emp5 = new Employee();
....
}
You will have to create new employee obj. At this moment you are keep updating same obj.
Update
Try creating new obj after adding item in the list
list.add(emp5);
emp5 = new Employee();

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 do I fix a mismatch exception in 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.

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.

Categories

Resources