Updating Student Information (Runtime) - java

This is my code for STUDENT RECORD SYSTEM. I think it is on its 80% of completion. The problem here is that when i have many students and i update a specific student(subj & grade) the updated element is not being saved on that specific student. And when I display all of the results the updated values are given to other student. Please help me out with this issue. And btw this code has 2 classes Student and StudentGrade. I hope you'll help me fix this. Thanks in advance. :) and Advance Happy New Year!
public class Student
{
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
public Student()
{
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Student(String IDNum, String fName, String mName, String lName, String deg,int level )
{
this.IDNumber=IDNum;
this.firstName=fName;
this.middleName=mName;
this.lastName=lName;
this.degree=deg;
this.yearLevel=level;
}
public void setIdNumber(String IDNumber)
{
this.IDNumber = IDNumber;
}
public String getIdNumber()
{
return IDNumber;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName()
{
return firstName;
}
public void setMiddleName(String middleName)
{
this.middleName=middleName;
}
public String getMiddleName()
{
return middleName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public String getLastName()
{
return lastName;
}
public void setDegree(String degree)
{
this.degree=degree;
}
public String getDegree()
{
return degree;
}
public void setYearLevel(int yearLevel)
{
this.yearLevel=yearLevel;
}
public int getYearLevel()
{
return yearLevel;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class test2 {
static ArrayList<Student> studentList = new ArrayList<Student>();
static ArrayList<StudentGrade> studentLists = new ArrayList<StudentGrade>();
public static void main(String[] args)
{
menu();
}
public static void menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("*********STUDENT RECORD SYSTEM*********\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1)
{
add();
}
else if (choice == 2)
{
displayAll();
}
else if (choice == 3)
{
displaySpecific();
}
else if (choice == 4)
{
update();
}
else if (choice == 5)
{
average();
}
else if( choice == 6)
{
System.exit(0);
}
else
menu();
}
public static void add()
{
Scanner in = new Scanner(System.in);
char ans;
String temp;
int total;
do {
System.out.println("NUMBER OF STUDENTS YOU WANT TO INPUT: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("**********STUDENT INFORMATION**********\n\n");
System.out.println("PRESS ENTER");
in.nextLine();
System.out.print("ID NUMBER: ");
student[index].setIdNumber(in.nextLine());
System.out.print("FIRST NAME: ");
student[index].setFirstName(in.nextLine());
System.out.print("MIDDLE NAME: ");
student[index].setMiddleName(in.nextLine());
System.out.print("LAST NAME: ");
student[index].setLastName(in.nextLine());
System.out.print("DEGREE: ");
student[index].setDegree(in.nextLine());
System.out.print("YEAR LEVEL: ");
student[index].setYearLevel(in.nextInt());
studentList.add(student[index]);
}
System.out.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
/* // SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
} */
menu();
}
public static void displayAll() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY lageeeee!!! \nPLEASE INPUT FIRST\n\n");
in.nextLine();
}
else
{
if(studentLists.size() == 0){
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()/* +"\nGrade: "
+ studentLists.get(i).getGrade() */+"\n\n");
}
in.nextLine();
}
else{
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++)
{
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()+"\n\n");
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void displaySpecific() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY oe!!! KALAGOT!\nPLEASE INPUT FIRST\n");
in.nextLine();
}
else
{
String id = new String();
/* in.nextLine(); */
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
if(studentLists.size()==0)
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + /* "\nGrade: "
+ studentLists.get(j).getGrade()+ */"\n\n");
System.out.println();
in.nextLine();
}
/* else
{
System.out.print("STUDENT DOES NOT EXIST IN THIS WORLD!");
in.nextLine();
} */
}
}
else
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() +"\n\n");
System.out.println();
}
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();
int total;
for(int x=0;x<studentList.size();x++)
{
if(idnum.equals(studentList.get(x).getIdNumber()))
{
System.out.println("NUMBER OF SUJECTS YOU WANT TO INPUT: ");
total = in.nextInt();
do
{
StudentGrade[] update = new StudentGrade[total];
for(int y = 0;y<update.length;y++)
{
update[y] = new StudentGrade();
in.nextLine();
System.out.print("ENTER SUBJECT: ");
update[y].setSubject(in.nextLine());
System.out.print("ENTER GRADE: ");
update[y].setGrade(in.nextDouble());
studentLists.add(update[y]);
}
System.out.print("Enter another subject and grade? [y/n]");
String ans = in.next();
answer = ans.charAt(0);
}while(answer == 'y');
}
menu();
}
}
public static void average()
{
Scanner in = new Scanner(System.in);
double sum=0;
double average=0;
String ID = new String();
System.out.print("ENTER ID NUMBER: ");
ID = in.nextLine();
for(int xx=0;xx<studentList.size();xx++)
{
if(ID.equals(studentList.get(xx).getIdNumber()))
{
for(int ind=0;ind<studentLists.size();ind++)
{
sum += studentLists.get(ind).getGrade();
average=sum/studentLists.size();
}
System.out.print("ID NUMBER:"+studentList.get(xx).getIdNumber()+"\nNAME: "
+studentList.get(xx).getFirstName()+" "
+studentList.get(xx).getMiddleName()+" "
+studentList.get(xx).getLastName());
System.out.print("\nAVERAGE: "+average+"\n");
in.nextLine();
}
}
menu();
}
}

First of all I would change studentList to Map to be able to get the student by id directly and not to search for the matching student every time.
The access to the collections of all students is then like this:
for(Map.Entry<String, Student> entry : studentList.entrySet()){
String id = entry.getKey();
Student student = entry.getValue();
// ...
}
A a second step you should check your update method. I see, that you a searching for the student, but you don't updating this object. You are adding a new one at the end of the loop with studentList.add().
You have store the matching Student into the local variable and just modify this without modifying the collection of students.

