I made a program which asks the user for their pet name and assigns it states of mind for 5 rounds. If the pet gets too angry it is put down.
What I am having trouble with is allowing the user to restart to an earlier stage at the game before the pet died.
Compiling the code would help illustrate the issue.
Any help would be appreciated.
import java.util.Random;
import java.util.Scanner;
class dinoo {
public static void main(String[] p) {
Pet p1 = new Pet();
Pet p2 = new Pet();
Scanner scanner = new Scanner(System.in);
String petname;
String species;
String angerlevel;
int thirst;
int hunger;
int irritability;
explain();
petname = askpetname();
species = askpetspecies();
int howmanyrounds = 5;
for (int i = 0; i < howmanyrounds; i++) {
int number = i + 1;
String num = Integer.toString(number);
print("Round " + number);
String[] emotionalstate = newarray(5);
thirst = thirstlevel(p1);
hunger = hungerlevel(p1);
irritability = irritabilitylevel(p1);
angerlevel = anger(hunger, thirst, irritability);
p1 = setpetname(p1, petname);
p1 = setspecies(p1, species);
p1 = setthirst(p1, thirst);
p1 = setanger(p1, angerlevel);
p1 = sethunger(p1, hunger);
p1 = setangervalue(p1, irritability);
print(petname + "'s thirst level is " + thirst + " , hunger level is " + hunger + ", irritability level is " + irritability + " and therefore emotional state is " + angerlevel);
if (angerlevel.equals("DANGEROUS")) {
print(petname + " is looking " + angerlevel + ", get out now! we will have to put " + petname + " down.");
boolean continueEnd = petdead();
if (continueEnd == false) {
System.exit(0);
} else {
emotionalstate = wheretogo(emotionalstate[]);
}
} else if (angerlevel.equals("Serene")) {
print("He looks " + angerlevel + ". Seems in a good mood.");
} else if (angerlevel.equals("Grouchy")) {
print("You should give him a treat to cheer him up.");
}
whatdoyouwant(p1);
print("Your pets emotion is now " + anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1)));
emotionalstate[i] = anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1));
print("Emotional state " + emotionalstate[i] + " has been saved!");
}
System.exit(0);
}
public static String[] wheretogo(String[] a) {
Scanner scanner = new scanner;
print("which level would you like to return to?");
int number = scanner.nextInt();
String level = a[number];
return a;
}
public static boolean petdead() {
Scanner scanner = new Scanner(System.in);
print("Your pet has been killed. Would you like to continue? (True or False)");
boolean yesorno = scanner.nextBoolean();
return yesorno;
}
public static int inputint(String message) {
Scanner scanner = new Scanner(System.in);
System.out.println(message);
int answer = scanner.nextInt();
return answer;
}
public static String[] newarray(int arraylength) {
String[] emotionalstate = new String[arraylength];
return emotionalstate;
}
//takes input from user to cheerup/feed/sing to the animal to lower values stored in setter/getter
public static Pet whatdoyouwant(Pet p1) {
Scanner scanner = new Scanner(System.in);
print("what would you like to do to the pet? (treat/water/sing)");
String ans = scanner.nextLine();
Random ran = new Random();
int reduction = ran.nextInt(6);
if (ans.equalsIgnoreCase("treat")) {
int hunger = gethungervalue(p1) - reduction;
if (hunger < 0) {
hunger = 0;
}
p1 = sethunger(p1, hunger);
print("Your pets hunger has been reduced to:");
printint(gethungervalue(p1));
} else if (ans.equals("sing")) {
int irrit = getirritabilityvalue(p1) - reduction;
if (irrit < 0) {
irrit = 0;
}
p1 = setirritability(p1, irrit);
print("Your pets irritability hs been reduced to:");
printint(getirritabilityvalue(p1));
} else if (ans.equals("water")) {
int thirst = getthirst(p1) - reduction;
if (thirst < 0) {
thirst = 0;
}
p1 = setthirst(p1, thirst);
print("Your pets thirst is has been reduced to:");
printint(getthirst(p1));
} else {
print("That action seems to agitate your pet, try something else before your pet becomes dangerous!");
}
return p1;
}
//GETTER METHOD
public static String getpetname(Pet p) {
return p.name;
}
public static String getspecies(Pet p) {
return p.species;
}
public static String getanger(Pet p) {
return p.anger;
}
public static int getthirst(Pet p) {
return p.thirst;
}
public static int gethungervalue(Pet p) {
return p.hunger;
}
public static int getangervalue(Pet p) {
return p.angervalue;
}
public static int getirritabilityvalue(Pet p) {
return p.irritability;
}
//SETTER METHOD
public static Pet setangervalue(Pet p, int whatsangervalue) {
p.angervalue = whatsangervalue;
return p;
}
public static Pet setpetname(Pet p, String name) {
p.name = name;
return p;
}
public static Pet setspecies(Pet p, String petspecies) {
p.species = petspecies;
return p;
}
public static Pet setanger(Pet p, String howangry) {
p.anger = howangry;
return p;
}
public static Pet sethunger(Pet p, int howhungry) {
p.hunger = howhungry;
return p;
}
public static Pet setthirst(Pet p, int howthirsty) {
p.thirst = howthirsty;
return p;
}
public static Pet setirritability(Pet p, int howirritable) {
p.irritability = howirritable;
return p;
}
//Method printing out statement to explain functionality of program
public static void explain() {
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
//Method to ask the pet name
public static String askpetname() {
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
return petname;
}
//Method to ask the pet species
public static String askpetspecies() {
Scanner scanner = new Scanner(System.in);
print("What species is your pet?");
String petspecies = scanner.nextLine();
return petspecies;
}
//Randomly allocates thirst value 0-10
public static int thirstlevel(Pet p1) {
Random ran = new Random();
int thirst = ran.nextInt(11);
setthirst(p1, thirst);
return thirst;
}
//Randomly Allocates hunger value 0-10
public static int hungerlevel(Pet p1) {
Random ran = new Random();
int hunger = ran.nextInt(11);
sethunger(p1, hunger);
return hunger;
}
//randomly generates a irratibilty value
public static int irritabilitylevel(Pet p1) {
Random ran = new Random();
int irritable = ran.nextInt(11);
setirritability(p1, irritable);
return irritable;
}
//Method calculates the anger value based on the thirst/hunger/irritability average
public static String anger(int thirst, int hunger, int irritability) {
int angerscore = (thirst + hunger + irritability) / 3;
String temper;
temper = Integer.toString(angerscore);
if (angerscore <= 1) {
temper = "Serene";
} else if (angerscore <= 3) {
temper = "Grouchy";
} else if (5 < angerscore) {
temper = "DANGEROUS";
}
return temper;
}
//HELPER PRINT METHOD
public static String print(String message) {
System.out.println(message);
return message;
}
public static int printint(int message) {
System.out.println(message);
return message;
}
}//END class dinoo
class Pet {
String name;
String species;
int thirst;
int hunger;
String anger;
int irritability;
int angervalue;
} //END class pet
First of all you should look at the compile errors in your code before submitting a question here.
Please read the links provided in the comments to learn how to submit a proper question.
I tried to compile your code and it had the following errors:
java2.java:51: error: '.class' expected
emotionalstate = wheretogo(emotionalstate[]);
^
java2.java:75: error: '(' or '[' expected
Scanner scanner = new scanner;
That means in line 51, you're passing emotionalstate[] , which is emotional state array, whereas emotionalstate itself is an array, so you're passing an array of an array.
So just change it to emotionalstate = wheretogo(emotionalstate)
And in line 75, your initialization of Scanner object is wrong, change it to Scanner scanner = new Scanner();
Related
I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.
This is the code that is meant to call a class called Couple and yet
it doesn't recognize the class why is this?
public class AgencyInterFace {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Couple c = new Couple();
int choice, position;
showSelection();
choice = console.nextInt();
while (choice != 9) {
switch (choice) {
case 1:
addCouple();
break;
case 2:
position = console.nextInt();
testCouple(position);
break;
case 3:
position = console.nextInt();
displayCouple(position);
break;
case 9:
break;
default:
System.out.println("Invalid Selection");
} //end switch
showSelection();
choice = console.nextInt();
}
}
public static void showSelection() {
System.out.println("Select and enter");
System.out.println("1 - add a new couple");
System.out.println("2 - test a couple");
System.out.println("3 - display couple");
System.out.println("9 - exit");
}
public static void addCouple() {
Scanner console = new Scanner(System.in);
String herName, hisName;
int herAge, hisAge, ageDiff;
System.out.print("her name: ");
herName = console.nextLine();
System.out.print("her age: ");
herAge = console.nextInt();
System.out.print("his name: ");
hisName = console.nextLine();
System.out.print("his age: ");
hisAge = console.nextInt();
ageDiff = herAge - hisAge;
c.addData(herName, herAge, ageDiff, hisName, hisAge, ageDiff);
}
public static void testCouple(int position) {
System.out.println(c.test(position));
}
public static void displayCouple(int position) {
System.out.println(c.display(position));
}
public static void averageAge(int position) {
System.out.println(c.avgAge());
}
public static void maxDifference(int position) {
System.out.println(c.maxDif(position));
}
public static void averageDifference(int position) {
System.out.println(c.avgDif(position));
}
}//end of class
This code is the class that is meant to be called and that is not
being recognized and is unable to be called.
public class Couple {
final private int MAX = 5;
private Person[] p1, p2;
private int total;
public Couple() {
p1 = new Person[MAX];
p2 = new Person[MAX];
total = 0;
}
private void setData1(Person p, String name, int age, int ageDiff) {
p.setName(name);
p.setAge(age);
}
public String test(int pos) {
if (pos != -1) {
if (p1[pos].getAge() < p2[pos].getAge()) return ("GOOD FOR
"+p2[pos].getName()+" !");
else return ("GOOD
FOR "+p1[pos].getName()+" !");
}
return "error";
}
public void addData(String name1, int age1, int ageDiff1, String
name2, int age2, int ageDiff2) {
p1[total] = new Person();
p2[total] = new Person();
setData1(p1[total], name1, age1, ageDiff1);
setData1(p2[total], name2, age2, ageDiff2);
total++;
}
public String display(int position) {
if (position != -1)
return ("p1: " + p1[position].getName() + "
"+p1[position].getAge()+" / n "+" p2:
"+p2[position].getName()+"
"+p2[position].getAge());
else
return ("error");
}
public String avgAge(int position) {
double avg = 0;
double sum = 0.0;
for (int i = 0; i < position; i++) {
sum += p1[total].getAge();
sum += p2[total].getAge();
}
avg = sum / position;
return ("The average age is: " + avg);
}
public void ageDifference(int position) {
double ageDif = 0.0;
double ageSum = 0.0;
for (int i = 0; i < position; i++) {
if (p1[total].getAge() < p2[total].getAge()) {
ageSum = p2[total].getAge() - p1[total].getAge();
} else {
ageSum = p1[total].getAge() - p2[total].getAge();
}
ageSum = ageDif;
}
}
}
Is this have something to do with the name of the 'Couple' file or how
I call the class. I am getting an 'Undeclared Variable' error.
You defined c inside your main() method. Therefore it is not visible in your other methods. Either pass c as a parameter to your other methods or make it a (static) property of the AgencyInterFace class instead of a local variable of main().
USING STATIC METHODS
If you want to call a method of the class, e.g. test(int position), without creating a variable c, you need to make this method static:
public static String test(int pos) {
if (pos!=-1) {
if (p1[pos].getAge()<p2[pos].getAge()) return("GOOD FOR "+p2[pos].getName()+"!");
else return("GOOD FOR"+p1[pos].getName()+"!");
}
return "error";
}
In this case, your arrays p1[] and p2[] would also need to be static --> they would only be created one time.
And example for making your arrays static:
private static Person[] p1 = new Person[MAX],
p2 = new Person[MAX];
Now you can call this method of the class using Couple.test(position) and it will return a String.
USING NON-STATIC METHODS
If you want to create multiple references of the class Couple, in that p1[] and p2[] should contain different values, you need to create a reference of the class Couple.
You can implement this by telling the program, what c is:
Couple c = new Couple();
Edit:
I see that you have created a couple, but not at the right place. If you create your couple inside of the main() method, you cannot use it anywhere except in this method. You should declare it in your class:
public class AgencyInterFace {
private static Couple c = new Couple(); //<-- here
// main-method
// other methods
}
Can someone see why the user can enter more than 27 apple, blueberry, or peanut pies? Even after declaring a final int for the max number of each type of pie.
The object here is to continually prompt the user for type of pie until the user wants to quit. Each time one of the valid inputs is entered it is stored in it's own array. After the user has indicated they are finished, calculations are done and a message is printed.
import javax.swing.JOptionPane;
public class CalcPieProfit {
public static void main(String[] args) {
final int MAX_PER_TYPE = 27;
int appleTotal = 0;
int blueberryTotal = 0;
int peanutTotal = 0;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
blueberryTotal++;
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
peanutTotal++;
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleTotal, blueberryTotal, peanutTotal);
double profit = calcProfit(appleTotal, blueberryTotal, peanutTotal);
printReport(totalPies, appleTotal, blueberryTotal, peanutTotal, profit);
}
}
public static String getPieType() {
String pieType;
do {
try {
pieType = JOptionPane.showInputDialog("Enter a pie type:");
}
catch (NumberFormatException e) {
pieType = "";
}
if (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q")) {
JOptionPane.showMessageDialog(null, "Enter 'apple', 'blueberry', 'peanut', or 'q' only.");
}
} while (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q"));
return pieType;
}
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
public static String[] fillBlueberry(String typeOfPie, int MAX_PER_TYPE) {
String[] blueberryArray = new String[MAX_PER_TYPE];
for (int i = 0; i < blueberryArray.length; i++) {
blueberryArray[i] = typeOfPie;
}
return blueberryArray;
}
public static String[] fillPeanut(String typeOfPie, int MAX_PER_TYPE) {
String[] peanutArray = new String[MAX_PER_TYPE];
for (int i = 0; i < peanutArray.length; i++) {
peanutArray[i] = typeOfPie;
}
return peanutArray;
}
public static int calcTotalPies(int appleTotal, int blueberryTotal, int peanutTotal) {
int total = appleTotal + blueberryTotal + peanutTotal;
return total;
}
public static double calcProfit (int appleTotal, int blueberryTotal, int peanutTotal) {
final double APPLE_PROFIT = 5.94;
final double BLUEBERRY_PROFIT = 5.89;
final double PEANUT_PROFIT = 6.95;
double profit = (APPLE_PROFIT * appleTotal) + (BLUEBERRY_PROFIT * blueberryTotal) +
(PEANUT_PROFIT * peanutTotal);
return profit;
}
public static void printReport(int totalPies, int appleTotal, int blueberryTotal, int peanutTotal, double profit) {
if (totalPies > 0) {
JOptionPane.showMessageDialog(null,
"Pie Report\n\n" +
"Total pies: " + totalPies +
"\nTotal of apple pie: " + appleTotal +
"\nTotal of blueberry pie: " + blueberryTotal +
"\nTotal of peanut butter pie: " + peanutTotal +
"\nTotal profit: $" + String.format("%.2f", profit));
}
else {
JOptionPane.showMessageDialog(null, "Enjoy your day off.");
}
}
}
You are not really using the String[]s appleArray, blueberryArray and peanutArray - they are created in their respective method but not used anywhere else. For calculating the profits, you are (rightfully) only the total variables.
Instead of
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
you should do something like
if (typeOfPie.equalsIgnoreCase("apple")) {
if (appleTotal >= MAX_PER_TYPE) {
JOptionPane.showMessageDialog(null, "Too many apples.");
} else {
appleTotal++;
}
}
(and the same for other pie types).
You're redeclaring the pie arrays each time you go to add them.
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
Each time you call this method, a new "appleArray" is generated. If you want it to persist between calls to this method, declare the appleArray as private static outside of the loop, and reference that instead.
I'm trying to use insertion sort to sort for the batting average of the players. I get an error message "The method get(int) in the type java.util.ArrayList is not applicable for the arguments (double)" on the lines of S.get(outer) and S.get(inner - 1)
What am I doing wrong?
How can I fix this?
import java.util.*;
import java.io.*;
class menu {
public static void main (String [] arg) throws IOException
{
PlayerRip.PlayerInfo obj5 = new PlayerRip.PlayerInfo();
ArrayList<Player> obj6 = new ArrayList<Player>();
MainMenu(obj5, obj6);
}
public static void MainMenu(PlayerRip P, ArrayList<Player> S) throws IOException
{
Scanner keyboard = new Scanner(System.in);
int response = 0;
int response2 = 0;
ArrayList<Player> obj1 = new ArrayList<Player>();
obj1.add(new Player("Agostini", "Aldo", "Pitcher", 170, 20, 72, 12, 6, 1, 1, 0));
do
{
System.out.println("1. Open A file:");
System.out.println("7. Exit the program");
response = keyboard.nextInt();
switch (response)
{
case 1:
{
openFile(obj1);
do
{
System.out.println("2. Display all players");
System.out.println("3. Enter player's Height");
System.out.println("4. Sort all players alphabetically by Surname");
System.out.println("5. Sort all players by batting average");
System.out.println("6. Delete a player by selecting the player's surname from a list");
System.out.println("7. Add a player to the stats");
System.out.println("8. Save stats to a file");
System.out.println("9. Exit the program");
response2 = keyboard.nextInt();
switch (response2)
{
case 2:
{
displayInfo(obj1);
break;
}
case 3:
{
changeHeight(obj1);
break;
}
case 4:
{
BubbleSort(obj1);
break;
}
case 5:
{
break;
}
case 6:
{
deletePlayerInfo(obj1);
break;
}
case 7:
{
addPlayerInfo(obj1);
break;
}
case 8:
{
saveFile(obj1);
break;
}
case 9:
{
System.exit(0);
break;
}
}
} while (response2 != 9);
break;
}
case 7:
{
System.exit(0);
break;
}
}
} while (response != 1 || response != 7); // End of switch statement
}
public static void displayInfo(ArrayList<Player> S) {
System.out.printf("%10s %10s %10s \t %4s %4s \t %4s \t %4s %4s \t %4s %4s %4s \n", "Surname", "GivenName", "Postition", "Height(cm)", "Hits", "AtBats", "Singles", "Doubles", "Triples", "HomeRuns", "Batting Average");
for (int index = 0; index < S.size(); index++)
S.get(index).displayInfo();
}
public static void openFile(ArrayList<Player> S) throws IOException // This method allows the oepning of files into the program
{
Scanner userInput = new Scanner(System.in);
String fileName;
S.removeAll(S); // Empties the list readies it for a new oned
System.out.println("Enter a file name to open: ");
fileName = userInput.next().trim();
File file = new File(fileName);
if (file.exists()) // Checks whether or not the file exists in the directory
{
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext())
{
S.add(new Player(fileInput.next(), fileInput.next(), fileInput.next(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextDouble())); // If it exists it adds the token values into the respective lists
}
fileInput.close(); // Closes further file input
}
else // Error message incase the file-name is not valid
System.out.println("FILE NOT FOUND");
}
public static void saveFile(ArrayList<Player> S) throws IOException // This method allows for the saving of values to an external file
{
Scanner inputInfo = new Scanner(System.in);
String fileName;
System.out.println("Enter a file name to save the info with:");
fileName = inputInfo.next().trim();
File file = new File(fileName);
PrintStream writeFile = new PrintStream(file);
for (int i = 0; i < S.size(); i++) // Gathers all values and prints them to the file in their respective format
{
writeFile.print(S.get(i).getName() + " ");
writeFile.print(S.get(i).getName2() + " ");
writeFile.print(S.get(i).getPosition() + " ");
for (int j = 0; j < 7; j++)
writeFile.print(S.get(i).getMark(j) + " ");
for (int j = 0; j < 1; j++)
writeFile.print(S.get(i).getBatAvg(j));
writeFile.println(" ");
}
writeFile.close(); // Stops any further writing to the file
}
public static void deletePlayerInfo(ArrayList<Player> S) // THis method allows the user to delete any player within the list
{
int deleteIt = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please select the number of the player to be deleted: ");
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
deleteIt = keyboard.nextInt();
S.remove(deleteIt);
}
public static void addPlayerInfo(ArrayList<Player> S) // This method allows the user to add a new player to the list
{
String firstName = "";
String surName = "";
String posName = "";
int heightVal = 0;
int hitsVal = 0;
int atBatsVal = 0;
int singVal = 0;
int doubVal = 0;
int tripVal = 0;
int homeVal = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Enter the surname and name of the new player: ");
System.out.println("Surname: ");
surName = keyboard.nextLine();
System.out.println("Name: ");
firstName = keyboard.nextLine();
System.out.println("Enter the position of the new player: ");
System.out.println("Position: ");
posName = keyboard.nextLine();
System.out.println("Enter the height of the new player: ");
heightVal = keyboard.nextInt();
System.out.println("Enter the batting statistics: ");
System.out.println("Hits: ");
hitsVal = keyboard.nextInt();
System.out.println("AtBats: ");
atBatsVal = keyboard.nextInt();
System.out.println("Singles: ");
singVal = keyboard.nextInt();
System.out.println("Doubles: ");
doubVal = keyboard.nextInt();
System.out.println("Triples: ");
tripVal = keyboard.nextInt();
System.out.println("HomeRuns: ");
homeVal = keyboard.nextInt();
S.add(new Player(surName, firstName, posName, heightVal, hitsVal, atBatsVal, singVal, doubVal, tripVal, homeVal, 0));
}
public static void changeHeight(ArrayList<Player> S)
{
int playerSel = 0;
int newHeight = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Select a player to enter the height for: ");
do
{
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
playerSel = keyboard.nextInt();
System.out.println("Enter the height for this character: ");
newHeight = keyboard.nextInt();
if (newHeight < 125 && newHeight > 240)
{
System.out.println("WRONG! TRY AGAIN!");
}
else
{
}
} while (newHeight >= 125 && newHeight <= 240);
}
public static void BubbleSort(ArrayList<Player> S){
Player strTemp;
int i = 0;
boolean isSorted = false;
while(i < S.size()&&isSorted==false)
{
isSorted = true;
for(int j = 0; j < (S.size()-1)-i;j++)
{
if(S.get(j).getName().compareToIgnoreCase(S.get(j+1).getName())>0){
strTemp = S.get(j);
S.set(j,S.get(j+1));
S.set(j+1,strTemp);
isSorted = false;
}
}
i++;}
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
class PlayerRip {
public String name;
public String name2;
public String position;
public int [ ] mark = new int[7];
public double [ ] batAvg = new double[1];
static class PlayerInfo extends PlayerRip
{
PlayerInfo() {
this.name = "-1";
this.name2 = "-1";
this.position = "-1";
for (int i=0; i < mark.length; i++)
mark[i] = -1;
}
PlayerInfo(String nam, String nam2, String pos, int a, int b, int c, int d, int e, int f, int g, double h) {
this.name = nam;
this.name2 = nam2;
this.position = pos;
this.mark[0] = a; this.mark[1] = b; this.mark[2] = c; this.mark[3] = d; this.mark[4] = e; this.mark[5] = f; this.mark[6] = g;
batAvg[0] = (((double)mark[1] / (double)mark[2]) * 100);
}
public void setName(String nam) { name = nam; }
public void setName2(String nam2) { name2 = nam2; }
public void setPosition(String pos) { position = pos; }
public void setMark(int index, int mark) { this.mark[index] = mark; }
public void setBatAvg(int index, double batAvg) {this.batAvg[index] = batAvg;}
public String getName() { return this.name; }
public String getName2() { return this.name2; }
public String getPosition() { return this.position; }
public double getBatAvg() { return this.batAvg[0];}
public int getMark(int index) { return this.mark[index]; }
public void setHeight(int index, int mark) { this.mark[index] = mark; }
public int getHeight(int index) { return this.mark[0]; }
public void setHits (int index, int mark) { this.mark [index] = mark; }
public int getHits (int index) { return this.mark [1]; }
public void setAtBats (int index, int mark) { this.mark [index] = mark; }
public int getAtBats(int index) { return this.mark [2]; }
public void setSingles (int index, int mark) { this.mark [index] = mark; }
public int getSingles (int index) { return this.mark [3] ; }
public void setDoubles (int index, int mark) { this.mark [index] = mark; }
public int getDoubles (int index) { return this.mark [4] ; }
public void setTriples (int index, int mark) { this.mark [index] = mark; }
public int getTriples (int index) { return this.mark [5] ; }
public void setHomeRuns (int index, int mark) { this.mark [index] = mark; }
public int getHomeRuns (int index) { return this.mark [6] ; }
}
}
sorry for format im new to the site
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
is the specific area of problems
S.get() and S.set() take a int variable so cast inner to a int.
You defined inner as a double, and in Java, when you do math with a double and an int (such as inner - 1), you'll get a double as a result. This page has a fairly good explanation.
Then when you say S.get(inner - 1), you're saying to use a double as an the index in the ArrayList. The documentation for ArrayList.get says that you can only use an int as an index, and that's why you're getting a compiler error. You're also only allowed to use an int as the index for set, so that's why the compiler would complain about S.set(inner, ...).
You could just cast inner to an int, but it would be much better to declare it as an int in the first place since there's no reason it needs to be a double.
So, i was using some variables in my methods but I get errors and I dont know how to fix this heres my code from my first class:
import java.util.Scanner;
public class Gerbilfood {
public static void main(String[] args) {
Gerbil[] gerbil;
Scanner scanner = new Scanner(System.in);
System.out.println("Please input how many types of food items the gerbils eat as an integer");
String n0 = scanner.nextLine();
int n1 = Integer.parseInt(n0);
String[] food = new String[n1];
for (int i = 0; i < n1; i++) {
System.out.println("Please enter a food name");
String n2 = scanner.nextLine();
food[i] = n2;
int[] maximum = new int[n1];
System.out.println("Please enter maximum amount of food per day");
String n33 = scanner.nextLine();
int n3 = Integer.parseInt(n33);
maximum[i] = n3;
}
System.out.println("Please enter in the number of gerbils in the lab");
String n73 = scanner.nextLine();
int n4 = Integer.parseInt(n73);
gerbil = new Gerbil[n4];
int[] combo = new int[n4];
String[] ids = new String[n4];
for (int i = 0; i < n4; i++) {
Gerbil g = new Gerbil(n1);
System.out.println("Please enter in the lab id for each gerbil");
String n5 = scanner.nextLine();
g.setId(n5);
//ids[i] = n5;
//String[] names = new String[n4];
System.out.println("Please enter in the name of each gerbil");
String n6 = scanner.nextLine(); // gerbil name
g.setName(n6);
String[] amountfood = new String[n1];
for (int j = 0; j < n1; j++) {
System.out.println("how much of" + food[j] + "did the gerbil eat");
String n8 = scanner.nextLine();
amountfood[i] = n8;
}
String[] bite = new String[n4];
System.out.println("Does this Gerbil bite? Enter True or False");
String n77 = scanner.nextLine();
bite[i] = n77;
String[]escape = new String[n4];
System.out.println("Does this Gerbil escape? Enter True or False");
String n89 = scanner.nextLine();
escape[i] = n89;
}
System.out.println("What information would you like to know?");
String n55 = scanner.nextLine();
String n33 = "search";
String n34 = "average";
String n35 = "restart";
String n36 = "quit";
if(n55.equalsIgnoreCase(n34)) {
System.out.println(averagefood());
} else {
if(n55.equalsIgnoreCase(n33)) {
System.out.println("Please type the lab id of the gerbil you wish to search for");
String n87 = scanner.nextLine();
System.out.println();
} else {
if (n55.equalsIgnoreCase(n35)) {
//go back to beginning of program
} else {
if (n55.equalsIgnoreCase(n36)) {
System.exit(0);
} else {
System.out.println("ERROR");
}
}
}
}
}
public static int averagefood(int n4, int n3, int n8) {
for (int i = 0; i < n4; i++) {
long percent = Math.round(n8 * 100.0 / n3);
return averagefood(newName, newId, percent);
}
}
public static int searchForGerbil() {
n87 = setId;
return 0;
// return (new Gerbil[i]
and heres the code from my second class:
public class Gerbil {
private String id;
private String name;
private int[] amountfood;
//private int numbergerbils;
//private int maxfood;
private boolean escape;
private boolean bite;
public Gerbil(String n5, String n6, int numOfFood, boolean newEscape, boolean newBite) {
id = n5;
name = n6;
amountfood = new int[numOfFood];
escape = newEscape;
bite = newBite;
}
public Gerbil(int numOfFood) {
amountfood = new int[numOfFood];
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String newId) {
id = newId;
}
public void setName(String newName) {
name = newName;
}
}
it says next to System.out.println(averagefood()); The method
averagefood(int, int, int) in the type Gerbilfood is not applicable
for the arguments ()
If you check your code your function definition requires three arguments and you have not passed any.
getName cannot be resolved to a variable
This is a function in class Gerbil and hence needs to be called as follows:
Gerbil gb = new Gerbil();
gb.getName();
Syntax error on token "return", Name expected after this token - getId
cannot be resolved to a variable - newId cannot be resolved to a
variable - newName cannot be resolved to a variable it says that next
to return averagefood(newName, newId, percent);
None of these variables have been defined in class Gerbilfood. What values are you expecting to pass using these variables?