Method not working properly when called upon? - java

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;
}
}

Related

Print a specific cell from a string array

I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).
I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.
I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".
(Yes, I tested this when I already inserted some data.)
Here's the full code:
package appartamento;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Appartamento {
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyb = new BufferedReader(input);
boolean attiva = true;
do {
System.out.println("what do you want to do?");
System.out.println("1 - check for a person");
System.out.println("2 - Add person");
int choice = Integer.parseInt(keyb.readLine());
Datiutente du[] = new Datiutente[10];
if (choice == 2){
System.out.println("How many people?");
int hm = Integer.parseInt(keyb.readLine());
for (int i=0;i<hm;i++){
du[i] = new Datiutente();
System.out.println("insert name:");
du[i].setName(keyb.readLine());
System.out.println("insert surname");
du[i].setSurname(keyb.readLine());
}
}
if (choice == 1){
System.out.println("which person are you searching?");
int vd = Integer.parseInt(keyb.readLine());
System.out.println("position: " + i);
System.out.println("Name: "+ du[i]);
System.out.println("Surname: " + du[i]);
}
} while (attiva = true);
}
}
and the class "Datiutente":
package appartamento;
public class Datiutente {
private String name;
private String surname;
private String codfis;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSurname(String surname){
this.surname = surname;
}
public String getSurname(){
return surname;
}
}
In every iteration you define the Datiutente du[] = new Datiutente[10];, so du is reset to {null,...,null} and the data saved in the previous iteration are replaced;
Try to define the array before the loop statement.
I found a way here:
You need to insert values on object creation, you can also use hashmaps
hashmap will benefit you more I think.
Code sample to fix your stuff.
class GFG {
public static void main(String args[]){
// Declaring an array of student
Student[] arr;
// Allocating memory for 2 objects
// of type student
arr = new Student[2];
// Initializing the first element
// of the array
arr[0] = new Student(1701289270, "Satyabrata");
// Initializing the second element
// of the array
arr[1] = new Student(1701289219, "Omm Prasad");
// Displaying the student data
System.out.println(
"Student data in student arr 0: ");
arr[0].display();
System.out.println(
"Student data in student arr 1: ");
arr[1].display();
}
}
class Student {
public int id;
public String name;
// Student class constructor
Student(int id, String name)
{
this.id = id;
this.name = name;
}
// display() method to display
// the student data
public void display()
{
System.out.println("Student id is: " + id + " "
+ "and Student name is: "
+ name);
System.out.println();
}
}

Suspended uncaught exception Thread [main] (Suspended (uncaught exception InputMismatchException))