You have two reader statements in update function
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();//1
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();//2
I think there should be only one as your just reading the id number and as #Vlad said your adding a new element to the array list rather than modifying the existing data .
also for your code you can use
arrayList.set(index i,String replaceElement);// this will help you replace the value at a particular index
it is better to use HashMap instead of array list so when you put an existing element into
a map the value is overwritten.
static Map <String,Student> studentList = new HashMap<String,Student>();
static Map<String, List<StudentGrade>> studentLists = new HashMap<String, List<StudentGrade>>();
Here the key will be the student idNumber

Related

I have a little problem in the delete function.After i delete a certain data,the remaining 2 datas keeps their id numbers stays constants

This is the code
import java.util.Scanner;
import java.util.ArrayList;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> name = new ArrayList<String>();
boolean initiated = false;
int personID = 0; //Numbering the profiles
int operation = 0; //User Choice
int target = 0; //Targeted profile
while(operation != 0|| initiated == false){
System.out.println("============================");
System.out.print("1-Add Person\n2-Edit Person\n3-Delete Person\n4-Print Report\nSelect Option: ");
operation = scanner.nextInt();
System.out.println("============================");
if(operation == 1){
personID++;
Add(scanner, personID, name);
}
else if(operation == 2){
Edit(scanner,target,name);
}
else if(operation == 3){
System.out.println("PROFILE DELETE");
Delete(scanner, target, name);
personID--;
}
else if(operation == 4){
System.out.println("Reporting Records..");
Report(name);
}else{
System.out.print("Input Error!");
return;
}
if(operation != 4){
Report(name);
}
initiated = true;
}
}
public static void Add(Scanner scanner, int personID, ArrayList<String> name){
System.out.println("PROFILE ADD");
name.add(Integer.toString(personID));
String dummyScaner = scanner.nextLine(); //DOes Nothing but makesure FName gets an input
System.out.print("Enter First Name: ");
String input0 = scanner.nextLine();
name.add(input0);
System.out.print("Enter Last Name: ");
String input1 = scanner.nextLine();
name.add(input1);
System.out.print("Enter Age: ");
String input2 = scanner.nextLine();
name.add(input2);
}
public static void Edit(Scanner scanner, int target, ArrayList<String> name){
System.out.println("PROFILE EDIT");
Report(name);
System.out.print("Enter Number you want to update: ");
int targetID = scanner.nextInt();
target = (targetID-1)*4;
System.out.print("Enter First Name: ");
String dummyInput = scanner.nextLine();
String input0 = scanner.nextLine();
name.set(target+1,input0);
System.out.print("Enter Last Name: ");
String input1 = scanner.nextLine();
name.set(target+2,input1);
System.out.print("Age: ");
String input2 = scanner.nextLine();
name.set(target+3,input2);
System.out.println("Number "+target+" updated successfully!");
}
public static void Delete(Scanner scanner, int target, ArrayList<String> name){
System.out.println("PROFILE DELETE");
Report(name);
System.out.print("Enter Number you want to delete: ");
int targetID = scanner.nextInt();
target = (targetID-1)*4;
name.remove(target+3);
name.remove(target+2);
name.remove(target+1);
name.remove(target);
System.out.println("Number "+target+" deleted successfully!");
}
public static void Report(ArrayList<String> name){
System.out.println("============================\n");
System.out.print("No. | First Name | Last Name | Age");
for (int i = 0; i < name.size(); i++) {
if(i%4==0){
System.out.println("");
}
System.out.print(name.get(i)+" | ");
}
System.out.println("");
}
}
//To Do List:
//Fix: Delete Function
// Issue: When deleting a profile, with id number, the profile ID remains constant and does not adapt to new profile count.
// Ex: you have 3 profile and then you decided to delete 3. there will be 1 and 2 left.
// But if you decided to delete 2 instead, it'll show 1 and 3 instead of being 1 and 2. This is the to do list
I advise you to create a class to represent a person,
public class Person {
private String firstName;
private String lastName;
private String age;
public Person(String firstName, String lastName, String age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}}
And use this class in your Main ArrayList,
For the id it is rather necessary to speak of index at this moment, here is the modification to make to your main
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Person> personnes = new ArrayList<>();
boolean initiated = false;
int personID = 0; //Numbering the profiles
int operation = 0; //User Choice
int target = 0; //Targeted profile
while(operation != 0|| initiated == false){
System.out.println("============================");
System.out.print("1-Add Person\n2-Edit Person\n3-Delete Person\n4-Print Report\nSelect Option: ");
operation = scanner.nextInt();
System.out.println("============================");
if(operation == 1){
personID++;
Add(scanner, personnes);
}
else if(operation == 2){
Edit(scanner,target, personnes);
}
else if(operation == 3){
System.out.println("PROFILE DELETE");
Delete(scanner, target, personnes);
personID--;
}
else if(operation == 4){
System.out.println("Reporting Records..");
Report(personnes);
}else{
System.out.print("Input Error!");
return;
}
if(operation != 4){
Report(personnes);
}
initiated = true;
}
}
public static void Add(Scanner scanner , ArrayList<Person> name){
System.out.println("PROFILE ADD");
String dummyScaner = scanner.nextLine(); //DOes Nothing but makesure FName gets an input
System.out.print("Enter First Name: ");
String input0 = scanner.nextLine();
System.out.print("Enter Last Name: ");
String input1 = scanner.nextLine();
System.out.print("Enter Age: ");
String input2 = scanner.nextLine();
name.add(new Person(input0, input1, input2));
}
public static void Edit(Scanner scanner, int target, ArrayList<Person> name){
System.out.println("PROFILE EDIT");
Report(name);
System.out.print("Enter Number you want to update: ");
int targetID = scanner.nextInt();
target = (targetID-1);
Person person = name.get(target);
System.out.print("Enter First Name: ");
String dummyInput = scanner.nextLine();
String input0 = scanner.nextLine();
person.setFirstName(input0);
System.out.print("Enter Last Name: ");
String input1 = scanner.nextLine();
person.setLastName(input1);
System.out.print("Age: ");
String input2 = scanner.nextLine();
person.setAge(input2);
System.out.println("Number "+target+" updated successfully!");
}
public static void Delete(Scanner scanner, int target, ArrayList<Person> name){
System.out.println("PROFILE DELETE");
Report(name);
System.out.print("Enter Number you want to delete: ");
int targetID = scanner.nextInt();
target = (targetID-1);
name.remove(target);
System.out.println("Number "+target+" deleted successfully!");
}
public static void Report(ArrayList<Person> name){
System.out.println("============================\n");
System.out.println("No. | First Name | Last Name | Age");
for (int i = 0; i < name.size(); i++) {
Person person = name.get(i);
System.out.println((i + 1) + " | " + person.getFirstName() + " | " + person.getLastName() + " | " + person.getAge());
}
System.out.println("");
}

