i have a exercice to do in Java. I need to create a World Cup tournament and the restriction is that the program will restart until my favourite team win. However, if my team didn't win after 20 times, the program stop
The problem is when I try to put the second restriction (20 times max) with a for after the while (true), I always get an infinite loop.
//Q1
String[] teams16 = {"Uruguay", "Portugal", "France", "Argentina", "Brazil", "Mexico",
"Belgium", "Japan", "Spain", "Russia", "Croatia", "Denmark", "Sweden", "Switzerland",
"Colombia", "England"};
//data
Scanner keyboard = new Scanner(System.in);
Random result = new Random();
System.out.print("Enter your favourite team: ");
String team = keyboard.nextLine();
boolean teamwc = false;
// choice of the favourite team
for (int i = 0 ; i < 16 ; i++ ) {
if (teams16[i].equalsIgnoreCase(team)) {
teamwc = true;
}
}
if(teamwc == false) {
System.out.println("Your team is not in the Round of 16 ");
}
// the tournament begins (ROUND OF 16)
while (true) {
if (teamwc == true) {
int z = 0;
String[] winnerof16 = new String[8];
int a = 0;
System.out.print("ROUND OF 16:");
for (int i = 0; i < 16 ; i+=2) {
int score1 = result.nextInt(5);
int score2 = result.nextInt(5);
if (score1 > score2) {
winnerof16 [a] = teams16[i];
}
else if (score1 < score2) {
winnerof16[a] = teams16[i+1];
} else if (score1 == score2) {
Random overtime = new Random();
int ot = overtime.nextInt(2);
if (ot == 0) {
score1++;
winnerof16[a] = teams16[i];
} else if (ot == 1) {
score2++;
winnerof16[a]=teams16[i+1];
}
}
System.out.print("["+teams16[i] +"]"+ " " + score1+":"+score2 + " " + "["+teams16[i+1]+"]" + " ");
a++;
}
System.out.println();
String[] winnerof8 = new String[4];
int b = 0;
System.out.print("QUARTER-FINALS:");
for (int k = 0 ; k < 8 ; k+=2) {
int score3 = result.nextInt(5);
int score4 = result.nextInt(5);
if (score3 > score4) {
winnerof8[b]=winnerof16[k];
}
else if (score3 < score4) {
winnerof8[b] = winnerof16[k+1];
} else if (score3 == score4) {
Random overtime2 = new Random();
int ot2 = overtime2.nextInt(2);
if (ot2 == 0) {
score3++;
winnerof8[b]=winnerof16[k];
} else if (ot2 == 1) {
score4++;
winnerof8[b]=winnerof16[k+1];
}
}
System.out.print("["+winnerof16[k] +"]"+ " " + score3+":"+score4 + " " + "["+winnerof16[k+1]+"]" + " ");
b++;
}
System.out.println();
String[] winnerof4 = new String[2];
int c = 0;
System.out.print("SEMI-FINALS:");
for (int l = 0 ; l < 4 ; l+=2) {
int score5 = result.nextInt(5);
int score6 = result.nextInt(5);
if (score5 > score6) {
winnerof4[c]=winnerof8[l];
}
else if (score5 < score6) {
winnerof4[c] = winnerof8[l+1];
} else if (score5 == score6) {
Random overtime3 = new Random();
int ot3 = overtime3.nextInt(2);
if (ot3 == 0) {
score5++;
winnerof4[c]=winnerof8[l];
} else if (ot3 == 1) {
score6++;
winnerof4[c]=winnerof8[l+1];
}
}
System.out.print("["+winnerof8[l] +"]"+ " " + score5+":"+score6 + " " + "["+winnerof8[l+1]+"]" + " ");
c++;
}
System.out.println();
String[] winnerof2 = new String[1];
int d = 0;
System.out.print("FINALS:");
for (int m = 0 ; m < 2 ; m+=2) {
int score7 = result.nextInt(5);
int score8 = result.nextInt(5);
if (score7 > score8) {
winnerof2[d]=winnerof4[m];
}
else if (score7 < score8) {
winnerof2[d] = winnerof4[m+1];
} else if (score7 == score8) {
Random overtime4 = new Random();
int ot4 = overtime4.nextInt(2);
if (ot4 == 0) {
score7++;
winnerof2[d]=winnerof4[m];
} else if (ot4 == 1) {
score8++;
winnerof2[d]=winnerof4[m+1];
}
}
System.out.print("["+winnerof4[m] +"]"+ " " + score7+":"+score8 + " " + "["+winnerof4[m+1]+"]" + " ");
System.out.println();
}
System.out.println("Tournament: " + z + " The WINNER is: " + winnerof2[d]);
z++;
if (winnerof2[d].equalsIgnoreCase(team)) {
break;
}
}
}
}
}
This is my code before I put the second restriction.
Is there a problem with my code ? How can I put the second restriction ? Thank you
The infinite loop is due to this 2:
while (true) { // it will quit while loop only when an exception raised
if (teamwc == true) { // after this you nowhere assign teamwc == false therefore it is always true
instead of direct assigning True to while loop, use a boolean variable or a condition to quit somewhere:
t = true
while(t):
OR
while n>0:
Related
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package w01s03p;
import static java.sql.Types.NULL;
import java.util.Scanner;
/**
*
* #author WIN8
*/
public class task5 {
private static int hitLevel;
private static int attackLevel;
private static int defLevel;
private static int LEVEL;
private static int numberOfData;
private static String[] arrName;
private static int dataCounter;
private static int dataOfCounter;
private static int inputChoice;
private static double temp;
public static void main(String[] _args) {
int numberOfData = 3;
int i, temp = 0;
int inputChoice;
//declaration
String[] arrName;
double[] arrHP;
double[] arrAP;
double[] arrDP;
double[] hitLevel;
double[] attackLevel;
double[] defLevel;
double[] LEVEL;
//instantiation
arrName = new String[numberOfData];
arrHP = new double[numberOfData];
arrAP = new double[numberOfData];
arrDP = new double[numberOfData];
hitLevel = new double[numberOfData];
attackLevel = new double[numberOfData];
defLevel = new double[numberOfData];
LEVEL = new double[numberOfData];
do {
Scanner scanner = new Scanner(System.in);
System.out.println("--------------------");
System.out.println("Monsville Tournament");
System.out.println("--------------------");
System.out.println("1.List Monster");
System.out.println("2.Best By Hits Point");
System.out.println("3.Best By Attack Point");
System.out.println("4.Best By Defense Attack");
System.out.println("5.Search Profile");
System.out.println("6.Registration Monster");
System.out.println("0.Quit");
inputChoice = Keyin.inInt(" Your Choice: ");
switch (inputChoice) {
case 1:
System.out.println("List Monster : ");
if (arrName == null) {
System.out.println("Input Monster");
} else {
for (i = 0; i < 2; i++) {
System.out.println("Monster Name " + arrName[i]);
}
}
break;
case 2:
System.out.println("Daftar Best HP!");
if(arrHP != null){
for (i = 0; i < 2; i++) {
if (arrHP[i] < arrHP[i + 1]) {
temp = (int) arrHP[i + 1];
arrHP[i + 1] = arrHP[i];
arrHP[i] = temp;
}
System.out.println("HP (" + arrHP[i] + ") :" + arrName[i]);
}
}
break;
case 3:
System.out.println("Daftar Best AP!");
for (i = 0; i < 2; i++) {
if (arrAP[i] < arrAP[i + 1]) {
temp = (int) arrAP[i + 1];
arrAP[i + 1] = arrAP[i];
arrAP[i] = temp;
}
System.out.println("AP (" + arrAP[i] + ") :" + arrName[i]);
}
break;
case 4:
System.out.println("Daftar Best DP!");
for (i = 0; i < 2; i++) {
if (arrDP[i] < arrDP[i + 1]) {
temp = (int) arrDP[i + 1];
arrDP[i + 1] = arrDP[i];
arrDP[i] = temp;
}
System.out.println("DP (" + arrDP[i] + ") :" + arrName[i]);
}
break;
case 5:
System.out.println("Search Profile Monster");
break;
case 6:
for (i = 0; i < 2; i++) {
System.out.print("Monster Name: ");
arrName[i] = scanner.next();
System.out.print("hit point: ");
arrHP[i] = scanner.nextInt();
System.out.print("attack point: ");
arrAP[i] = scanner.nextInt();
System.out.print("defense point: ");
arrDP[i] = scanner.nextInt();
}
break;
default:
System.out.println("Invalid selection");
break;
}
} while (inputChoice != 0);
for (i = 0; i < 2; i++) {
if (arrHP[i] >= 100) {
hitLevel[i] = 3;
} else if ((arrHP[i] >= 50) && (arrHP[i] < 100)) {
hitLevel[i] = 2;
} else if (arrHP[i] < 50) {
hitLevel[i] = 1;
}
}
for (i = 0; i < 2; i++) {
if (arrAP[i] >= 20) {
attackLevel[i] = 3;
} else if ((arrAP[i] >= 10) && (arrAP[i] < 20)) {
attackLevel[i] = 2;
} else if (arrAP[i] < 10) {
attackLevel[i] = 1;
}
}
for (i = 0; i < 2; i++) {
if (arrDP[i] >= 15) {
defLevel[i] = 3;
} else if ((arrDP[i] >= 5) && (arrAP[i] < 15)) {
defLevel[i] = 2;
} else if (arrDP[i] < 5) {
defLevel[i] = 1;
}
}
for (i = 0; i < 2; i++) {
LEVEL[i] = +hitLevel[i] + attackLevel[i] + defLevel[i];
}
System.out.println("---------monster profile ---------\"");
for (i = 0; i < 2; i++) {
System.out.println("name : \"" + arrName[i] + "\"");
System.out.println("hit point :" + arrHP[i]);
System.out.println("attack point :" + arrAP[i]);
System.out.println("defense point:" + arrDP[i]);
System.out.println("level :" + LEVEL[i] + "(" + arrHP[i] + "/" + arrAP[i] + "/" + arrDP[i] + ")");
}
}
}
I wish to find the monster by it's name in a search query but I don't know how to search for the monster's information by it's name. The monster's information is separated in many arrays. If inputChoice is 5, then it should prompt the user to find a monster's profile.
Thankss
One hint: do not create 5 different arrays that carry different properties of a "player" (like one for player names, one for player points, ..). Instead: create a class that represents one Player and give that class all the attributes that a player should have. And then create one array to hold player objects! – GhostCat
Perfect response from GhostCat.
But if you're not following his advice, you'd have to do it like this:
Get input from the console, i.e: the name of the monster;
Search for the name in the monster array.
If the name matches the input, save the index of that monster
Obtain all info from that monster using that index number.
The code would look similar to:
String searchQuery = scanner.next();
int indexFound = -1;
for(int x = 0; x < arrName.length; x++) {
if(arrName[x] != null && (arrName[x].toLowerCase().equals(searchQuery.toLowerCase()) || arrName[x].toLowerCase().contains(searchQuery.toLowerCase())) {
indexFound = x;
break;
}
}
if(indexFound != -1) {
System.out.println("Monster Found by the name of " + searchQuery)
System.out.println("name : \"" + arrName[indexFound] + "\"");
System.out.println("hit point :" + arrHP[indexFound]);
System.out.println("attack point :" + arrAP[indexFound]);
System.out.println("defense point:" + arrDP[indexFound]);
System.out.println("level :" + LEVEL[indexFound] + "(" + arrHP[indexFound] + "/" + arrAP[indexFound] + "/" + arrDP[indexFound] + ")");
} else {
System.out.println("Monster not found");
}
Place that piece of code under your case 5:.
This is my task
I have the program, printing out the values in the arrays, that step does not need to be there, that is the last for loop. Instead of that I need add the rows up, value by value using the die class i have, the code is something.getFaceValue();.
Code is Below
import java.util.Scanner;
class ASgn8
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt(); // get number of participant player...
scan.nextLine();
Die[] tempDie = new Die[5]; // temporary purpose
Die[][] finalDie = new Die[5][]; // final array in which all rolled dies stores...
int tempVar = 0;
String [] playerName = new String[playerCount]; // stores player name
int totalRollDie = 0; // keep track number of user hash rolled dies...
for(int i = 0; i < playerCount; i++) // get all player name from command prompt...
{
System.out.print("What is your name: ");
String plyrName = scan.nextLine();
playerName[i] = plyrName;
}
for(int i = 0; i < playerCount; i++)
{
System.out.println(playerName[i] + "'s turn....");
totalRollDie = 0;
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
tempDie[totalRollDie] = d;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
int choice = scan.nextInt();
while(choice == 1)
{
if(totalRollDie < 5)
{
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ;
tempDie[totalRollDie] = dd;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
choice = scan.nextInt();
}
}
finalDie[i] = new Die[totalRollDie];
for(int var = 0 ; var < totalRollDie ; var++)
{
finalDie[i][var] = tempDie[var];
}
}
for(int i = 0 ;i < playerCount ; i++) //prints out the values stored in the array. need to sum them instead.
{
System.out.println(" --------- " + playerName[i] + " ------------ ");
for(Die de : finalDie[i])
{
System.out.println(de);
}
}
tempDie = null;
}
}
Anyone have any tips?
EDIT: Die class
public class Die
{
private final int MAX = 6;
private int faceValue;
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Append following code into your existance code,
public static void main(String... s)
{
......
int score[][] = new int[playerCount][2];
for(int i = 0 ;i < playerCount ; i++){ // finally print whatever user's roll value with all try...
// System.out.println(" --------- " + playerName[i] + " ------------ ");
int playerTotalScore = 0;
for(Die de : finalDie[i]){
// System.out.println(de);
playerTotalScore += de.getFaceValue();
}
score[i][0] = i;
score[i][1]=playerTotalScore;
}
tempDie = null;
System.out.println("------------- Participant Score Card -------------");
System.out.println("Index PlayerName Score");
for(int i = 0 ; i < score.length ; i++){
System.out.println(score[i][0] + " - " + playerName[score[i][0]] + " - " + score[i][1]);
}
int temp[][] = new int[1][2];
for(int i = 0 ; i< score.length; i++){
for(int j = i+1 ; j<score.length;j++){
if(score[i][1] < score[j][1]){
temp[0][0] = score[i][0];
temp[0][1] = score[i][1];
score[i][0] = score[j][0];
score[i][1] = score[j][1];
score[j][0] = temp[0][0];
score[j][1] = temp[0][1];
}
}
}
System.out.println("--------------------------------------------------------");
System.out.println("-----------------WINNER---------------------");
System.out.println(score[0][0] + " - " + playerName[score[0][0]] + " - " + score[0][1]);
System.out.println("--------------------------------------------------------");
} // end of main method...
If I understand your question well, you could store the value in a variable;
int[] mPlayerScores = new int[playerCount];
String name = "";
for(int i = 0 ;i < playerCount ; i++) //prints out the values stored in the array. need to sum them instead.
{
int playerScoreSum = 0;
name = playerName[i];
System.out.println(" --------- " + name + " ------------ ");
for(Die de : finalDie[i])
{
playerScoreSum += de;
}
// this should store the sums in an array
mPlayerScores[i] = playerScoreSum;
//display the result for each player outside the for-loop to avoid continous printing
System.out.println(playerScoreSum);
}
//finds the highest score
double max = mPlayerScores[0];
for (int j = 1; j< mPlayerScores.length; j++)
{
if (mPlayerScores[j] > max)
{
max = mPlayerScores[j];
}
}
System.out.println(name+" is the winner with " + max+ " score");
I just want to follow this condition, but the problem is that when i enter the empty, it will be continue loop infinity.
Please Enter either S (supply) or R (replenish) followed by ID and quantity.
R p122 10
New Stock-level for p125 (Pedal) is 18
S p905 20
No part found with ID p905
Empty String (to terminate)
Display the final.
I also try the following code, but it couldn't work
if (n.equals("")){
code
}
Here's my code:
import java.util.*;
public class TestPart {
public static void main(String[] args)
{
Part[] part = new Part[5];
part[0] = new Part("p122", "Chain", 48, 12.5 );
part[1] = new Part("p123", "Chain Guard", 73, 22.0 );
part[2] = new Part("p124", "Crank", 400, 11.5 );
part[3] = new Part("p125", "Pedal", 38, 6.5 );
part[4] = new Part("p126", "Handlebar", 123, 9.50 );
Scanner src = new Scanner(System.in);
String n;
String id;
int qty;
System.out.print("Please Enter either S(supply) or R(replenish) followed by ID and quantity:\n");
int a = 0;
do
{
n = src.next();
id= src.next();
qty= src.nextInt();
boolean found = false;
for(int i = 0; i< part.length; i++)
{
if(part[i].getID().equals(id))
{
found = true;
String name = part[i].getName();
int stockLevel = part[i].getStockLevel();
if(id.equals(part[i].getID()) && n.charAt(0) == 'S')
{
double amount = part[i].supply(qty);
if(amount>0){
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is " + part[i].getStockLevel());
}
else{
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is not available" );
}
}
else if (id.equals(part[i].getID()) && n.charAt(0) == 'R')
{
part[i].replenish(qty);
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is " + part[i].getStockLevel());
}
}
}
if (found == false)
{
System.out.println("No part found with ID " + id );
}
System.out.println("");
for(int i=0; i<part.length; i++)
{
System.out.println(part[i].getID()+ "\t"+part[i].getName()+"\t"+part[i].getStockLevel()+"\t"+part[i].getUnitPrice() );
}
}while(a ==0);
}
If you want to terminate when the input line is empty
do{
String line = src.nextLine();
String [] inputs = null;
if(!line.matches("\\s*")){
String n ;
String id ;
int qty;
inputs = line.split(" ");
if(inputs.length ==3)
{
n = inputs[0];
id = inputs[1];
qty = (int) Integer.parseInt(inputs[2]);
}
else if(inputs.length ==2)
{
id = inputs[0];
qty = (int) Integer.parseInt(inputs[1]);
}
// Your Logic
}
else
break;
}while(a==0)
Your code is:
a = 0;
do {
// ...
}while(a ==0);
that's why it loop infinitively.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Below is my code, and there are no errors in the actual code, but it won't run and I am not sure how to fix it. I have been working on this assignment for hours and keep receiving the same error in the output box over and over.
import java.util.Scanner;
public class whatTheGerbils
{
public static void main(String[] args)
{
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
Gerbil[] gerbilArray;
Food[] foodArray;
int numGerbils;
int foodnum;
public whatTheGerbils() {}
public void gerbLab()
{
boolean gerbLab = true;
while(gerbLab)
{
foodnum = 0;
numGerbils = 0;
String nameOfFood = "";
String colorOfFood;
int maxAmount = 0;
String ID;
String name;
String onebite;
String oneescape;
boolean bite = true;
boolean escape = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many types of food do the gerbils eat?");
int foodnum = Integer.parseInt(keyboard.nextLine());
foodArray = new Food[foodnum];
for (int i = 0; i < foodnum; i++)
{
System.out.println("The name of food item " + (i+1) + ":"); //this is different
nameOfFood = keyboard.nextLine();
System.out.println("The color of food item " + (i+1) + ":");
colorOfFood = keyboard.nextLine();
System.out.println("Maximum amount consumed per gerbil:");
maxAmount = keyboard.nextInt();
keyboard.nextLine();
foodArray[i] = new Food(nameOfFood, colorOfFood, maxAmount);
}
System.out.println("How many gerbils are in the lab?");
int numGerbils = Integer.parseInt(keyboard.nextLine()); // this is different
gerbilArray = new Gerbil[numGerbils];
for (int i = 0; i < numGerbils; i++)
{
System.out.println("Gerbil " + (i+1) + "'s lab ID:");
ID = keyboard.nextLine();
System.out.println("What name did the undergrads give to "
+ ID + "?");
name = keyboard.nextLine();
Food[] gerbsBetterThanMice = new Food[foodnum];
int foodType = 0;
for(int k = 0; k < foodnum; k++)
{
boolean unsound = true;
while(unsound)
{
System.out.println("How much " + foodArray[k].getnameOfFood() + "does" + name + " eat?");
foodType = keyboard.nextInt();
keyboard.nextLine();
if(foodType <= foodArray[k].getamtOfFood())
{
unsound = false;
}
else
{
System.out.println("try again");
}
}
gerbsBetterThanMice[k] = new Food(foodArray[k].getnameOfFood(), foodArray[k].getcolorOfFood(), foodType);
}
boolean runIt = true;
while (runIt)
{
System.out.println("Does " + ID + "bite? (Type in True or False)");
onebite = keyboard.nextLine();
if(onebite.equalsIgnoreCase("True"))
{
bite = true;
runIt = false;
}
else if (onebite.equalsIgnoreCase("False"))
{
bite = false;
runIt = false;
}
else {
System.out.println("try again");
}
}
runIt = true;
while(runIt)
{
System.out.println("Does " + ID + "try to escape? (Type in True or False)");
oneescape = keyboard.nextLine();
if(oneescape.equalsIgnoreCase("True"))
{
escape = true;
runIt = false;
}
else if(oneescape.equalsIgnoreCase("False"))
{
escape = false;
runIt = false;
}
else
{
System.out.println("try again");
}
}
gerbilArray[i] = new Gerbil(ID, name, bite, escape, gerbsBetterThanMice);
}
for(int i = 0; i < numGerbils; i++)
{
for(int k = 0; k < numGerbils; k++)
{
if(gerbilArray[i].getID().compareTo(gerbilArray[k].getID()) >
0)
{
Gerbil tar = gerbilArray[i];
gerbilArray[i] = gerbilArray[k];
gerbilArray[k] = tar;
}
}
}
boolean stop = false;
String prompt = "";
while(!stop)
{
System.out.println("Which function would you like to carry out: average, search, restart, or quit?");
prompt = keyboard.nextLine();
if (prompt.equalsIgnoreCase("average"))
{
System.out.println(averageFood());
}
else if (prompt.equalsIgnoreCase("search"))
{
String searchForID = "";
System.out.println("What lab ID do you want to search for?");
searchForID = keyboard.nextLine();
Gerbil findGerbil = findThatRat(searchForID);
if(findGerbil != null)
{
int integer1 = 0;
int integer2 = 0;
for (int i = 0; i < numGerbils; i++)
{
integer1 = integer1 + foodArray[i].getamtOfFood();
integer2 = integer2 + findGerbil.getGerbFood()[i].getamtOfFood();
}
System.out.println("Gerbil name: " +
findGerbil.getName() + " (" + findGerbil.getBite() + ", " +
findGerbil.getEscape() + ") " +
Integer.toString(integer2) + "/" + Integer.toString(integer1));
}
else
{
System.out.println("error");
}
}
else if (prompt.equalsIgnoreCase("restart"))
{
stop = true;
break;
}
else if(prompt.equalsIgnoreCase("quit"))
{
System.out.println("program is going to quit");
gerbLab = false;
stop = true;
keyboard.close();
}
else
{
System.out.println("error, you did not type average, search, restart or quit");
}
}
}
}
public String averageFood()
{
String averageStuff = "";
double avg = 0;
double num1 = 0;
double num2 = 0;
for (int i = 0; i < numGerbils; i++)
{
averageStuff = averageStuff + gerbilArray[i].getID();
averageStuff = averageStuff + " (";
averageStuff = averageStuff + gerbilArray[i].getName();
averageStuff = averageStuff + ") ";
for (int k = 0; k < foodnum; k++)
{
num1 = num1 + foodArray[k].getamtOfFood();
num2 = num2 + gerbilArray[i].getGerbFood()[k].getamtOfFood();
}
avg = 100*(num2/num1);
avg = Math.round(avg);
averageStuff = averageStuff + Double.toString(avg);
averageStuff = averageStuff + "%\n";
}
return averageStuff;
}
public Gerbil findThatRat (String ID)
{
for(int i = 0; i < numGerbils; i++)
{
if(ID.contentEquals(gerbilArray[i].getID()))
{
return gerbilArray[i];
}
}
return null;
}
}
Whenever a Java program runs, it starts with a method called main. You are getting the error because you don't have such a method. If you write such a method, then what it needs to do is this.
Create an object of the whatTheGerbils class.
Run the gerbLab() method for the object that was created.
The simplest way to do this would be to add the following code inside the whatTheGerbils class.
public static void main(String[] args){
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
You need a main method in your code for it to run, add in something like this
public static void main(String [] args){
gerLab();
}