I'm just practicing java and at the moment I am currently experimenting with getter/setter methods and constructors. The java program works as I am able to store the user inputs into the object but when I input the String "Dice and rollers" into the gametype string variable, a Suspended uncaught exception InputMismatch error comes up.
This is the error I'm getting whenever I input "Dice and Rollers"
However, if I use String variables that does not include spaces, it works fine.
Can someone please explain to me why this is?
Ps. I've shared my source code below.
package test;
import java.util.Scanner;
public class Test8a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the following information: Boardgame name, Alternative Name, Game Type, Year Released, Price and Maximum amount of Players");
String name = in.next();
String secondaryname = in.next();
String type = in.next();
int date = in.nextInt();
double price = in.nextDouble();
int player = in.nextInt();
System.out.println();
new Test8b(name, secondaryname, type, date, price, player);
}
}
The one above is the superclass while the source code below is the constructor and getter/setter java file.
package test;
public class Test8b {
private String boardname;
private String secondaryname;
private String gametype;
private int date;
private double price;
private int numberofPlayers;
public Test8b(String boardname, String secondaryname, String gametype, int date, double price, int players) {
setBoardname(boardname);
setSecondaryname(secondaryname);
setGametype(gametype);
setDate(date);
setPrice(price);
setNumberofPlayers(players);
this.printDetails();
}
public String getBoardname() {
return boardname;
}
public String getSecondaryname() {
return secondaryname;
}
public String getGametype() {
return gametype;
}
public int getDate() {
return date;
}
public double getPrice() {
return price;
}
public int getNumberofPlayers() {
return numberofPlayers;
}
public void setBoardname(String boardname) {
if (boardname.length() >= 15) {
System.out.println("There is no boardgame with this name length! Please enter a valid name!");
} else this.boardname = boardname;
}
public void setSecondaryname (String secondaryname) {
if (secondaryname.length() >= 15) {
System.out.println("There is no boardgame with this name length! Please enter a valid name!");
} else this.secondaryname = secondaryname;
}
public void setGametype(String gametype) {
this.gametype = gametype;
}
public void setDate(int date) {
if (date > 2021) {
System.out.println("This game haven't been invented yet or are you a time traveller?");
} else this.date = date;
}
public void setPrice(double price) {
if (price <= 0) {
System.out.println("Can't give away free games!");
} else this.price = price;
}
public void setNumberofPlayers(int numberofPlayers) {
if (numberofPlayers <= 0) {
System.out.println("Need someone to play the game!");
} else this.numberofPlayers = numberofPlayers;
}
public void printDetails() {
System.out.print(
"Board Game: " + this.getBoardname() + "\n" +
"Alternative Title: " + this.getSecondaryname() + "\n" +
"Game Type: " + this.getGametype() + "\n" +
"Year Released: " + this.getDate() + "\n" +
"Price: " + this.getPrice() + "\n" +
"Maximum # of Players: " + this.getNumberofPlayers() + "\n"
);
}
}
The exception is being thrown by the Scanner object's next() method because the input when you enter a string with spaces does not match the Scanner's default delimiter pattern used for scanning. When you enter a String with spaces, the Scanner sees a line of characters, not just one word of input. In other words, it it differentiates between a single word and a line of words separated by white spaces.
The java.util.Scanner.nextLine() method advances the scanner past the current line and returns the input that was skipped and is the method you should use to scan the game type. Modify your code to use Scanner.nextLine() for the game type and any other type that may have multiple words in it.

Classes within java