how to code a specefic random number scheme?

I am learning Java. I just want to write a method that generates random numbers that comes in a specific set, like a bank credit card " xxxx - xxxx - xxxx - xxxx ". Each chunk needs to be exactly 4 digit long. anybody has any solution?
public class Main {
public static User accountHolders[] = new User[100];
public static int index = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("\t-----\tWelcome to The Bank portal\t-----");
System.out.println("\nPlease enter the number of your required action");
System.out.println("\n1) Make a Deposit");
System.out.println("2) Get balance");
System.out.println("3) Register new account");
System.out.println("0) Quit the portal");
int command = input.nextInt();
switch (command) {
case 1:
InputController.deposit();
break;
case 2:
InputController.balance();
break;
case 3:
User user = InputController.register();
accountHolders[index] = user;
index++;
break;
default:
System.out.println("Wrong input! please enter a number between 1 - 4!!!");
break;
}
}
}
}
public class Account {
private int uniID;
private int password;
private int balance;
private String cardNum;
public int getUniID() {
return uniID;
}
public int getPassword() {
return password;
}
public int getBalance() {
return balance;
}
public void makeDeposit(int amount) {
this.balance = this.balance + amount;
}
public Account(int password, int balance) {
this.password = password;
this.balance = balance;
Random rand = new Random();
this.uniID = rand.nextInt(100);
}
}
public class User {
private String name;
private Account account;
public String getName() {
return name;
}
public Account getAccount() {
return account;
}
public User(String name, Account account) {
this.name = name;
this.account = account;
}
}
public class InputController {
static Scanner input = new Scanner(System.in);
public static User register() {
System.out.print("Enter your name: ");
String name = input.next();
System.out.print("Enter your password: ");
int password = input.nextInt();
System.out.print("Please enter the amount of your initial deposit: ");
int balance = input.nextInt();
Account account = new Account(password, balance);
User user = new User(name, account);
System.out.print("Your account number is: " + account.getUniID());
return user;
}
public static void balance() {
int index = findAccount();
if (index != -1) {
System.out.print("Enter your password: ");
int password = input.nextInt();
if (Main.accountHolders[index].getAccount().getPassword() == password) {
System.out.println("Your balance is: " +
Main.accountHolders[index].getAccount().getBalance());
} else {
System.out.println("Wrong password");
}
}
}
public static void deposit() {
int index = findAccount();
if (index != -1) {
System.out.print("Enter the required amount: ");
int money = input.nextInt();
Main.accountHolders[index].getAccount().makeDeposit(money);
System.out.println("Deposit successful");
}
}
private static int findAccount() {
System.out.print("Please Enter your account number: ");
int accountNum = input.nextInt();
for (int i = 0; i < Main.index; i++) {
User user = Main.accountHolders[i];
int id = user.getAccount().getUniID();
if (id == accountNum) {
return i;
} else if (id != accountNum){
System.out.println("Account number not found");
}
}
return -1;
}
}
sorry, It's a bit long but right now this the whole thing. I want to introduce a new variable for credit card number users every time they register a new account.
Can you try below code.if you wants only one time just remove for loop.
public class RandomSetGenerator {
public static void main(String[] args) {
Random generator = new Random();
for (int i = 0; i < 10; i++) {
String string = Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000) + "-" + Integer.toString(generator.nextInt(9000) + 1000);
System.out.println("Specific set of random number generated :" + string);
}
}}
create a function which gives you the random number within a range and use it generate the same:
public class RandomSetGenerator {
public String genNumberToString(int i, int j){
Random generator = new Random();
return Integer.toString(generator.nextInt(i) + j)
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String str = genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000) + "-" + genNumberToString(9000, 1000);
System.out.println("Specific set of random number generated :" + str);
}
}}

Java Sorting Algorithm Classroom Data Structures Project Trouble

