This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I am working on a project in Java that requests user inputs information like name, id, score in array.I need to help about calculate a average grade that user input and how to find out who have highest score. Here is my code:
package finalproject;
import java.util.Scanner;
/**
*
* #author vincephng
*/
public class FinalProject {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
Cis84[] student= new Cis84[50];
int option;
for (int c = 0; c<50;c++)
student[c]=new Cis84();
do{
System.out.print("");
System.out.println("1) Add Information");
System.out.println("2) Show report");
System.out.println("3) Exit");
System.out.print("\nEnter option: ");
option = input.nextInt();
switch(option)
{
case 1:
String n;
double g;
int index, i;
System.out.println("Which position of the student?");
index=input.nextInt();
System.out.println("What is the student's name:");
n=input.nextLine();
n=input.nextLine();
System.out.println("What is student's Id");
i=input.nextInt();
System.out.println("What is student's score");
g=input.nextDouble();
student[index].setName(n);
student[index].setGrade(g);
student[index].setId(i);
break;
case 2:
for(int c=0; c<50;c++)
System.out.println(student[c]);
break;
case 3:
System.out.println("You are done");
break;
default:
System.out.println("Try again");
break;
}
}while (option != 3);
}
}
and class
package finalproject;
public class Cis84
{
private String name;
private int id;
private double grade;
public Cis84()
{
name="not input yet";
id= 00000;
grade= 0.0;
}
public Cis84(String n, int i, double g)
{
name= n;
id= i;
grade=g;
}
public void setName(String n)
{
name=n;
}
public void setId(int i)
{
id=i;
}
public void setGrade(double g)
{
grade=g;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public double getGrade()
{
return grade;
}
public String toString()
{
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
}
Your toString method isn't defined correctly - it should be toString, with a lower case t, not ToString as you currently have. This is, by the way, why it's recommended to use the #Override annotation when overriding a superclass' method. In case you made a trivial mistake (such as a typo, or mixing up cases like you did here), the compiler would have alerted you that you're doing something wrong, instead of just allowing you to declare another method, which has nothing wrong with it per se, except for not being the method you want to override.
To sum up, here's how the code should look:
#Override // override annotation
public String toString() { // correct method name
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
Your error is here:
You wrote this:
public String ToString() {
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
And that is not the method toString() of the class object.. (note the difference in the name, java defines methods camelCase but you did it PascalCase)
You mean instead
#Override
public String toString() {
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
After that you will be able to see the content of student[c]
You should override public String toString() method for Cis84 class. Then you can use one of the following ways:
for(Cis84 std: student){
System.out.println(std);
}
or
Arrays.deepToString(student);
In place of
case 2:
for(int c=0; c<50;c++)
System.out.println(student[c]);
break;
Try this:
case 2:
for(int c=0; c<50;c++)
System.out.println(student[c].getName()+" "+student[c].getId()+" "+student[c].getGrade());
break;
You are printing the object but actually you want the data which is inside that object.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Average and Grade Calculation
Develop a smart application as Student Grade Calculator(SGC).
Create a class Student with following private attribute :
int id
String name
marks(integer array)
float average
char grade
Include appropriate getters and setters methods and constructor.
The getter method names should be getId, getName, getMarks, getAverage and getGrade and setter method names should be setId, setName, setMarks, setAverage and setGrade.
Write a public 3 argument constructor in the order – id, name and marks.
Write the below methods in Student class :
public void calculateAvg()- This method should calculate average and set average mark for the current student.
public void findGrade()- This method should set the grade based on the average calculated. If the average is between 80 and 100 then, then return grade as 'O', else 'A' .If the student gets less than 50 in any of the subjects then return grade as 'F'. Using appropriate setter method set the grade to the student.
(Note : number of subject should be greater than zero, if not display as 'Invalid number of subject' and get number of subject again, Assume mark for a subject should be in the range 0 - 100. If not display a message "Invalid Mark" and get the mark again)
Write a class StudentMain and write the main method.
In this class, write a method
public static Student getStudentDetails() - this method should get the input from the user for a student, create a student object with those details and return that object.
In main create student’s object by invoking the getStudentDetails method. Also calculate average and grade for that student object using appropriate methods.
SGC app should get the input and display the output as specified in the snapshot:
Sample Input 1:
Enter the id:
123
Enter the name:
Tom
Enter the no of subjects:
3
Enter mark for subject 1:
95
Enter mark for subject 2:
80
Enter mark for subject 3:
75
Sample Output 1:
Id:123
Name:Tom
Average:83.33
Grade:O
Sample Input 2:
Enter the id:
123
Enter the name:
Tom
Enter the no of subjects:
0
Invalid number of subject
Enter the no of subjects:
3
Enter mark for subject 1:
75
Enter mark for subject 2:
49
Enter mark for subject 3:
90
Sample Output 2:
Id:123
Name:Tom
Average:71.33
Grade:F
import java.util.*;
public class Student {
private int id;
private String name;
private int marks[];
private float average;
private char grade;
//Student(int id, String name, int marks[]){}
Student(){}
public void setId(int id) {
this.id =id;
}
public void setName(String name) {
this.name=name;
}
public void setMarks(int marks[]) {
this.marks =marks;
}
public void setAverage(float average) {
this.average=average;
}
public void setGrade(char grade) {
System.out.println("grade");
this.grade=grade;
}
public void calculateAvg() {
float average = (Arrays.stream(marks).sum())/(marks.length);
Student student = new Student();
student.setAverage(average);
}
public void findGrade() {
Student sm = new Student();
if(average>80.0 && average <= 100.0) {
sm.setGrade('O');
}
else if(average<50) {
sm.setGrade('F');
}
else
sm.setGrade('A');
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int[] getMarks() {
return marks;
}
public float getAverage() {
System.out.println("average");
return average;
}
public char getGrade() {
System.out.println("null");
return grade;
}
}
import java.util.Scanner;
public class StudentMain {
public static void main(String[] args) {
StudentMain object = new StudentMain();
object.getStudentDetails();
}
public static Student getStudentDetails() {
int i; int m[] = new int[100];
Scanner sc = new Scanner(System.in);
Student student = new Student();
System.out.println("Enter the id:");
int id= sc.nextInt();
student.setId(id);sc.nextLine();
System.out.println("Enter the name:");
student.setName(sc.nextLine());
do {
System.out.println("Enter the no of subjects:");
i = sc.nextInt();
if(i==0) {
System.out.println("Invalid number of subject");
}
}while(i==0);
for(int j = 1;j<=i;j++) {
System.out.println("Enter mark for subject "+j+":");
m[j-1]=sc.nextInt();
}
student.setMarks(m);
System.out.println("Id:"+student.getId());
System.out.println("Name:"+student.getName());
System.out.println("Average:"+student.getAverage());
System.out.println("Grade:"+student.getGrade());
return student;
}
}
After running the code, I figured out that setMarks(m) is not passing the array to the method present in Student class, and output is
Id:
name :
Avg:0.0
Grade:
The Avg and Grade is not giving expected output.enter code here
You must setAverage(). Since it is calculateAvg(int m[]) which does the work,
student.setMarks(m);
student.setAverage(student.calculateAvg(m)); // add this line
System.out.println("Id:"+student.getId());
System.out.println("Name:"+student.getName());
System.out.println("Average:"+student.getAverage());
System.out.println("Grade:"+student.getGrade());
To improve, your work states to have a public void calculateAvg(), for that, no need to pass marks[], but directly modify the internal average
// firstly remove parameter and update internal average
public void calculateAvg() {
this.average = ((float) Arrays.stream(marks).sum()) / (marks.length);
// OR as spotted by #Lino
// this.average = (float) Arrays.stream(marks).asDoubleStream().average().orElse(0.0);
}
// secondly, in your main, just call calculateAvg()
student.setMarks(m);
student.calculateAvg();
System.out.println("Id:"+student.getId());
System.out.println("Name:"+student.getName());
System.out.println("Average:"+student.getAverage());
System.out.println("Grade:"+student.getGrade());
return student;
You said you "figured out that setMarks(m) is not passing the array to the method present in Student class". What makes you think this is the case?
Your getAverage() method returns the value of the field average. Where does this field get set?
You should debug your class by single-stepping through it in a debugger. If you haven't learned how to use a debugger yet, just put some temporary System.out.println traces. But it would be very worthwhile learning to use a debugger.
So I have this assignment which is meant to simulate passengers waiting at a boarding gate and we need to create a menu with different options. For it we have to have two classes and a main program and the entire thing is supposed to be based on a circular queue.
While attempting to do the circular queue, I stumbled upon the problem mentioned in the title. When I add items to the queue, once I attempt to display them with the option from the menu, the queue pops the first item, which is not meant to do unless the option delete from the menu is called. Furthermore, if I call the delete and view options, the queue deletes two items. To summarize:
I have no idea why my view option acts as a delete option
Any suggestions as to how to resolve this are appreciated because I've been trying for hours on end, I re-wrote the passenger queue class a few times in different ways, yet still the same and currently I have no idea how to resolve it.
The program is as it follows:
Main:
public class Airport {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
PassengerQueue queue1= new PassengerQueue();
Passenger[] ArrayOfPassenger = new Passenger[20];
Scanner input= new Scanner (System.in);
String optionMenu;
for (int i=0; i<20; i++)
ArrayOfPassenger[i]= new Passenger();
char letter;
do {
System.out.println("Enter display option [A-add passenger, V- view passenger queue, D- delete passenger from queue, S- store passengerQueue data into file, L- load passengerQueue data from file] or 'X' to stop: ");
optionMenu = input.next();
letter = optionMenu.charAt(0);
switch (letter) {
case 'A':
queue1.AddPassenger();
break;
case 'V':
queue1.display();
case 'D':
queue1.removePassenger();
break;
case 'S':
break;
case 'L':
break;
}
} while (letter != 'X');
}
}
Passenger class:
public class Passenger {
private String firstName;
private String surname;
private int secondsInQueue;
Scanner input= new Scanner(System.in);
/**
*
* #return
*/
public String getname(){
return firstName= " "+surname;
}
public void setName (String fName, String sName){
firstName=fName;
surname=sName;
}
public Passenger (){
firstName= "";
surname="";
}
public String toString() {
return firstName + " " + surname;
}
And PassengerQueue class, which is having the issue:
public class PassengerQueue {
Scanner input= new Scanner(System.in);
private Passenger[] qArray =new Passenger [20];
private int first = 0;
private int last = 0;
private int maxStayInQueue;
static final int MAX_QUEUE_SIZE = 20;
public PassengerQueue() {
for (int i = 0;i < 20; i++)
qArray[i]= new Passenger();
}
public void AddPassenger() {
System.out.println("Enter passenger's First Name:");
String FirstName = input.next();
System.out.println("Enter passenger's surname:");
String Surname= input.next();
qArray[last].setName(FirstName, Surname);
last++;
if(last == qArray.length+1){
last = 0;
}
}
public boolean isEmpty() {
return first == 0;
}
public boolean isFull() {
return last == 19;
}
public void removePassenger(){
Passenger x;
x= qArray[first];
qArray[first].setName("","");
first=first+1;
if(first==qArray.length+1)
first=0;
}
public void display() {
System.out.println("The queue: ");
for(int i = first; i < last; i++)
System.out.println(qArray[i]);
}
}
You miss the break; statement after
queue1.display(); in class Airport main method.
So the next case'D' executed.
I set up a method to increase the age of a Pet by 1 each time its called upon but for some reason, it is giving me the age originally set.
Here is the file with my methods and classes listed:
public class Pet
{
String Name;
int Age;
String AdoptionStatus;
String True="not adopted";
public Pet(){
}
public Pet(String Name,int Age){
this.Name=Name;
this.Age=Age;
}
public void SetName(String namesetup){
namesetup=Name;
}
public String GetName(){
return Name;
}
public int GetAge(){
return Age;
}
public int ageincrease(){
return Age+1;
}
public String Getadoptionstatus(){
return AdoptionStatus;
}
public void Setadoptionstatus(String setadoption2){
AdoptionStatus=True;
}
}
Here is the other class where the ageincrease() is called but ends up giving me zero:
public class MainPets
{
static Scanner scan = new Scanner(System.in);
private static String Userinput;
private static void mainmenu(){
System.out.println("A."+" " + "List the pets in the store.");
System.out.println("B."+" " + "Age up the pets");
System.out.println("C."+" " + "Add a new pet");
System.out.println("D."+" " + "Adopt a pet");
System.out.println("E."+" " + "Quit");
Userinput=scan.nextLine();
}
public static String Getuserinput(){
return Userinput;
}
public static void main (String [] args){
int Pet3age;
String Pet3name;
Pet Pet1=new Pet("Fido",3);
Pet Pet2=new Pet("furball",1);
Pet Pet3=null;
System.out.println("Welcome to the pet store.Type the letter to make your selection");
MainPets.mainmenu();
while (Userinput.equals("E")||Userinput.equals("A")||Userinput.equals("B")||Userinput.equals("C")||Userinput.equals("D")){
if (Userinput.equals("E")){
System.out.println("Have a good day!");
break;
}
else if(Userinput.equals("A")){
System.out.println("Fido is "+Pet1.GetAge()+ " years old and is " + Pet1.Getadoptionstatus());
System.out.println("furball is " + Pet2.GetAge()+ " years old and is " + Pet2.Getadoptionstatus());
Userinput=scan.nextLine();
}
if(Userinput.equals("B")){
System.out.println("Everyone just got a little older.");
Pet1.ageincrease();//Still keeps Pet1 age to 3
Pet2.ageincrease();//Still keeps Pet2 age to 1
Userinput=scan.nextLine();
}
else if (Userinput.equals("C")){
System.out.println("Please type in a name");
Pet3name=scan.nextLine();
System.out.println("Please type in an age");
Pet3age=scan.nextInt();
Userinput=scan.nextLine();
}
}
}
}
I cleaned up the code for you a little bit.
To answer your question first: You were returning the Age of the pet plus 1, not actually asigning a new value to the Pet's Age. To do this, use Age++ or Age = Age + 1 or Age += 1. This should assign a new value to the Pet's age, thus fixing your issue.
Here are the changes I've made:
Condensed the String declarations to one line
Fixed SetName(String namesetup). You had the statment namesetup=Name, which assigns the Name field of the class to the instance variable namesetup of the method. You want to assign what was passed to the method to the class which is done by Name=namesetup
Changed the return statement in ageincrease() to return Age++; instead of return Age + 1;. This is the same as Age = Age + 1;
Replaced the long while loop in the main class with a switch statement and a while loop. This is convenient because you don't need a long condition check in the while loop. I used a flag variable that flags when the user inputs "E". If you're unfamiliar with switch statements, then you can readup on them here.
Notes and concerns:
With your current code, you check for the condition Userinput.equals("D") in the while loop, but you have nothing in the while loop to handle that condition, which leaves a possibility for an infinite loop.
I'm not going to change the names of your variables or methods, but you should know that the convention is variableName, where the first word is lowercase and the all the following have the first letter uppercased. Your variable and method names are inconsitent with this convention in your code, which can make it confusing for other coders to read and use. Following this convention is a good coding practice that can save you headaches on larger projects.
Here's your edited Pet class:
public class Pet {
String Name, AdoptionStatus, True = "not adopted";
int Age;
public Pet() {}
public Pet(String Name, int Age) {
this.Name = Name;
this.Age = Age;
}
public void SetName(String namesetup) {
Name = namesetup;
}
public String GetName() {
return Name;
}
public int GetAge() {
return Age;
}
public int ageincrease() {
return Age++;
}
public String Getadoptionstatus() {
return AdoptionStatus;
}
public void Setadoptionstatus(String setadoption2) {
AdoptionStatus = True;
}
}
And here's what I replaced the your while loop with:
int flag = 0;
while(flag != -1) {
switch(Userinput) {
case "A":
System.out.println("Fido is "+Pet1.GetAge()+ " years old and is " + Pet1.Getadoptionstatus());
System.out.println("furball is " + Pet2.GetAge()+ " years old and is " + Pet2.Getadoptionstatus());
Userinput=scan.nextLine();
break;
case "B":
System.out.println("Everyone just got a little older.");
Pet1.ageincrease();//Still keeps Pet1 age to 3
Pet2.ageincrease();//Still keeps Pet2 age to 1
System.out.println(Pet1.GetAge() + " " + Pet2.GetAge());
Userinput=scan.nextLine();
break;
case "C":
System.out.println("Please type in a name");
Pet3name=scan.nextLine();
System.out.println("Please type in an age");
Pet3age=scan.nextInt();
Userinput=scan.nextLine();
break;
case "D":
//Not sure how you want to implement this
break;
case "E":
flag = -1;
break;
}
}
I have made an array from class student
student [] stu=new student[100];
I'm in class student op and I want to insert name and code from method insert to array stu.
Until now everything worked, but when I want to get my name and code from another method like delete in class student op, it shows that my array stu is empty. Where is the problem? if I delet the line
stu[0]=new student();
in delet method Net beans show an error!!
public class studentop {
student [] stu=new student[100];
private int counter=0;
int con=0;
public int edd;
public void insert(int edame){
String ans;
Scanner input=new Scanner(System.in);
for(int i=edame;i<100;i++){
System.out.println("add more student? ");
ans=input.next();
if(ans.equals("y")){
String thename;
stu[i]=new student();
System.out.println("insert name "+(i+1)+" : ");
thename = input.next();
stu[i].setname(thename);
System.out.println("insert code "+(i+1)+" : ");
int thecode;
thecode = input.nextInt();
stu[i].setcode(thecode);
System.out.println(stu[i].getcode());
for(int m=0;m<=3;m++){
System.out.println("add mark "+(m+1)+" ? ");
String ans2;
ans2=input.next();
if(ans2.equals("y")){
switch (m){
case 0:
System.out.println("mark"+(m+1)+" : ");
int mark;
mark=input.nextInt();
stu[i].setmark(mark);
break;
case 1:
System.out.println("mark"+(m+1)+" : ");
// int mark;
mark=input.nextInt();
stu[i].setMark2(mark);
break;
case 2:
System.out.println("mark"+(m+1)+" : ");
// int mark;
mark=input.nextInt();
stu[i].setMark3(mark);
break;
case 3:
System.out.println("mark"+(m+1)+" : ");
// int mark;
mark=input.nextInt();
stu[i].setMark4(mark);
break;
}
}
else{
break;
}
}
System.out.println(stu[i].getname());//aztarighe get name az
}
else {
edame=i;
edd=edame;
break;
}
}//end for
}
public void delete(){
stu[0]=new student();//if I delet this line it shows an error!
System.out.println(stu[0].getcode());
}
}
and here is my class student
public class student {
public String name;
public int code;
public double mark;
private double mark2;
private double mark3;
private double mark4;
public void setname(String sourcename){
name=sourcename;
}
public String getname(){
return name;
}
It is not empty, however, when you try to get the student from the array you're creating a new student that's why it appears to be empty:
public void delete()
{
stu[0]=new student(); //here you're deleting your old student
System.out.println(stu[0].getcode());
}
Instead you could use:
public void delete()
{
System.out.println(stu[0].getcode());
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I just learned about constructors and had to use them in a recent program. I got it right however I still do not understand exactly what they do. If someone could give me a detailed explanation using this program as reference that would be great!
MAIN CLASS
public class Student
{
public static void main(String[]args)
{
String question, name, GPAStr, studentNumberStr;
int studentNumber;
double GPA;
question = JOptionPane.showInputDialog("Would you like to see if you Qualify for the Dean's List? (Y or N)");
while (question.equalsIgnoreCase("Y"))
{
name = JOptionPane.showInputDialog("Please enter your name.");
studentNumberStr = JOptionPane.showInputDialog("Please enter your student number.");
studentNumber = Integer.parseInt(studentNumberStr);
GPAStr = JOptionPane.showInputDialog("Please enter your GPA.");
GPA = Double.parseDouble(GPAStr);
StudentIO students = new StudentIO(name, GPA);
// ouput
JOptionPane.showMessageDialog(null, students.getDeansList());
question = JOptionPane.showInputDialog("Would you like to see if you Qualify for the Dean's List? (Y or N)");
if (question.equalsIgnoreCase("N"))
//display the content of players processed
{
JOptionPane.showMessageDialog(null,StudentIO.getCount());
}
}
}
}
SECOND CLASS(THE ONE WITH CONSTRUCTORS THEY ARE LABELED)
public class StudentIO
{
//instance fields
private String name;
private double GPA;
// static fields
private static final double GPAMIN=3.0;
private static int count = 0;
public StudentIO(String theName, double theGPA) // constructor
{
name = theName;
GPA= theGPA;
count = count +1;
}
public StudentIO() //no arg constructor
{
name = " ";
GPA = 0;
count = count +1;
}
public void setName(String theName)
{
name = theName;
}
public void setGPA(double theGPA)
{
GPA = theGPA;
}
public String getName()
{
return name;
}
public double getGPA()
{
return GPA;
}
public String getDeansList()
{
if(GPA >= GPAMIN)
return (name + ", has made the Dean's List!");
else
return(name + ", did not make the Dean's List!");
}
public static String getCount()
{
return ("You processed " + count + "students.");
}
}
StudentIO students = new StudentIO(name, GPA);
Will create a StudentIO object called students, and affect name and GPA parameters to your object created by using the first contractor:
public StudentIO(String theName, double theGPA) // constructor
{
name = theName;
GPA= theGPA;
count = count +1;
}
And that is equivalent to call :
StudentIO students = new StudentIO();
students.setName(name);
students.setGPA(GPA);
which will use the seconde contractor :
public StudentIO() //no arg constructor
{
name = " ";
GPA = 0;
count = count +1;
}
with the two methods
public void setName(String theName)
{
name = theName;
}
public void setGPA(double theGPA)
{
GPA = theGPA;
}
Finaly, the two approach give you the same result, its a style matter, and some times we are forced to use the seconds one in a strong coupled objects.
count = count +1;
It seems you are referring to this line in the constructors. The variable count is a static member in StudentIO class and is being used to keep track of number of StudentIO objects created using the parameterized or default constructor.
The construct instances of the StudentIO class. Their purpose is to set initial state for the new instance(s) of StudentIO. Each instance has its' own state. Static variables are shared among instances, so on each construction you're adding one to a count. It'll tell you how many instance(s) have been created (I guess).