So I took everyone's feedback and information and have spent quite a bit of time trying to work on my code prior to submitting. Here are the changes that I have:
import java.util.*;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
class Automobiles {
String make;
String model;
String color;
int year;
int mileage;
int i;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public void setMake(String make) {
this.make = make;
}
public Automobiles() {
make = "";
model = "";
color = "";
year = 0;
mileage = 0;
}
public void Inventory(String make, String model, String color, int year, int mileage) {
System.out.println("Car is: " + make + " " + model + " " + color + " " + year + " " + mileage);
}
String getMake() {
return make;
}
}
public class AutomobileInventory {
public static void main(String[] args)
{
Automobiles[] carInventory = new Automobiles[15];
int i;
String fileName = "out.txt";
boolean quit = false;
String quit1 = "No";
Scanner scnr = new Scanner(System.in);
while (quit1 != "Yes") {
for(i=0; i<carInventory.length; i++) {
carInventory[i] = new Automobiles();
System.out.println("");
System.out.println("Please Enter the make of the vehicle: ");
carInventory[i].make = scnr.nextLine();
System.out.println("Please Enter the model of the vehicle: ");
carInventory[i].model = scnr.nextLine();
System.out.println("Please Enter the vehicle color: ");
carInventory[i].color = scnr.nextLine();
System.out.println("Please Enter the year of the vehicle: ");
carInventory[i].year = scnr.nextInt();
System.out.println("Please Enter the vehicle's mileage: ");
carInventory[i].mileage = scnr.nextInt();
System.out.println("Are you done? Yes or No");
quit1 = scnr.nextLine();
}
}
for(i=0; i<carInventory.length; i++)
System.out.println(carInventory[i].make + " " + carInventory[i].model + " " + carInventory[i].color + " " + carInventory[i].year + " " + carInventory[i].mileage);
try {
PrintWriter outputstream = new PrintWriter(fileName);
outputstream.println(carInventory[i].make + " " + carInventory[i].model + " " + carInventory[i].color + " " + carInventory[i].year + " " + carInventory[i].mileage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am running into an issue now that as it completes the loop the first and second instance are combining and it is not allowing me to enter a string for Make each time. Also when I printed to a file it only printed one instance and not all of the instances. Any help is appreciated.
Because you aren't initializing the quit variable, and are using a do-while loop, the loop executes once without checking if quit = "quit". This causes the loop to appear to execute fine, but then crash on the second iteration.
If we examine the structure of how the loop executes:
1) Print "Car Model:"
2) Print "Car Make:"
3) Print "Car Color:"
4) Print "Car Year:"
5) Print "Car Mileage:"
6) Execute For loop
7) Evaluate whether quit == "quit"
8) Print "Car Model"
9) Etc...
When step #7 attempts to evaluate the equality, it is actually performing this comparison:
!null.equalsIgnoreCase("quit"));
Because above in the code, the variable quit was never initialized, and is still set to null. The two code snippets below are in essence equivalent:
// Initialization without assignment:
String quit;
// Explicit initialization to null:
String quitTwo = null;
// Output
print quit
// >> NullPointerException
print quitTwo
// >> NullPointerException
Your Automobile class is fine.
In your automobileInventory class, your are initializing static data member in a non-static method (Check the function where you are initializing the automobiles array).
You can simply initialize it where you are declaring it i.e.:
private static Automobile[] automobiles = new Automobile[ INVENTORY_SIZE ];
Another way is to initialize it in a static block i.e.:
private static Automobile[] automobiles;
static {
automobiles = new Automobile[ INVENTORY_SIZE ];
}
Another way is to initialize it in your function before your loop.
In your sentinel-controlled loop, you are checking exit condition on quit variable but you are not assigning it anything. You need to get value from user whether he/she intends to quit or not.
Here's an example:
String quit; // In your function; not a class member
do {
// ... Rest of your code ...
System.out.println("Do you want to quit [Yes/No]? ");
quit = scnr.nextLine();
}
while ( !quit.equalsIgnoreCase("yes") );
And, you need to take care of your array instance of automobiles that it is correctly being populated. You need to take care of its index that it remains valid.
String quit; // In your function; not a class member
int i = 0;
do {
// ... Rest of your code ...
if ( i < INVENTORY_SIZE ) {
automobiles[i] = new Automobile(make, model, color, year, mileage);
i++;
}
else {
// ... Display error message here that array is full ...
// ... You can then break this loop to exit if you want to ...
break;
}
System.out.println("Do you want to quit [Yes/No]? ");
quit = scnr.nextLine();
}
while ( !quit.equalsIgnoreCase("yes") );
Here's your working code: https://ideone.com/JqX9Y9
Some of the lines are commented for my own testing. You can easily correlate the changes with this answer and figure out yourself what is going on.
Best of luck!
Happy coding!
As #kushagra mentioned, you need to initialize your quit variable. It's currently null, hence the NullPointerException (trying to call a method that doesn't yet exist for your variable)
One tip regarding your quit variable though, I would change it to type boolean since all you need is a true/false. This way, you don't have to do any string comparisons. It would look something like this:
boolean quit = false;
...
do { /* loop stuff */ }
while(quit != true);
Then in your do loop, you can add logic to change your quit variable to true when your user is ready to quit.
Regarding your inventory, I wouldn't use an array if you don't have to; I would use a list (arrays can't change size, whereas lists can). Then instead of using your for loop (you're already looping with your do-while - makes it a little redundant), you can add a new automobile to your list where you currently have it commented out. It would look something like this:
private static List<Automobile> automobiles;
...
automobiles.add(new Automobile(make, model, Color, year, mileage));
UPDATE
Your code is pretty messy - make sure you're consistent with your tabbing/spacing/etc. You should also come up with a clean way of organizing your methods. For example, I like to keep all my getters and setters together with constructors right below the class properties. The bottom of the class is where I like to keep general class methods, overridden methods, etc.
One issue you have with your code is in your main(...); try not to loop within loops if you don't have to (obviously there are always exceptions, such as multidimensional arrays, traversing "grids", etc) - this can slow down execution quite a bit (check out Big O notation - this is a pretty good article: https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/). This will also help you keep track of when your loop closes.
Your file write only happens once because you're not looping (this is where consistent indentation/spacing may help you).
Couple more quick tips: whenever you reuse a value, make a variable for it. You did this a few times, but there were several instances where you could have used a variable (remember: method calls take time to run, so limiting redundant calls will speed up your program). Also, don't be afraid to override the toString() method in your classes - the automobiles class is actually a really good use case for it.
I tried not to give you all the answers, but I've rewritten your code a bit to help you get going:
import java.util.ArrayList;
import java.util.List;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
class Automobiles {
String color = "";
String make = "";
String mileage = "";
String model = "";
String year = "";
// -------------------- getters -------------------- //
public String getColor() { return color; }
public String getMake() { return make; }
public String getModel() { return model; }
public String getMileage() { return mileage; }
public String getYear() { return year; }
// -------------------- setters -------------------- //
public void setColor(String color) { this.color = color; }
public void setMake(String make) { this.make = make; }
public void setMileage(String mileage) { this.mileage = mileage; }
public void setModel(String model) { this.model = model; }
public void setYear(String year) { this.year = year; }
#Override
public String toString() {
return year + " " + model + " " + make;
}// end toString()
}// end class Automobiles
public class AutomobileInventory {
public static void main(String[] args) {
List<Automobiles> carInventory = new ArrayList<>();
String fileName = "out.txt";
boolean quit = false;
Scanner scnr = new Scanner(System.in);
do {
Automobiles car = new Automobiles();
System.out.println("Please Enter the year of the vehicle: ");
car.setYear(scnr.nextLine());
System.out.println("Please Enter the make of the vehicle: ");
car.setMake(scnr.nextLine());
System.out.println("Please Enter the model of the vehicle: ");
car.setModel(scnr.nextLine());
System.out.println("Please Enter the vehicle color: ");
car.setColor(scnr.nextLine());
System.out.println("Please Enter the vehicle's mileage: ");
car.setMileage(scnr.nextLine());
carInventory.add(car);
System.out.println("Are you done? Yes or No");
quit = "yes".equals(scnr.nextLine().trim().toLowerCase()) ? true : false;
} while(quit == false);// end do-while-loop
int numCars = carInventory.size();
for(int i = 0; i < numCars; i++) {
String currentCar = carInventory.get(i).toString();
System.out.println(currentCar);
try {
PrintWriter outputstream = new PrintWriter(fileName);
outputstream.println(currentCar);
} catch( FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// end try-catch
}// end for-loop
}// end main(String[] args)
}// end class AutomobileInventory

Loop ending abruptly and Java not saving object?

So I'm having a problem with my code where my loop is ending for after my "C" case. I need it to print out a message saying the store is full and keep loop back up and print out the main menu. Also, my Pet3 is not being saved when I list all the pets after adding a new one. My
import java.util.*;
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);
int Userinputint;
Pet Pet3=null;
System.out.println("Welcome to the pet store.Type the letter to make your selection");
MainPets.mainmenu();
while(Userinput.equals("A")||Userinput.equals("B")||Userinput.equals("C")||Userinput.equals("D")||Userinput.equals("E")){
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();
case "B":
System.out.println("Everyone just got a little older.");
Pet1.ageincrease();
Pet2.ageincrease();
Userinput=scan.nextLine();
case "C":
if (Pet3!=null){
System.out.println("Sorry the store is full");
Userinput=scan.nextLine();
}/* If the Pet 3 spot has been filled I want it to print this
and loop back up to print the main menu again.*/
if(Pet3==null){
System.out.println("Please type in a name");
Pet3name=scan.nextLine();
System.out.println("Please type in an age");
Pet3age=scan.nextInt();
Pet3=new Pet(Pet3name,Pet3age);/*This line is Not saving Pet3 as
a "Pet" class and when I try to list all the pets by pressing
A when it loops back up , Pet3 does not show up as a Pet*/
Userinput=scan.nextLine();/* This is where my program just
ends.It doesn't even take a user input */
}
case "D":
//will add later on
break;
case "E":
//will add later on
break;
}
}
Here is the code for my 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;
}
}
Your loop is extting when Pet3!=null because you are not taking any input from the scanner after it.
Take input in both conditions inside case "C":
if (Pet3!=null){
System.out.println("Sorry the store is full");
} else {
System.out.println("Please type in a name");
Pet3name=scan.nextLine();
System.out.println("Please type in an age");
Pet3age=scan.nextInt();
Pet3=new Pet(Pet3name,Pet3age);/*This line is Not saving Pet3 as
a "Pet" class and when I try to list all the pets by pressing
A when it loops back up , Pet3 does not show up as a Pet*/
}
Userinput=scan.nextLine(); //make sure to keep this line outside the curly braces.
break;

Sum value in Array Java [duplicate]

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.

Categories