I'm having trouble with a project for my Java data structures and algorithms class. I have a classroom program with an option to create, update, display, or see all students.
Can someone help me by implementing a sorting algorithm and explain it? I was trying to sort the students by grade but I don't know how to implement it with a user input.
Here is main:
package main;
import school.School;
public class Main {
public static void main(String[] args) {
School aSchool = new School();
aSchool.initialMenu();
}
}
Here is school:
package school;
import java.io.PrintStream;
import java.util.Scanner;
import student.Student;
public class School {
private final Scanner keyboard = new Scanner(System.in);
private final PrintStream messagePane = new PrintStream(System.out, true);
private int nextAvailablePosition;
private Student[] classroom;
public School() {
super();
}
private void initializeArray() {
classroom = new Student[4];
nextAvailablePosition = 0;
}
private void storeStudentInArray(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.storeStudentInArray()";
if (nextAvailablePosition >= classroom.length) {
Student[] biggerClassroom = new Student[(int) (classroom.length * 1.5)];
System.arraycopy(classroom, 0, biggerClassroom, 0, classroom.length);
classroom = biggerClassroom;
}
classroom[nextAvailablePosition] = aStudent;
nextAvailablePosition++;
}
private Student searchForStudentInArray(String searchID) {
assert searchID != null : "Null parameter supplied to School.searchForStudentInArray()";
int index = 0;
while (index < nextAvailablePosition) {
if (searchID.equalsIgnoreCase(classroom[index].getID())) {
return classroom[index];
}
index++;
}
return null;
}
public void initialMenu() {
initializeArray();
boolean stillWorking = true;
do {
messagePane.print("\n"
+ "WELCOME to the Student Database Organizer 1.0!\n"
+ "Here you can store students in a virtual classroom.\n"
+ "\n"
+ "(C)reates a Student\n"
+ "(U)pdate a Student\n"
+ "(D)isplay a Student\n"
+ "(A)ll Students\n"
+ "(E)nd\n"
+ "Enter Letter Here: \n");
String initialResponse = keyboard.nextLine();
String response = initialResponse.trim().toUpperCase();
if (response.length() > 0) {
response = response.substring(0, 1);
if (response.equals("E")) {
stillWorking = false;
} else if (response.equals("U")) {
updateStudent();
} else if (response.equals("D")) {
displayStudent();
} else if (response.equals("C")) {
Student aStudent = createStudent();
if (aStudent != null) {
storeStudentInArray(aStudent);
}
} else if (response.equals("A")) {
gpa();
} else {
messagePane.println("Try again " + initialResponse
+ ", is not a valid choice.\n"
+ "Please enter one of the letters from the specified menu.");
}
} else {
messagePane.println("You must enter one of the letters from the specified menu\n"
+ "before you press \"Enter\".");
}
} while (stillWorking);
}
private Student createStudent() {
messagePane.println(
"\nYou can enter the student's information here: \n");
messagePane.print("What's the Student's name?: ");
String name = keyboard.nextLine();
messagePane.print("What year/grade is the student?: ");
String agrade = keyboard.nextLine();
messagePane.print("Birthday (MMDDYY): ");
int birthday = keyboard.nextInt();
keyboard.nextLine();
messagePane.print("What's their ID number? (1-7 Numbers): ");
String id = keyboard.next();
keyboard.nextLine();
messagePane.print("Course(s) taken: ");
String course = keyboard.nextLine();
double gpa;
messagePane.print("GPA: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextDouble()) {
gpa = inputScanner.nextDouble();
} else if (inputScanner.hasNext()) {
messagePane.println("You entered something other than a number - the gpa "
+ "has been set to the default of " + Student.DEFAULT_GPA);
gpa = Student.DEFAULT_GPA;
} else {
gpa = Student.DEFAULT_GPA;
}
Student newStudent;
try {
newStudent = Student.create(name,
agrade, birthday, id,
course, gpa );
} catch (Exception anException) {
messagePane.println(" Sorry, I couldn't input the student for you. " + anException.getMessage());
newStudent = null;
}
return newStudent;
}
private void displayStudent() {
Student aStudent = locateStudent();
if (aStudent == null) {
messagePane.println("Sorry, this ID number is not in the classroom.");
} else {
messagePane.println(" " + aStudent.getGrade() + " " + aStudent.getName()
+ " (" + aStudent.getBirthday() + ", " + aStudent.getID() + ") " + "\n"
+ " " + aStudent.getCourse() + " GPA: " + aStudent.getGpa()
);
}
}
private void updateStudent() {
Student aStudent = locateStudent();
if (aStudent == null) {
messagePane.println("Sorry, the student is not listed.");
} else {
updateMenu(aStudent);
}
}
private void updateMenu(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateMenu()";
String studentBeforeUpdating = singleLineStudentDisplay(aStudent);
messagePane.println("The Student being updated is: \n" + aStudent);
boolean stillTrying = true;
do {
messagePane.print("\n"
+ "Student Database Organizer 1.0\n"
+ "UPDATE MENU OPTIONS\n"
+ ""
+ "Press 1 to change the Student's name\n"
+ "Press 2 to update grade\n"
+ "Press 3 to update course(s)\n"
+ "Press 4 to update gpa \n"
+ "Press 5 to finish updating current Student\n"
+ ""
+ "\nPlease enter your selection: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextInt()) {
int response = inputScanner.nextInt();
if (response == 1) {
updateName(aStudent);
} else if (response == 2) {
updateGrade(aStudent);
} else if (response == 3) {
updateCourse(aStudent);
} else if (response == 4) {
updateGpa(aStudent);
} else if (response == 5) {
stillTrying = false;
} else {
messagePane.println(
"You typed " + response + ", which is not a legit option.\n"
+ "Please check the list of numbers in the menu..");
}
} else if (inputScanner.hasNext()) {
String junk = inputScanner.next();
messagePane.println("You entered " + junk + ", which is not a legal option.\n"
+ "Please enter one of the numbers from the specified menu.");
} else {
messagePane.println("Hold your horses! You need to enter a number\n"
+ "before you press \"Enter\".");
}
} while (stillTrying);
messagePane.println("\n" + "Student before updating: " + studentBeforeUpdating);
messagePane.println("Student after updating: " + singleLineStudentDisplay(aStudent));
}
private void updateName(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateName()";
int result;
messagePane.println("The student's name is: " + aStudent.getName());
messagePane.print("Now it is...: ");
String name = keyboard.nextLine();
result = aStudent.setName(name);
messagePane.println("\nUpdate status: "
+ Student.getDescriptionOfReturnedSignal(result) );
messagePane.println("\nFinalized changes: " + singleLineStudentDisplay(aStudent));
}
private void updateBirthday(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateBirthday()";
int result;
messagePane.println("The current birthday is: " + aStudent.getBirthday());
messagePane.print("New birthday (exactly four digits): ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextInt()) {
int birthday = keyboard.nextInt();
keyboard.nextLine();
result = aStudent.setBirthday(birthday);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " );
} else {
messagePane.println("You didn't enter a number\n"
+ "Please Check the Format MMDDYY \n\n"
+ "Sorry, no changes were made.");
}
}
private void updateGrade(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateGrade()";
int result;
messagePane.println("The student's grade is: " + aStudent.getGrade());
messagePane.print("Now it is... (at least three characters: ");
String agrade = keyboard.nextLine();
result = aStudent.setGrade(agrade);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " + singleLineStudentDisplay(aStudent));
}
private void updateCourse(Student aStudent){
assert aStudent != null : "Null parameter supplied to School.updateCourse()";
int result;
messagePane.println("The course(s) taken are: " + aStudent.getCourse());
messagePane.print("Now it is...: ");
String course = keyboard.nextLine();
result = aStudent.setCourse(course);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " + singleLineStudentDisplay(aStudent));
}
private void updateGpa(Student aStudent){
assert aStudent != null: "Null parameter supplied to School.updateGpa()";
int result;
messagePane.println("GPA is: " + aStudent.getGpa());
messagePane.print("Now it is... (Must be Postive Number): ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
double gpa;
if (inputScanner.hasNextDouble())
{
gpa = keyboard.nextDouble();
}
else
{
messagePane.println("You entered something other than a number - " +
"GPA is back to default " + Student.DEFAULT_GPA);
gpa = Student.DEFAULT_GPA;
}
result = aStudent.setGPA(gpa);
messagePane.println("Update status: " +
Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes" + singleLineStudentDisplay(aStudent));
}
private void gpa() {
int studentCount = nextAvailablePosition;
if (studentCount > 0) {
messagePane.println("\nThe student database has " + studentCount + " student(s):");
messagePane.printf(" %25s, %-35s (%4s, %13s) %-30s %9s \n",
"Grade/Standing", "Student's Name", "Birthday", "ID Number",
"Course(s) taken", "GPA");
int index = 0;
while (index < studentCount) {
Student temp = classroom[index];
messagePane.printf(" %25s, %-35s (%4d, %-13s) %-30s %9.2f \n",
temp.getGrade().length() < 25
? temp.getGrade() : temp.getGrade().substring(0, 25),
temp.getName().length() < 35
? temp.getName() : temp.getName().substring(0, 35),
temp.getBirthday(),
temp.getID(),
temp.getCourse().length() < 30
? temp.getCourse() : temp.getCourse().substring(0, 30),
temp.getGpa());
index++;
}
} else {
messagePane.println("The classroom is currently empty.");
}
}
private Student locateStudent() {
Student aStudent;
messagePane.print("\nEnter the Student's ID you would like to find: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNext()) {
String searchID = inputScanner.next();
aStudent = searchForStudentInArray(searchID);
} else {
messagePane.println("Please enter an ID");
aStudent = null;
}
return aStudent;
}
private String singleLineStudentDisplay(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.singleLineStudentDisplay()";
return aStudent.getGrade() + ", " + aStudent.getName() + " ("
+ aStudent.getID() + ", " + aStudent.getBirthday() + ") "
+ aStudent.getCourse() + " GPA: " + aStudent.getGpa();
}
}
Here is Student :
package student;
public class Student {
public static final int SET_SUCCESSFUL = 0;
public static final int GRADE_CANNOT_BE_NULL = -1;
public static final int GRADE_CANNOT_BE_EMPTY = -2;
public static final int GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS = -3;
public static final int NAME_CANNOT_BE_NULL = -11;
public static final int NAME_CANNOT_BE_EMPTY = -12;
public static final int BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT = -24;
public static final int ID_MUST_BE_ONE_OR_SEVEN_NUMBERS = -31;
public static final int ID_CANNOT_BE_NULL = -32;
public static final int ID_CANNOT_BE_EMPTY = -33;
public static final int COURSE_CANNOT_BE_EMPTY = -41;
public static final int GPA_CANNOT_BE_NEGATIVE = -51;
public static final double DEFAULT_GPA = 0.0;
private String name;
private String grade;
private int birthday;
private String id;
private String course;
private double gpa;
private Student() {
super();
}
public static Student create(String theName,
String theGrade, int theBirthday,String theId,
String theCourse, double theGpa) throws Exception {
Student newStudent = new Student();
int result;
result = newStudent.setName(theName);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setGrade(theGrade);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setBirthday(theBirthday);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setId(theId);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setCourse(theCourse);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setGPA(theGpa);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
return newStudent;}
// <editor-fold defaultstate="collapsed" desc="------------------------------------------------------------------------------"> /* */
// </editor-fold>
public String getName() {
return name;}
public String getGrade() {
return grade;}
public int getBirthday() {
return birthday;}
public String getID() {
return id;}
public String getCourse() {
return course;}
public double getGpa() {
return gpa;}
#Override
public String toString() {
StringBuilder temp = new StringBuilder(name);
temp.append("\nwho is a ");
temp.append(grade);
temp.append("\nwith a Birthday on ");
temp.append(birthday);
temp.append("\nID Number ");
temp.append(id);
temp.append("\nwho takes ");
temp.append(course);
temp.append("\nwith a GPA of ");
temp.append(gpa);
temp.append(' ');
return temp.toString();
}
public static String getDescriptionOfReturnedSignal(int aSignal) {
if (aSignal == SET_SUCCESSFUL) {
return "SET_SUCCESSFUL";}
if (aSignal == GRADE_CANNOT_BE_NULL) {
return "GRADE_CANNOT_BE_NULL";}
if (aSignal == GRADE_CANNOT_BE_EMPTY) {
return "GRADE_CANNOT_BE_EMPTY";}
if (aSignal == GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS) {
return "GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS";}
if (aSignal == NAME_CANNOT_BE_NULL) {
return "NAME_CANNOT_BE_NULL";}
if (aSignal == NAME_CANNOT_BE_EMPTY) {
return "NAME_CANNOT_BE_EMPTY";}
if (aSignal == BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT) {
return "BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT";}
if (aSignal == ID_CANNOT_BE_NULL) {
return "ID_CANNOT_BE_NULL";}
if (aSignal == ID_CANNOT_BE_EMPTY) {
return "ID_CANNOT_BE_EMPTY";}
if (aSignal == ID_MUST_BE_ONE_OR_SEVEN_NUMBERS) {
return "ID_MUST_BE_ONE_OR_SEVEN_NUMBERS";}
if (aSignal == COURSE_CANNOT_BE_EMPTY) {
return "COURSE_CANNOT_BE_EMPTY";}
if (aSignal == GPA_CANNOT_BE_NEGATIVE) {
return "GPA_CANNOT_BE_NEGATIVE";}
return "Sorry, but the signal value " + aSignal + " is not recognized.";
}
public int setName(String theName) {
if (theName == null) {
return NAME_CANNOT_BE_NULL;
}
String trimmedName = theName.trim();
if (trimmedName.isEmpty()) {
return NAME_CANNOT_BE_EMPTY;
}
name = trimmedName;
return SET_SUCCESSFUL;
}
public int setGrade(String theGrade) {
if (theGrade == null) {
return GRADE_CANNOT_BE_NULL;
}
String trimmedGrade = theGrade.trim();
if (trimmedGrade.isEmpty()) {
return GRADE_CANNOT_BE_EMPTY;
}
if (trimmedGrade.length() < 6) {
return GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS;
}
grade = trimmedGrade;
return SET_SUCCESSFUL;
}
public int setBirthday(int theBirthday) {
if (theBirthday <= 7) {
return BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT;
}
birthday = theBirthday;
return SET_SUCCESSFUL;
}
private int setId(String theId) {
if (theId == null) {
return ID_CANNOT_BE_NULL;
}
String trimmedId = theId.trim();
if (trimmedId.isEmpty()) {
return ID_CANNOT_BE_EMPTY;
}
if (trimmedId.length() != 1 && trimmedId.length() != 7) {
return ID_MUST_BE_ONE_OR_SEVEN_NUMBERS;
}
id = trimmedId;
return SET_SUCCESSFUL;
}
public int setCourse(String theCourse) {
if (theCourse == null) {
course = "";
return SET_SUCCESSFUL;
}
String trimmedCourse = theCourse.trim();
if (trimmedCourse.isEmpty()) {
return COURSE_CANNOT_BE_EMPTY;
}
course = trimmedCourse;
return SET_SUCCESSFUL;
}
public int setGPA(double theGPA) {
if (theGPA < 0.0) {
return GPA_CANNOT_BE_NEGATIVE;
}
gpa = theGPA;
return SET_SUCCESSFUL;
}
/*
public String getbirthday() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
*/
}
Don't have sufficient reputation to comment so adding as answer.
You must remove the current code and specify only the snippets that you tried for 1) Reading the inputs, which I see you are using Scanner 2) What's your approach for sorting
To guide you on this considering this is your classroom program, look at these:
How to read inputs:
How can I read input from the console using the Scanner class in Java?
Comparision:
https://www.baeldung.com/java-comparator-comparable
When should a class be Comparable and/or Comparator?
and then sorting:
https://www.geeksforgeeks.org/collections-sort-java-examples/
https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/

