So my code works completely; the only thing now is a very simple problem that I cannot figure out. I have to make the program loop back to the beginning if the user type restart and I cannot think how to that.
import java.util.Scanner;
public class MutantGerbil {
public static String []foodName;
public static int [] maxAmount;
public static Gerbil [] gerbilAttributes;
public static int [] consumption;
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
String userInput1 = keyboard.nextLine();
int food = Integer.parseInt(userInput1);
foodName = new String[food]; //array of food names
maxAmount = new int[food]; // array of max amount of food given everyday
for (int i = 0; i < food; i++){
System.out.println("Name of food item" + (i+1) +": " );
String foodType = keyboard.nextLine();
foodName[i] = foodType;
System.out.println("Maximum consumed per gerbil: ");
String consumption = keyboard.nextLine();
int consumption2 = Integer.parseInt(consumption);
maxAmount [i] = consumption2;
}
System.out.println("How many gerbils are in the lab?");
String userInput2 = keyboard.nextLine();
int numberOfGerbils = Integer.parseInt(userInput2);
gerbilAttributes = new Gerbil [numberOfGerbils];// Array with the gerbil attributes
for (int i = 0; i < numberOfGerbils; i++)
{
consumption = new int[food]; // Array with amount of the food the gerbil eat each day
System.out.println("Gerbil" + (i+1) + "'s" + "lab ID: ");
String gerbilID = keyboard.nextLine();
System.out.println("What name did the students give to "+ gerbilID);
String gerbilName = keyboard.nextLine();
for (int j = 0; j < food; j++)
{
System.out.println(gerbilID + " eats how many " + foodName[j] + " per day?");
String gerbilComsumption = keyboard.nextLine();
int gerbilFood = Integer.parseInt(gerbilComsumption);
if (gerbilFood <= maxAmount[j])
{
consumption[j] = gerbilFood;
}
}
System.out.println("Does " + gerbilID + " bite?");
boolean biter = keyboard.nextBoolean();
System.out.println("Does " + gerbilID + " try to escape?");
boolean flightRisk = keyboard.nextBoolean();
keyboard.nextLine();
Gerbil temp = new Gerbil (gerbilID, gerbilName, consumption, biter, flightRisk);
gerbilAttributes [i] = temp;
}
boolean end1 = false;
while (! end1){
System.out.println("What information would you like to know");
sortGerbilArray (gerbilAttributes);
String userInput3 = keyboard.nextLine();
if (userInput3.equalsIgnoreCase("average"))
{
String average1 = foodAverage();
System.out.println(average1);
}
if (userInput3.equalsIgnoreCase("search"))
{
System.out.println("Enter a Gerbil ID to search for");
userInput3 = keyboard.nextLine();
Gerbil findGerbil = searchForGerbil(userInput3);
if (findGerbil == null)
{
System.out.println("Error");
}
else {
String h = ("Name: " + findGerbil.getName());
if (findGerbil.getAttacker())
{
h+= " (will bite, ";
}
else
{
h+= " (will not bite, ";
}
if (findGerbil.getFilghtRisk())
{
h+= "will run away), ";
}
else
{
h+= "will not run away), ";
}
h+= "Food:";
for (int i = 0; i < foodName.length; i++){
h+=" " + foodName[i] + "-";
h+= findGerbil.getConsumption2()+"/"+ maxAmount[i];
if (i < foodName.length-1)
{
h+=",";
}
System.out.println(h);
}
}
}
if (userInput3.equalsIgnoreCase("restart")){
}
if (userInput3.equalsIgnoreCase("quit"))
{
System.out.println("Good-bye!");
break;
}
}
}
private static void sortGerbilArray(Gerbil[]sortGerbil){
for (int i = 0; i < sortGerbil.length; i++){
for (int j = 0; j < sortGerbil.length - i - 1; j++){
if(sortGerbil[j].getID().compareToIgnoreCase(sortGerbil[j+1].getID())>0){
Gerbil t = sortGerbil[j];
sortGerbil[j] = sortGerbil[j+1];
sortGerbil[j+1] = t;
}
}
}
}
private static String foodAverage()
{
double average = 0.0;
double totalMaxAmount = 0;
double totalConsumption = 0;
String averageFood = "";
for (int i = 0 ; i < gerbilAttributes.length;i++)
{
for(int j = 0; j < maxAmount.length; j++)
{
totalMaxAmount += maxAmount[j];
}
totalConsumption += gerbilAttributes[i].getConsumption();
average = totalConsumption/totalMaxAmount*100;
averageFood += gerbilAttributes[i].getID() + "(" + gerbilAttributes[i].getName() + ")" + Math.round(average) + "%\n";
totalMaxAmount = 0;
totalConsumption = 0;
}
return averageFood;
}
private static Gerbil searchForGerbil (String x) {
for (Gerbil l: gerbilAttributes){
if (l.getID().equals(x)){
return l;
}
}
return null;
}
}
there are two solutions.
1. wrap your code in "while" loop. but it will be difficult for you because your code is so messy :(
change the code as follow
import java.util.Scanner; public class MutantGerbil {
public static String []foodName;
public static int [] maxAmount;
public static Gerbil [] gerbilAttributes;
public static int [] consumption;
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
String userInput1 = keyboard.nextLine();
int food = Integer.parseInt(userInput1);
foodName = new String[food]; //array of food names
maxAmount = new int[food]; // array of max amount of food given everyday
for (int i = 0; i < food; i++){
System.out.println("Name of food item" + (i+1) +": " );
String foodType = keyboard.nextLine();
foodName[i] = foodType;
System.out.println("Maximum consumed per gerbil: ");
String consumption = keyboard.nextLine();
int consumption2 = Integer.parseInt(consumption);
maxAmount [i] = consumption2;
}
System.out.println("How many gerbils are in the lab?");
String userInput2 = keyboard.nextLine();
int numberOfGerbils = Integer.parseInt(userInput2);
gerbilAttributes = new Gerbil [numberOfGerbils];// Array with the gerbil attributes
for (int i = 0; i < numberOfGerbils; i++)
{
consumption = new int[food]; // Array with amount of the food the gerbil eat each day
System.out.println("Gerbil" + (i+1) + "'s" + "lab ID: ");
String gerbilID = keyboard.nextLine();
System.out.println("What name did the students give to "+ gerbilID);
String gerbilName = keyboard.nextLine();
for (int j = 0; j < food; j++)
{
System.out.println(gerbilID + " eats how many " + foodName[j] + " per day?");
String gerbilComsumption = keyboard.nextLine();
int gerbilFood = Integer.parseInt(gerbilComsumption);
if (gerbilFood <= maxAmount[j])
{
consumption[j] = gerbilFood;
}
}
System.out.println("Does " + gerbilID + " bite?");
boolean biter = keyboard.nextBoolean();
System.out.println("Does " + gerbilID + " try to escape?");
boolean flightRisk = keyboard.nextBoolean();
keyboard.nextLine();
Gerbil temp = new Gerbil (gerbilID, gerbilName, consumption, biter, flightRisk);
gerbilAttributes [i] = temp;
}
boolean end1 = false;
while (! end1){
System.out.println("What information would you like to know");
sortGerbilArray (gerbilAttributes);
String userInput3 = keyboard.nextLine();
if (userInput3.equalsIgnoreCase("average"))
{
String average1 = foodAverage();
System.out.println(average1);
}
if (userInput3.equalsIgnoreCase("search"))
{
System.out.println("Enter a Gerbil ID to search for");
userInput3 = keyboard.nextLine();
Gerbil findGerbil = searchForGerbil(userInput3);
if (findGerbil == null)
{
System.out.println("Error");
}
else {
String h = ("Name: " + findGerbil.getName());
if (findGerbil.getAttacker())
{
h+= " (will bite, ";
}
else
{
h+= " (will not bite, ";
}
if (findGerbil.getFilghtRisk())
{
h+= "will run away), ";
}
else
{
h+= "will not run away), ";
}
h+= "Food:";
for (int i = 0; i < foodName.length; i++){
h+=" " + foodName[i] + "-";
h+= findGerbil.getConsumption2()+"/"+ maxAmount[i];
if (i < foodName.length-1)
{
h+=",";
}
System.out.println(h);
}
}
}
if (userInput3.equalsIgnoreCase("restart")){
main();
}
if (userInput3.equalsIgnoreCase("quit"))
{
System.out.println("Good-bye!");
break;
}
}
}
private static void sortGerbilArray(Gerbil[]sortGerbil){
for (int i = 0; i < sortGerbil.length; i++){
for (int j = 0; j < sortGerbil.length - i - 1; j++){
if(sortGerbil[j].getID().compareToIgnoreCase(sortGerbil[j+1].getID())>0){
Gerbil t = sortGerbil[j];
sortGerbil[j] = sortGerbil[j+1];
sortGerbil[j+1] = t;
}
}
}
}
private static String foodAverage()
{
double average = 0.0;
double totalMaxAmount = 0;
double totalConsumption = 0;
String averageFood = "";
for (int i = 0 ; i < gerbilAttributes.length;i++)
{
for(int j = 0; j < maxAmount.length; j++)
{
totalMaxAmount += maxAmount[j];
}
totalConsumption += gerbilAttributes[i].getConsumption();
average = totalConsumption/totalMaxAmount*100;
averageFood += gerbilAttributes[i].getID() + "(" + gerbilAttributes[i].getName() + ")" + Math.round(average) + "%\n";
totalMaxAmount = 0;
totalConsumption = 0;
}
return averageFood;
}
private static Gerbil searchForGerbil (String x) {
for (Gerbil l: gerbilAttributes){
if (l.getID().equals(x)){
return l;
}
}
return null;
} }
Related
I am trying to use two int variables from other classes in another class and then add them together into another variable and print the result. When I try this though, I always get a result of zero like the values are not being brought over into the new class and I can't figure out what the problem is.
Here is some example code:
class1
public static int finished = (match2.totalpoints + match3.iq);
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
EDIT: class2
public class match2 {
public static int totalpoints;
int a;
int b;
int c;
int d;
int e;
int f;
String guess;
String group;
String countdown[] = {
"3...",
"2...",
"1...",
""
};
String memorize[] = {
""
};
public match2() throws InterruptedException
{
int x = set2();
int y = set3();
int z = set4();
total(x, y, z);
System.out.println("For the next part of your IQ ASSesment\njust type back the words in CAPSLOCK in CAPSLOCK");
System.out.println("");
match3 n = new match3();
}
public void set1() throws InterruptedException
{
//Scanner s = new Scanner(System.in);
for (int i = 0; i < countdown.length; i++)
{
Thread.sleep(750);
System.out.println(countdown[i]);
}
}
public int set2() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("press ENTER for your first set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
group = "" + a + b + c + d;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(guess.equals(group))
{
System.out.println("nice +1 bruh");
rv = 1;
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set3() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your next set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("good");
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set4() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your final set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
e = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f + e;
System.out.println(group);
System.out.println("");
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("great");
}
else if(!group.equals(guess))
{
System.out.println("eeeh buzer sound");
}
return rv;
}
public int total(int x, int y, int z)
{
System.out.println("");
int totalpoints = (x + y + z);
if(totalpoints == 3)
{
System.out.println("YOU GOT THEM ALL");
}
if(totalpoints <= 2 && totalpoints >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalpoints));
}
if(totalpoints == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
return totalpoints;
}
}
EDIT: class3
public class match3 {
public static int iq;
String countupdown [] = {
"READY...",
"SET.....",
""
};
String memorize [] = {
""
};
public match3() throws InterruptedException
{
int mem1 = memory1();
int mem2 = memory2();
int mem3 = memory3();
totalMemory(mem1, mem2, mem3);
}
public void methodCountdown() throws InterruptedException
{
for(int i = 0; i < countupdown.length; i++)
{
Thread.sleep(1000);
System.out.println(countupdown[i]);
}
}
public int memory1() throws InterruptedException
{
int rv = 1;
Scanner s = new Scanner(System.in);
System.out.println("Press ENTER when ready");
s.nextLine();
methodCountdown();
String a = word1();
String b = word2();
System.out.println("The " + a + " ate the " + b);
String wordgroup = "" + a + " " + b;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory2() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String c = word3();
System.out.println("The " + a + " drove the " + c);
String wordgroup = "" + a + " " + c;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory3() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String d = word4();
System.out.println("The " + a + " visited the " + d);
String wordgroup = "" + a + " " + d;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public static String word1()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "DOG";
}
else if(cv == 2)
{
word = "CAT";
}
else if(cv == 3)
{
word = "BIRD";
}
return word;
}
public static String word2()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "FOOD";
}
else if(cv == 2)
{
word = "MUD";
}
else if(cv == 3)
{
word = "GRAINS";
}
return word;
}
public static String word3()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "TRAM";
}
else if(cv == 2)
{
word = "BUS";
}
else if(cv == 3)
{
word = "BICYCLE";
}
return word;
}
public static String word4()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "MALL";
}
else if(cv == 2)
{
word = "PARK";
}
else if(cv == 3)
{
word = "POOL";
}
return word;
}
public void totalMemory(int mem1, int mem2, int mem3)
{
int iq = (mem1 + mem2 + mem3);
System.out.println("");
if(iq == 3)
{
System.out.println("YOU GOT THEM ALL");
}
else if(iq <= 2 || iq >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
}
else if(iq == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
}
}
total points is a variable from match2 class and iq from match3 class. Any help with any methods I could use to make this happen would be much appreciated. Thank You
Well ... besides the fact you are not following any code convention, Like class names should start with a capital letter and public static final fields (like totalpoints and iq) should be all Uppercase (code conventions, you are not sharring match2 and match3 codes, without it we can't understand what is happening inside those classes.
But you can do a simple test and assign a value to match2.totalpoints and match3.iq and you are going to see the summing of these two values being printed by the last system.out you put.
good luck and good Java studies!
Are the int variables you're trying to use inside child classes of your main parent class? Did you extend the child classes in your main parent class?
Class #1:
public int firstVar(int someNum) {
//code here
return someNum;
}
Class #2:
public int secondVar(int otherNum) {
//code here
return otherNum;
}
Class #3 Class with Main Method -
public class mainClass extends class#1; //etc
//code here and finally print out the finished number
You could try extending one of the classes that has an int you need into another one of the classes with the other int you need and then just extending that second class into your main, OR you could try completely redefining your classes and just placing all the ints you need into one separate class and then extending that single one into your main.
So I finally got it to work. The problem, I guess, was that I was trying to add together the variables from the other classes(match2 and match3) outside the main function within the class(match1) I was trying to add them together. All I did was move the expression adding the variables together from the top to inside the main function like this:
public static int finished;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
finished = (match2.totalpoints + match3.iq);
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
Thanks for all the help from everyone.
Smth. like this. You have lot's of code duplication
public class MatchRunner {
public static void main(String... args) throws InterruptedException {
new MatchRunner().start();
}
public void start() throws InterruptedException {
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println();
System.out.println("When taking the quiztest you have only two seconds before making each guess");
int totalPoints = new Match2().getTotalPoints();
System.out.println("For the next part of your IQ Assesment");
System.out.println("just type back the words in CAPSLOCK in CAPSLOCK");
int iq = new Match3().getIQ();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + (totalPoints + iq) + " POINTS");
}
}
public class Match2 {
public int getTotalPoints() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
int totalPoints = calc(scan, "first", "nice +1 try", "almost");
totalPoints += calc(scan, "next", "good", "almost");
totalPoints += calc(scan, "final", "great", "eeeh buzer sound");
printTotalPoints(totalPoints);
return totalPoints;
}
}
private static void countdown() throws InterruptedException {
for (int i = 5; i > 0; i--) {
Thread.sleep(750);
System.out.println(i + "...");
}
}
private static int calc(Scanner scan, String strSet, String strEqual, String strNotEqual) throws InterruptedException {
System.out.println("press ENTER for your " + strSet + " set...");
Random random = new Random();
scan.nextLine();
countdown();
int sum = 0;
for (int i = 0; i < 4; i++)
sum += random.nextInt(9) + 1;
System.out.println(sum);
for (int i = 0; i < 10; i++)
System.out.println();
int guess = scan.nextInt();
System.out.println(guess == sum ? strEqual : strNotEqual);
return guess == sum ? 1 : 0;
}
private static void printTotalPoints(int totalPoints) {
System.out.println();
if (totalPoints == 3)
System.out.println("YOU GOT THEM ALL");
else if (totalPoints <= 2 && totalPoints >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalPoints));
else if (totalPoints == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}
public class Match3 {
public int getIQ() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
Random random = new Random();
Supplier<String> getWord1 = () -> getWord(random, "DOG", "CAT", "BIRD");
Supplier<String> getWord2 = () -> getWord(random, "FOOD", "MUD", "GRAINS");
Supplier<String> getWord3 = () -> getWord(random, "TRAM", "BUS", "BICYCLE");
Supplier<String> getWord4 = () -> getWord(random, "MALL", "PARK", "POOL");
int iq = calc(scan, getWord1, getWord2, "ate the");
iq += calc(scan, getWord1, getWord3, "drove the");
iq += calc(scan, getWord1, getWord4, "visited the");
printIq(iq);
return iq;
}
}
private static void countdown() throws InterruptedException {
System.out.println("READY...");
Thread.sleep(1000);
System.out.println("SET...");
Thread.sleep(1000);
}
public int calc(Scanner scan, Supplier<String> wordOne, Supplier<String> wordTwo, String strMsq) throws InterruptedException {
System.out.println("Press ENTER when ready");
scan.nextLine();
countdown();
String a = wordOne.get();
String b = wordTwo.get();
System.out.println("The " + a + ' ' + strMsq + ' ' + b);
String wordGroup = a + ' ' + b;
for (int i = 0; i <= 10; i++)
System.out.println();
String wordGuess = scan.nextLine();
System.out.println(wordGroup.equals(wordGuess) ? "awesome cock muncher a match" : "nope");
return wordGroup.equals(wordGuess) ? 1 : 0;
}
private static String getWord(Random random, String one, String two, String three) {
int cv = random.nextInt(3) + 1;
if (cv == 1)
return one;
if (cv == 2)
return two;
if (cv == 3)
return three;
return "";
}
public void printIq(int iq) {
System.out.println();
if (iq == 3)
System.out.println("YOU GOT THEM ALL");
else if (iq <= 2 || iq >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
else if (iq == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}
I'm trying to make a random deck generator for HearthStone and something is wrong with card[] array. It gives me null pointer exception and the first time it occurs is in the readFile() method, the debugger says the problem is with this line (well it starts there anyway) card[a].setName(name);. I know that it isn't the String variable "name" because I can reference that in a System.out.print().
p.s. my compiler is netbeans IDE 8.0.2
HearthStoneDeckMaker
package hearthstone.deck.maker;
import java.io.*;
import java.lang.*;
import java.util.*;
public class HearthStoneDeckMaker {
static createfile save = new createfile();
public static double manaAVG = 5;
public static int maxTaunt = 30;
public static int maxSpell = 30;
public static int maxMinions = 30;
public static int minTaunt = 0;
public static int minSpell = 0;
public static int minMinions = 0;
static Scanner input = new Scanner(System.in);
public static int numberOfCards = 0;
static Card[] card = new Card[9999];
static int i;
static int usedMinions = 0;
static int usedSpells = 0;
static int usedTaunts = 0;
static String cls = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
private static Scanner x;
public static void addcards(){
for (i = numberOfCards; i <= numberOfCards; i++) {
boolean DoneWithCard = false;
while(DoneWithCard == false){
card[i] = new Card();
System.out.print("Name of Card >> ");
card[i].setName(input.nextLine());
System.out.print(card[i].getName()+"'s Class >> ");
card[i].setCharacter(input.nextLine());
boolean isValid = false;
String message = "";
String cardtype = "";
while(isValid == false){
System.out.println(message +"Is " + card[i].getName() + " a minion or a spell >>");
if(input.nextLine().equalsIgnoreCase("minion")){
card[i].setIsMinion(true);
isValid = true;
cardtype = "minion";
}
else if(input.nextLine().equalsIgnoreCase("spell")){
card[i].setIsSpell(true);
isValid = true;
cardtype = "spell";
}
else{
message = "<INVALID ENTRY TRY AGAIN> ";
}
}
String hastaunt = "";
System.out.print("Does "+ card[i].getName() + " have Taunt (Y/N) >>");
if(input.nextLine().equalsIgnoreCase("Y")) {
card[i].setHasTaunt(true);
hastaunt = "Does";
}
else{
card[i].setHasTaunt(false);
hastaunt = "Does not";
}
System.out.print("What is " +card[i].getName() +"'s mana cost >>");
card[i].setMana(input.nextInt());
if(card[i].getIsSpell() == false){
System.out.print("What is " +card[i].getName() +"'s health >>");
card[i].setHealth(input.nextInt());
}
else{
card[i].setHealth(0);
}
System.out.print("What is " +card[i].getName() +"'s damage >>");
card[i].setDamage(input.nextInt());
System.out.println("would you like to add a desription (Y/N)");
String ADesc = input.nextLine();
if(input.nextLine().equalsIgnoreCase("y")){
System.out.println("What is "+ card[i].getName() + "'s description >>");
card[i].setDescription(input.nextLine());
}
else{
System.out.println("Alright next");
}
System.out.println(card[i].getName() + " is a(n) " + cardtype + " with " +card[i].getDamage() + ""
+ "/" + card[i].getHealth() + "\nand " + hastaunt + " have taunt");
System.out.print("is this correct? (Y/N)");
if(input.nextLine().equalsIgnoreCase("Y")){
DoneWithCard = true;
}
else{
DoneWithCard = false;
}
}
System.out.print("Do you want to enter another card? (Y/N)");
if(input.nextLine().equalsIgnoreCase("n")){
numberOfCards = i+1;
save.OpenFile();
save.addRecords();
save.closeFile();
numberOfCards++;
parameters();
}
else{
numberOfCards++;
}
}
}
public static void setup(){
int counter = 0;
boolean add = false;
System.out.println("Current Cards >>");
openFile();
}
public static void openFile(){
try{
x = new Scanner(new File("HearthCards.txt"));
}
catch(Exception e){
System.out.println("Load Failure");
}
readFile();
}
public static void readFile(){
Card[] cardie = new Card[numberOfCards];
while(x.hasNext()){
numberOfCards++;
int a = 0;
String name = x.next();
String Character= x.next();
int Health = Integer.parseInt(x.next());
int Damage = Integer.parseInt(x.next());
int Mana = Integer.parseInt(x.next());
int TimesUsed = Integer.parseInt(x.next());
boolean hasTaunt = Boolean.parseBoolean(x.next());
boolean isMinion = Boolean.parseBoolean(x.next());
boolean isSpell = Boolean.parseBoolean(x.next());
card[a].setName(name);
card[a].setCharacter(Character);
card[a].setHealth(Health);
card[a].setDamage(Damage);
card[a].setMana(Mana);
card[a].setTimesUsed(0);
card[a].setHasTaunt(hasTaunt);
card[a].setIsMinion(isMinion);
card[a].setIsSpell(isSpell);
a++;
}
closeFile();
}
public static void closeFile(){
x.close();
setupcont();
}
public static void setupcont(){
for (int j = 0; j <= 30; j++) {
String type = "oof";
String taunts = "oofer";
if(card[j].getIsMinion() == true){
type = "minion";
}
else if(card[j].getIsSpell() == true){
type = "spell";
}
if(card[j].getHasTaunt() == true){
taunts = "has";
}
else{
taunts = "doesnt have";
}
System.out.println(cls);
System.out.println(card[j].getName() + " >> " + card[j].getName() + " is a " + type + " that "+ taunts + " taunt");
}
System.out.print("would you like to add any new Cards (Y/N)");
if(input.nextLine().equalsIgnoreCase("y")){
addcards();
}
else{
makedeck();
}
}
public static void parameters(){
System.out.print("Would you like to use default max and mins, or custom >> ");
if(input.nextLine().equalsIgnoreCase("default")){
makedeck();
}
else{
System.out.print("What should the mana average be?");
manaAVG = input.nextInt();
System.out.println("What is the max taunt minions ?");
maxTaunt = input.nextInt();
System.out.print("What is max minions (1-30) >> ");
maxMinions = input.nextInt();
System.out.print("What is the max spells (1-30) >> ");
maxSpell = input.nextInt();
if(maxMinions + maxSpell < 30){
System.out.println("<INVALID ENTRY TRY AGAIN> What is the max spells (1-30 >> ");
maxSpell = input.nextInt();
}
}
}
public static void makedeck(){
Card deck[] = new Card[30];
for(int a = 0; a <= 30; a++){
Random ran = new Random(i);
int rand = ran.nextInt();
if(card[rand].getTimesUsed() <= 2){
deck[a] = card[rand];
String hastaunt = "does not";
if(card[rand].getHasTaunt() == true){
hastaunt = "does";
usedTaunts++;
}
String cardtype = "";
if(card[rand].getIsMinion() == true && usedMinions < maxMinions){
usedMinions++;
cardtype = "minion";
}
System.out.println(deck[rand].getName() + " is a(n) " + cardtype + " with " +deck[rand].getDamage() + ""
+ "/" + deck[rand].getHealth() + "\nand " + hastaunt + " have taunt");
}
}
boolean isDone = false;
Random ran = new Random(i);
int rand = ran.nextInt();
boolean minMinDone = false;
boolean maxMinDone = false;
boolean minSpellDone = false;
boolean maxSpellDone = false;
boolean minTauntDone = false;
boolean maxTauntDone = false;
boolean correctClass = false;
System.out.println("What Class would you like to use");
String usedClass = input.nextLine();
while(isDone == false){
Random R = new Random(i);
int Ran = R.nextInt();
if(usedMinions < minMinions){
Ran = R.nextInt();
if(deck[Ran].getIsMinion() == false){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
minMinDone = true;
}
if(usedMinions > maxMinions){
Ran = R.nextInt();
if(deck[Ran].getIsMinion() == true){
int random = R.nextInt();
deck[Ran] = card[random];
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
maxMinDone = true;
}
if(usedSpells < minSpell){
Ran = R.nextInt();
if(deck[Ran].getIsSpell() == false){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
minSpellDone = true;
}
if(usedSpells > maxSpell){
Ran = R.nextInt();
if(deck[Ran].getIsMinion() == true){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
maxSpellDone = true;
}
if(usedTaunts < minTaunt){
Ran = R.nextInt();
if(deck[Ran].getHasTaunt() == false){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
card[Ran].setTimesUsed(card[Ran].getTimesUsed() + 1);
}
}
}
else{
minTauntDone = true;
}
if(usedTaunts > maxTaunt){
Ran = R.nextInt();
if(deck[Ran].getHasTaunt() == true){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2){
deck[Ran] = card[random];
}
}
}
else{
maxTauntDone = true;
}
correctClass = false;
for (int j = 0; j <= 30; j++) {
while(!deck[j].getCharacter().equalsIgnoreCase(usedClass)){
int random = R.nextInt();
if(card[random].getTimesUsed() <= 2 && card[random].getCharacter().equalsIgnoreCase(usedClass)){
deck[j] = card[random];
}
}
}
correctClass = true;
if(minMinDone == true && maxMinDone == true && minSpellDone == true && maxSpellDone == true && minTauntDone == true && maxTauntDone == true && correctClass == true){
isDone = true;
}
else{
isDone = false;
}
}
for (int j = 0; j <= 30; j++) {
String type = "oof";
String taunts = "oofer";
if(deck[j].getIsMinion() == true){
type = "minion";
}
else if(deck[j].getIsSpell() == true){
type = "spell";
}
if(deck[j].getHasTaunt() == true){
taunts = "has";
}
else{
taunts = "doesnt have";
}
System.out.println(cls);
if(!deck[j].getDescription().equals("")){
System.out.println(deck[j].getName() + " >> " + deck[j].getName() + " is a " + type + " that "+ taunts + " taunt >>> \n\t" + deck[j].getDescription());
}
else{
System.out.println(deck[j].getName() + " >> " + deck[j].getName() + " is a " + type + " that "+ taunts + " taunt");
}
}
}
public static void main(String[] args) {
setup();
}
}
Card
package hearthstone.deck.maker;
public class Card {
private String Name;
private String Class;
private boolean HasTaunt;
private int Mana;
private int Damage;
private int Health;
private boolean isMinion = false;
private boolean isSpell = false;
private boolean isElemental = false;
private int TimesUsed = 0;
private String Description = " no description ";
//Omitted getters and setters
public Card(){
}
}
createFile
package hearthstone.deck.maker;
import java.io.*;
import java.lang.*;
import java.util.*;
public class createfile {
int numCards = HearthStoneDeckMaker.numberOfCards;
private Formatter x;
public void OpenFile(){
try{
x = new Formatter("HearthCards.txt");
}
catch(Exception e){
System.out.println("Save Failed");
}
}
public void addRecords(){
for (int j = 0; j < HearthStoneDeckMaker.numberOfCards; j++) {
x.format("%s %s %x %x %x %x %b %b %b %n", HearthStoneDeckMaker.card[j].getName(), HearthStoneDeckMaker.card[j].getCharacter(), HearthStoneDeckMaker.card[j].getHealth(), HearthStoneDeckMaker.card[j].getDamage(), HearthStoneDeckMaker.card[j].getMana(), HearthStoneDeckMaker.card[j].getTimesUsed(), HearthStoneDeckMaker.card[j].getHasTaunt(), HearthStoneDeckMaker.card[j].getIsMinion(), HearthStoneDeckMaker.card[j].getIsSpell());
}
}
public void closeFile(){
x.close();
}
}
I have a string input which, that input have a team name and score separated by one space. e.g bb 3 , teamd 5 the winner should be teamd
In order to get the winner team that scored highest score, i'm doing following:
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String str = "";
String winnerTeam = "";
int winnerScore = 0, countedChar = 0;
for (int i = 0; i < cases; i++) {
str += scanner.nextLine();
}
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
countedChar++;
if (arr[i] == ' ') {
if (str.charAt(i + 1) > winnerScore) {
winnerTeam = "";
winnerScore = (int) str.charAt((int) i + 1);
for (int j = 0; j < countedChar; j++) {
winnerTeam += str.charAt(j);
}
countedChar = 0;
} else {
//winnerTeam = "";
countedChar = 0;
}
}
}
System.out.println(winnerTeam);
}
But it's not work prefect, It's print wired result, how to make that work as expect ?
I haven't tried your code, But I would imagine a big problem is the concatenation of str += scanner.nextLine(); The new line is going to be appended straight onto the end of the previous lines number
Have a look at this
Scanner sc = new Scanner(System.in);
int bestScore = Integer.MIN_VALUE;
String team = "Nothing entered";
System.out.println("how many teams");
int count = sc.nextInt();
sc.nextLine();
while (count-- > 0) {
System.out.println("Entered team,score");
String line = sc.nextLine();
String arr [] = line.split(" ");
// check size - TBD
if (Integer.parseInt(arr[1]) > bestScore) {
bestScore = Integer.parseInt(arr[1]);
team = arr[0];
}
}
System.out.println("nest team is " + team + " with a score of " + bestScore);
If I have to do something like that I will do it like this:
import java.util.*;
public class winner {
public static void main (String args []) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String winnerTeam = "";
String Team="";
int winnerScore = 0, score = 0;
for (int i = 0; i < cases; i++) {
Team = scanner.next();
score = scanner.nextInt();
if(score > winnerScore){
winnerTeam = Team;
winnerScore = score;
}
}
System.out.println("Winner team" + winnerTeam + "Score:" + winnerScore);
}
}
I am new to CS and I am doing this online java class which is a joke tbh. I say that because the books we got are $15 books, custom made that were used for a summer camp that was "taught" to kids. There is no where in the book that has actual java information, it is just a bunch of programs. I did a bit of searching around and I can't seem to find what I am looking for.
One thing we have to do is modify the program so it can display first and last name. I have looked and seen that you can do two strings to get first and last name. Is there something that will get the entire line in java?
package computegrades;
import java.util.Scanner;
public class ComputeGrades {
public static void main (String[] args) {
String[] names = getNames();
int[] scores = getScores(names);
double average = computeAverage(scores);
int highestIndex = getHighest(scores);
int lowestIndex = getLowest(scores);
System.out.format("Average = %3.2f\n", average);
System.out.println("Highest = " + names[highestIndex] + ": " + scores [highestIndex]);
System.out.println("Lowest = " + names[lowestIndex] + ": " + scores [lowestIndex]);
printLetterGrades(names, scores);
}
public static void printLetterGrades(String[] names, int[] scores) {
for (int i = 0; i < names.length; i++) {
if (scores[i] >= 90) {
System.out.println(names[i] + ": A");
} else if (scores[i] >= 80) {
System.out.println(names[i] + ": B");
} else if (scores[i] >= 70) {
System.out.println(names[i] + ": C");
} else if (scores[i] >= 60) {
System.out.println(names[i] + ": D");
} else {
System.out.println(names[i] + ": F");
}
}
}
public static String[] getNames() {
Scanner input = new Scanner(System.in);
System.out.println("How many students?");
int n = input.nextInt();
System.out.println("Please enter their first names:");
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.print("name " + (i + 1) + ": ");
names[i] = input.next();
}
System.out.println("Thank you.");
return names;
}
public static int[] getScores(String[] names) {
System.out.println("Now, please enter their scores:");
Scanner input = new Scanner(System.in);
int[] scores = new int[names.length];
for (int i = 0; i < names.length; i++) {
System.out.print(names[i] + "'s ");
System.out.print("score: ");
while(!input.hasNextInt()){
input.next();
System.out.println("Please enter an integer for the score");
System.out.print("scores: ");
}
scores[i] = input.nextInt();
}
return scores;
}
public static double computeAverage(int[] scores) {
double sum = 0;
for (int i = 0; i < scores.length; i++) {
sum += scores[i];
}
return sum / scores.length;
}
public static int getHighest(int[] scores) {
int highestIndex = Integer.MIN_VALUE;
int highestScore = Integer.MIN_VALUE;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > highestScore) {
highestScore = scores[i];
highestIndex = i;
}
}
return highestIndex;
}
public static int getLowest(int[] scores) {
int lowestIndex = Integer.MAX_VALUE;
int lowestScore = Integer.MAX_VALUE;
for (int i = 0; i < scores.length; i++) {
if (scores[i] < lowestScore) {
lowestScore = scores[i];
lowestIndex = i;
}
}
return lowestIndex;
}
}
Being new to Java, one of the resources you need to have on hand is the Oracle documentation pages, for example:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
That will guide you on what a Scanner can do.
Specifically, you should look for
.nextLine()
Currently, I'm trying to read in a .dat file and assign various lines into an array. The file will provide items like "a100" and "q80" which I will have to separate into categories by letter and then have different grades as an array for each category. Right now, this is what I have, but I'm getting a lot of run-time errors when I try various things. Is there something I'm missing here?
Some of the errors I'm having:
When I execute case 'P', it prints this out: WeightedGrades#13105f32
When I try to execute cases C, A or D, this happens: Exception in thread "main" java.lang.NoSuchMethodError: WeightedGrades.deleteGrade(Ljava/lang/String;)Z
WeightedGrades class:
public class WeightedGrades {
private String name;
private int numGrades;
private String[] grades;
public static final double ACTV_WT = 0.05, QUIZ_WT = 0.10, PROJ_WT = 0.25, EXAM_WT = 0.30, FINAL_EXAM_WT = 0.30;
public WeightedGrades(String nameIn, int numGradesIn, String[] gradesIn) {
name = nameIn;
numGrades = numGradesIn;
grades = gradesIn;
}
public String getName() {
return name;
}
public int getNumGrades() {
return numGrades;
}
public String[] getGrades() {
return grades;
}
public double[] gradesByCategory(char categoryChar) {
int count = 0;
for (int i = 0; i < grades.length; i++) {
if (categoryChar == grades[i].charAt(0)) {
count++;
}
}
double[] gradesNew = new double[count];
count = 0;
for( int i = 0; i < numGrades; i++) {
if (categoryChar == grades[i].charAt(0)) {
gradesNew[count] = Double.parseDouble(grades[i].substring(1));
count++;
}
}
return gradesNew;
}
public String toString() {
String result = "\tStudent Name: " + getName()
+ "\n\tActivities: " + gradesByCategory('A')
+ "\n\tQuizzes: " + gradesByCategory('Q')
+ "\n\tProjects: " + gradesByCategory('P')
+ "\n\tExams: " + gradesByCategory('E')
+ "\n\tFinal Exam: " + gradesByCategory('F')
+ "\n\tCourse Average: " + courseAvg();
return result;
}
public void addGrade(String newGrade) {
if (numGrades >= grades.length) {
increaseGradesCapacity();
}
grades[numGrades] = newGrade;
numGrades++;
}
public boolean deleteGrade(String gradeDelete) {
boolean delete = false;
int deleteIndex = -1;
for (int i = 0; i < numGrades; i++) {
if (gradeDelete.charAt(0) == grades[i].charAt(0) &&
Double.parseDouble(gradeDelete.substring(1))
== Double.parseDouble(grades[i].substring(1))) {
deleteIndex = i;
}
}
if (deleteIndex > -1) {
for (int i = deleteIndex; i < numGrades - 1; i++) {
grades[i] = grades[i + 1];
}
grades[numGrades - 1] = "";
numGrades--;
return true;
}
else {
return false;
}
}
public void increaseGradesCapacity() {
String[] temporary = new String[grades.length + 1];
for (int i = 0; i < grades.length; i++) {
temporary[i] = grades[i];
}
grades = temporary;
}
public double average(double[] newArray) {
if (newArray.length == 0) {
return 0.0;
}
double sum = 0;
double average = 0;
for ( int i = 0; i < newArray.length; i++) {
sum += newArray[i];
average = sum / newArray.length;
}
return average;
}
public double courseAvg() {
double actvAvg = 0.0;
double quizAvg = 0.0;
double projAvg = 0.0;
double examAvg = 0.0;
double finalAvg = 0.0;
double avg = 0.0;
if (!numGrades.length == 0) {
avg = actvAvg * ACTV_WT + quizAvg * QUIZ_WT + projAvg * PROJ_WT + examAvg * EXAM_WT + finalAvg * FINAL_EXAM_WT;
}
return avg;
}
}
Second class
import java.util.Scanner;
import java.io.IOException;
public class WeightedGradesApp {
public static void main(String[] args) throws IOException {
String name = "";
int numGrades = 0;
String[] grades = new String[13];
String code = "";
String gradeAdd = "";
String gradeDelete = "";
String categoryIn = "";
WeightedGrades student = new WeightedGrades(name, numGrades, grades);
Scanner userInput = new Scanner(System.in);
if (args == null) {
System.out.println("File name was expected as a run argument.");
System.out.println("Program ending.");
return;
}
else {
System.out.println("File read in and WeightedGrades object created.");
System.out.println("");
System.out.println("Player App Menu");
System.out.println("P - Print Report");
System.out.println("C - Print Category");
System.out.println("A - Add Grade");
System.out.println("D - Delete Grade");
System.out.println("Q - Quit ");
do {
System.out.print("Enter Code [P, C, A, D, or Q]: ");
code = userInput.nextLine();
if (code.length() == 0) {
continue;
}
code = code.toUpperCase();
char codeChar = code.charAt(0);
switch (codeChar) {
case 'P':
System.out.println(student.toString());
break;
case 'C':
System.out.print(" Category: ");
categoryIn = userInput.nextLine();
char categoryChar = categoryIn.charAt(0);
System.out.println(student.gradesByCategory(categoryChar));
break;
case 'A':
System.out.print(" Grade to add: ");
gradeAdd = userInput.nextLine();
student.addGrade(gradeAdd);
break;
case 'D':
System.out.print(" Grade to delete: ");
gradeDelete = userInput.nextLine();
boolean isDeleted = student.deleteGrade(gradeDelete);
if (isDeleted) {
System.out.println(" Grade deleted");
}
else {
System.out.println(" Grade not found");
}
break;
case 'Q':
break;
default:
}
} while (!code.equalsIgnoreCase("Q"));
}
}
}
For starters your code as is doesn't compile due to the line
if (!numGrades.length == 0) {
This is because numGrades is an int it is a primative type and therefore does not have any property length. I'm assuming what you want here is
if (numGrades != 0) {
Also as I mentioned you are not dealing with reading in the file, you supply the file name but never actually read it, I suggest you look at the Java tutorial on File IO
On this note you do the check args == null this will not check that no args are supplied, try it. what you want is args.length == 0
On your other error I have no idea how you even produced that... I'm assuming it is using an older compiled version of the class where the methods have not being written.