How to get the total of each column

Its been a ridiculous task especially to build the total of each vertical column & to show it on screen. Though, calculating the total of horizontal row never seemed to be a challenge.
The problem I'm having is three-fold.
How do I calculate the total of each vertical column ?
The index (id) is getting printed in descending order. How do I make it print in ascending order ?
Further, in the percentage column the value after the decimal point is being discarded. How do I get that displayed? For eg.. if
answer is supposed to be 78.25% it exhibits as 78.0%
P.S : (2 places after the decimal point is what I'm aiming at.)
POJO class -- StudentsProg.java
package com.students.marks;
import java.util.Arrays;
public class StudentsProg {
private int id = 0;
private String name;
private int english;
private int german;
private int french;
private int arabic;
private double percentage;
private int total_marks;
private int rowHighest;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getGerman() {
return german;
}
public void setGerman(int german) {
this.german = german;
}
public int getFrench() {
return french;
}
public void setFrench(int french) {
this.french = french;
}
public int getArabic() {
return arabic;
}
public void setArabic(int arabic) {
this.arabic = arabic;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public int getTotal_marks() {
return total_marks;
}
public void setTotal_marks(int total_marks) {
this.total_marks = total_marks;
}
public int getRowHighest() {
return rowHighest;
}
public void setRowHighest(int rowHighest) {
this.rowHighest = rowHighest;
}
public String toString() {
id = id+1;
return (id + "\t" +name+ "\t\t" +english+ "\t" + " " +german+ "\t" + " "+ french+ "\t" + " " +arabic+ "\t" +" " +total_marks+ "\t\t" + " " +percentage+ "\t\t" +rowHighest);
}
}
StudentsProgMain.java
import java.util.Scanner;
public class StudentsProgMain {
#SuppressWarnings("resource")
public static void main(String[] args) {
int count = 0;
StudentsProg[] stud = new StudentsProg[15];
int choice=0;
int max = 0;
Scanner scanner = new Scanner(System.in);
do{
System.out.println("1: Add new Student");
System.out.println("2: List Student");
System.out.println("3: List Student By Name.");
System.out.println("4: Delete Student");
System.out.println("5: Exit");
System.out.println("Please enter your choice \n\n");
choice=scanner.nextInt();
switch(choice){
case 1:
stud[count] = new StudentsProg();
System.out.println("Enter student name");
stud[count].setName(scanner.next());
System.out.println("Enter marks in English");
stud[count].setEnglish(scanner.nextInt());
System.out.println("Enter marks in German");
stud[count].setGerman(scanner.nextInt());
System.out.println("Enter marks in French");
stud[count].setFrench(scanner.nextInt());
System.out.println("Enter marks in Arabic");
stud[count].setArabic(scanner.nextInt());
count++;
break;
case 2:
System.out.println("ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i=0; i<count; i++){
if(stud[i]!=null){
int total_marks = stud[i].getEnglish()+stud[i].getGerman()+ stud[i].getFrench()+stud[i].getArabic();
stud[i].setTotal_marks(total_marks);
double calc_per = ((total_marks*100)/400);
stud[i].setPercentage(calc_per);
int arrayListMarks [] = {stud[i].getEnglish(), stud[i].getFrench(), stud[i].getGerman(), stud[i].getArabic()};
max = arrayListMarks[0];
for (int j = 1; j < arrayListMarks.length; j++) {
if(arrayListMarks[j] > max)
max = arrayListMarks[j]; }
stud[i].setRowHighest(max);
System.out.println(stud[i].toString());
System.out.println("\n");}
}
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
System.out.println("\tTotal :" +"\n");
break;
case 3 :
System.out.println("Please enter your name");
String name = scanner.next();
System.out.println("\n" + "ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i =0 ; i<count; i++){
if(stud[i]!=null && stud[i].getName().equals(name))
System.out.println(stud[i].toString()); }
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
break;
case 4 :
System.out.println("Please enter your name");
String naam = scanner.next();
for (int i = 0; i<count; i++) {
if(stud[i]!=null && stud[i].getName()==naam)
stud[i]=null;
}
break;
case 5:
System.exit(0);
System.out.println("You have exited successfully");
default :
System.out.println("Invalid choice");
}
}while(true);
}
}
The problem with the percentage calculation is that the line of code double calc_per = ((total_marks*100)/400); will do integer arithmetic and truncate each intermediate result as an integer. To fix this you need to include a floating point number somewhere in the calculation either by converting total_marks to double like so:
double calc_per = ((Integer.valueOf(total_marks).doubleValue()*100)/400);
Or using a float constant like so:
double calc_per = ((total_marks*100.0)/400);
Vertical totals should just be a matter of adding the row value to a variable inside your print loop.
I'm not really sure about your index order problem but the code in toString() that reads id = id+1; looks wrong. This will increment the Id each time you call toString(). Instead of that, your creation code should set the value of id just after creating the object, something like:
stud[count] = new StudentsProg();
// add the following line of code.
stud[count].setId(count);
System.out.println("Enter student name");
stud[count].setName(scanner.next());

Method cannot be applied to given types, trying to call my getMenuChoice() method

I'm trying to call my getMenuChoice() method in my main method to output the things in my getMenuChoice() method but it is telling me that the method cannot be applied to the given types; required: String, String found: no arguments
Why is this? Any help is appreciated, thanks.
package footballgame;
import java.util.Scanner;
public class FootballGame {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String footballTeam1;
String footballTeam2;
System.out.print("Enter a name for a team:");
footballTeam1 = keyboard.nextLine();
System.out.print("Enter a name for another team:");
footballTeam2 = keyboard.nextLine();
System.out.println("Game Score:");
System.out.println(footballTeam1 + ":0");
System.out.println(footballTeam2 + ":0");
choice = getMenuChoice();
}
public static String getMenuChoice(String footballTeam1,String footballTeam2){
String choice;
do{
System.out.println("Select an option:");
System.out.println("A:" + footballTeam1 + "scored");
System.out.println("B:" + footballTeam2 + "scored");
System.out.println("C: game ended.");
System.out.println("?:");
choice = keyboard.nextLine();
if (choice.equalsIgnoreCase("A")){
choice = (footballTeam1);
} else if (choice.equalsIgnoreCase("B")){
choice = (footballTeam2);
} else if (choice.equalsIgnoreCase("C")){
choice = ("Game over!");
}
}while(!choice.equals("A") && !choice.equals("B") && !choice.equals("C"));
return choice;
}
}
Here is my new code.
package footballgame;
import java.util.Scanner;
public class FootballGame { static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
String choice;
Scanner keyboard = new Scanner(System.in);
String footballTeam1;
String footballTeam2;
System.out.print("Enter a name for a team:");
footballTeam1 = keyboard.nextLine();
System.out.print("Enter a name for another team:");
footballTeam2 = keyboard.nextLine();
System.out.println("Game Score:");
System.out.println(footballTeam1 + ":0");
System.out.println(footballTeam2 + ":0");
choice = getMenuChoice(footballTeam1, footballTeam2);
}
public static String getMenuChoice(String footballTeam1,String footballTeam2){
String choice;
String input;
do{
System.out.println("Select an option:");
System.out.println("A:" + footballTeam1 + " scored");
System.out.println("B:" + footballTeam2 + " scored");
System.out.println("C: game ended.");
System.out.println("?:");
input = keyboard.nextLine();
if (input.equalsIgnoreCase("A")){
choice = (footballTeam1);
} else if (input.equalsIgnoreCase("B")){
choice = (footballTeam2);
} else if (input.equalsIgnoreCase("C")){
choice = ("Game over!");
}
}while(!input.equals("A") && !input.equals("B") && !input.equals("C"));
return choice;
}
}
Here's the my other class with the addscore method within it at the bottom.
public class FootballTeam {
private String name;
private int score;
public static int TOUCHDOWN = 6;
public static int FIELD_GOAL = 3;
public static int SAFETY = 2;
public static int TWO_POINT_CONVERSION = 2;
public static int EXTRA_POINT = 1;
public FootballTeam(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public boolean addScore(int points) {
if (points == TOUCHDOWN || points == FIELD_GOAL || points == SAFETY || points == TWO_POINT_CONVERSION || points == EXTRA_POINT) {
score = points + score;
return true;
} else {
return false;
}
}
}
You declared getMenuChoice(String footballTeam1,String footballTeam2)
That means that when calling this method you must give two String parameters:
choice = getMenuChoice(footballTeam1, footballTeam2);
BTW, choice is not declared. You need to declare it before (or when) assigning value to it:
String choice = getMenuChoice(footballTeam1, footballTeam2);
System.out.println("Game Score:");
System.out.println(footballTeam1 + ":0");
System.out.println(footballTeam2 + ":0");
choice = getMenuChoice(footballTeam1,footballTeam2);
You need to pass two String argument to getMenuChoice(); method.
Need to change
choice = getMenuChoice();
to
String choice = getMenuChoice(footballTeam1 ,footballTeam2);
System.out.println("Choice is :" + choice );
update
You are using && operator in your while condition that's not correct.
Replace with below one
while (!choice.equals("A") || !choice.equals("B")
|| !choice.equals("C"));
Once you found the matched value then no need to iterate again, You can return the matched value.
Your corrected method is below
public static String getMenuChoice(String footballTeam1,
String footballTeam2) {
String choice;
do {
System.out.println("Select an option:");
System.out.println("A:" + footballTeam1 + "scored");
System.out.println("B:" + footballTeam2 + "scored");
System.out.println("C: game ended.");
System.out.println("?:");
Scanner keyboard = null;
choice = keyboard.nextLine();
if (choice.equalsIgnoreCase("A")) {
return footballTeam1;
} else if (choice.equalsIgnoreCase("B")) {
return footballTeam2;
} else if (choice.equalsIgnoreCase("C")) {
return "Game over!";
}
} while (!choice.equals("A") || !choice.equals("B")
|| !choice.equals("C"));
return choice;
}
Run this code:
package footballgame;
import java.util.Scanner;
public class FootballGame { static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
String choice;
Scanner keyboard = new Scanner(System.in);
String footballTeam1;
String footballTeam2;
System.out.print("Enter a name for a team:");
footballTeam1 = keyboard.nextLine();
System.out.print("Enter a name for another team:");
footballTeam2 = keyboard.nextLine();
System.out.println("Game Score:");
System.out.println(footballTeam1 + ":0");
System.out.println(footballTeam2 + ":0");
choice = getMenuChoice(footballTeam1, footballTeam2);
}
public static String getMenuChoice(String footballTeam1,String footballTeam2){
String choice ="";
String input;
do{
System.out.println("Select an option:");
System.out.println("A:" + footballTeam1 + " scored");
System.out.println("B:" + footballTeam2 + " scored");
System.out.println("C: game ended.");
System.out.println("?:");
input = keyboard.nextLine();
if (input.equalsIgnoreCase("A")){
choice = (footballTeam1);
} else if (input.equalsIgnoreCase("B")){
choice = (footballTeam2);
} else if (input.equalsIgnoreCase("C")){
choice = ("Game over!");
}
}while(!input.equals("A") && !input.equals("B") && !input.equals("C"));
return choice;
}
}
And the log is:
A is what you need input
Enter a name for a team:A
Enter a name for another team:A
Game Score:
A:0
A:0
Select an option:
A:A scored
B:A scored
C: game ended.
?:
A //------------this place is what you need input to stop loop.
Process finished with exit code 0
Hand socre:
package footballgame;
import java.util.Scanner;
public class FootballTeam {
private String name;
private int score;
public static int TOUCHDOWN = 6;
public static int FIELD_GOAL = 3;
public static int SAFETY = 2;
public static int TWO_POINT_CONVERSION = 2;
public static int EXTRA_POINT = 1;
static Scanner keyboard = new Scanner(System.in);
public FootballTeam() {
}
public FootballTeam(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public boolean addScore(int points) {
if (points == TOUCHDOWN || points == FIELD_GOAL || points == SAFETY || points == TWO_POINT_CONVERSION || points == EXTRA_POINT) {
score = points + score;
return true;
} else {
return false;
}
}
public String toString() {
return this.getName() + ":" + this.getScore();
}
public static void main(String[] args) {
String choice;
FootballTeam teamA = new FootballTeam();
FootballTeam teamB = new FootballTeam();
System.out.print("Enter a name for a team A:");
teamA.setName(keyboard.nextLine());
System.out.print("Enter a name for another team B :");
teamB.setName(keyboard.nextLine());
System.out.print("Enter a source for a team A :");
teamA.setScore(Integer.valueOf(keyboard.nextLine()));
System.out.print("Enter a name for another team B:");
teamB.setScore(Integer.valueOf(keyboard.nextLine()));
System.out.println("Game Score:");
System.out.println(teamA.getName() + ":" + teamA.getScore());
System.out.println(teamB.getName() + ":" + teamB.getScore());
choice = getMenuChoice(teamA, teamB);
System.out.println(choice);
}
public static String getMenuChoice(FootballTeam teamA, FootballTeam teamB){
String choice ="";
String input;
do{
System.out.println("Select an option:");
System.out.println("A:" + teamA.getName() + " scored");
System.out.println("A:" + teamA.getName() + " scored");
System.out.println("C: game ended.");
System.out.println("?:");
input = keyboard.nextLine();
if (input.equalsIgnoreCase("A")){
choice = teamA.toString();
} else if (input.equalsIgnoreCase("B")){
choice = teamB.toString();
} else if (input.equalsIgnoreCase("C")){
choice = ("Game over!");
}
}while(!input.equals("A") && !input.equals("B") && !input.equals("C"));
return choice;
}
}

Categories

Resources