class airlne {
static String seatsArray[][] = new String[30][6];
static String columnLetter[] = {"A", "B", "C", "D", "E", "F"};
static String passName[][] = new String[30][6];
static String name;
static int count;
static double cost;
static String reservedSeat;
static int i, j;
public static void main(String[] args) { //main
String pickedSeat = new String("");
System.out.println("\n********************* Welcome To The Fair Airlines **********************");
System.out.println("********************* **********************");
System.out.println("********************* Please Book *********************");
System.out.println("********************* Your Seat **********************");
System.out.println("********************* **********************");
System.out.println("********************* \1\2\3\4\5\6 **********************");
createSeatingArrangment();
String option = "m";
while (!option.equals("exit")) {
printMenu();
option = Keyboard.readString();
switch (option) { //switch for menu
case ("1"):
showSeatMap();
bookSeat(pickedSeat);
break;
case ("2"):
cancelSeat(pickedSeat);
break;
case ("3"):
seatsRemaining();
break;
case ("4"):
showSeatMap();
break;
case ("5"):
ticketCost();
break;
case ("6"):
printTicket();
break;
case ("exit"):
System.out.println("Thank you. Goodbye");
System.exit(0);
break;
default:
System.out.println("Invalid option");
break;
}
}
}
static void createSeatingArrangment() {
for (i = 0; i < 30; i++) {
for (j = 0; j < 6; j++) {
seatsArray[i][j] = new String((i + 1) + columnLetter[j]);
}
}
}
public static void printMenu() { //just prints menu
System.out.println("Please select an option below:\n"
+ "[1] Book your seat \n"
+ "[2] Cancel your seat \n"
+ "[3] Check how many seats are remaining \n"
+ "[4] See our seats \n"
+ "[5] Show seat cost\n"
+ "[6] Print Ticket"
+ "\nEnter \'exit\' to exit");
}
static void showSeatMap() { // goes through arr and prints
for (i = 0; i < 30; i++) {
for (j = 0; j < 6; j++) {
System.out.print(seatsArray[i][j] + "\t");
}
System.out.println("\4");
}
}
static void ticketCost() {
count = 0;
for (i = 0; i < 30; i++) {
for (j = 0; j < 6; j++) {
if (seatsArray[i][j].equals("X")) {
count++;
}
}
}
double splendidum = 0;
splendidum = 180 - count;
cost = 150 + (180 / splendidum);
System.out.println(" ******* Your ticket will cost " + cost + " ******* ");
}
static void bookSeat(String pickSeatIn) { //booking seat method
System.out.print("Enter Seat Details: ");
pickSeatIn = Keyboard.readString();
if (isSeatAvailable(pickSeatIn)) {
System.out.println("Enter name");
passName[i][j] = Keyboard.readString();
System.out.println("Reservation Confirmed!");
System.out.println("Dear " + passName[i][j] + " Thanks for booking with us!");
System.out.println(pickSeatIn + " is now reserved");
reservedSeat = pickSeatIn;
System.out.println("");
ticketCost();
}
else {
System.out.println("This seat is taken!");
bookSeat(pickSeatIn);
}
}
static void cancelSeat(String pickSeatIn) {
System.out.print("Enter Seat Reservation: ");
pickSeatIn = Keyboard.readString();
if (toCancel(pickSeatIn)) {
System.out.println(passName[i][j] + " your seat will be cancelled.");
}
else {
System.out.println("This is not your seat");
}
System.out.println("Enter name");
passName[i][j] = Keyboard.readString();
if (!passName[i][j].equalsIgnoreCase(passName[i][j])) {
System.out.println("wrong name");
}
showSeatMap();
}
static void printTicket() {
System.out.println("Enter name");
name = Keyboard.readString();
System.out.println("Name: " + name);
System.out.println("Seat Allocation: " + reservedSeat);
System.out.println("Price:" + cost);
}
static boolean isSeatAvailable(String pickSeatIn) {
for (i = 0; i < 30; i++) {
for (j = 0; j < 6; j++) {
if ((seatsArray[i][j]).equalsIgnoreCase(pickSeatIn)) {
seatsArray[i][j] = "X";
return true;
}
}
}
return false;
}
static boolean toCancel(String pickSeatIn) {
for (i = 0; i < 30; i++) {
for (j = 0; j < 6; j++) {
if ((seatsArray[i][j]).equalsIgnoreCase("X")) {
seatsArray[i][j] = pickSeatIn.toUpperCase();
return true;
}
}
}
return false;
}
static void seatsRemaining() {
count = 0;
for (i = 0; i < 30; i++) {
for (j = 0; j < 6; j++) {
if (seatsArray[i][j].equals("X")) {
count++;
}
}
}
System.out.println("seats remaining =" + (180 - count));
}
}
Where the keyboard.nextString() is it says it cant find the symbol anybody know whats wrong or how to fix this ? I know it will be a pretty easy error to fix but I just cant crack it
It seems you are missing an import. Have you declared a Keyboard class somewhere? If so, import it. Otherwise, have a look at Scanner:
Scanner sc = new Scanner(System.in);
String input = sc.next();
Related
I am making a program which allows the user to look at student's grades, find the average, find the highest grade, the lowest etc. For one of the methods I have, it checks for the average of the values that the user entered. I tried to do this but to no avail. Here is the specific code:
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
For some better context, here is the rest of the code:
import java.util.Scanner;
public class StudentGradeArray {
static Scanner input = new Scanner(System.in);
static String[] studentName;
static String letterGrade = " ";
static int[] studentGrade;
static int gradeMax = 0;
static int gradeMin = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("How many students are you entering into the database?");
int numOfKids = input.nextInt();
studentGrade = new int[numOfKids];
studentName = new String[numOfKids];
for (int i = 0; i < numOfKids; i++) {
System.out.println("Enter the student's name:");
studentName[i] = input.next();
System.out.println("Enter " + studentName[i] + "'s grade");
studentGrade[i] = input.nextInt();
}
do {
System.out.println("");
System.out.println("Enter a number for the following options:");
System.out.println("");
System.out.println("1. Student's letter grade");
System.out.println("2. Search for a student and their grade");
System.out.println("3. The class average");
System.out.println("4. The student with the highest grade");
System.out.println("5. The student with the lowest grade");
System.out.println("6. List of students that are failing");
System.out.println("7. Quit the program");
int options = input.nextInt();
switch(options) {
case 1:
letterGrade(options); break;
case 2:
searchStudent(); break;
case 3:
classAvg(options); break;
case 4:
markHighest(options); break;
case 5:
markLowest(options); break;
case 6:
markFailing(options); break;
case 7:
return;
default:
System.out.println("");
System.out.println("Please enter a valid option.");
System.out.println(""); break;
}
} while (!input.equals(7));
System.out.println("Program Terminated.");
}
public static void letterGrade(int numOfKids) {
System.out.println("Enter a grade: A, B, C, D, F");
letterGrade = input.next();
if (letterGrade.equalsIgnoreCase("a")) {
gradeMax = 100;
gradeMin = 80;
}
if (letterGrade.equalsIgnoreCase("b")) {
gradeMax = 79;
gradeMin = 70;
}
if (letterGrade.equalsIgnoreCase("c")) {
gradeMax = 69;
gradeMin = 60;
}
if (letterGrade.equalsIgnoreCase("d")) {
gradeMax = 59;
gradeMin = 50;
}
if (letterGrade.equalsIgnoreCase("f")) {
gradeMax = 49;
gradeMin = 0;
}
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] <= gradeMax && studentGrade[i] >= gradeMin) {
System.out.println(studentName[i] + " has a " + letterGrade);
System.out.println(letterGrade + " is equivalent to " + gradeMin + " - " + gradeMax + "%");
}
}
}
public static void searchStudent() {
}
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
public static void markHighest(int numOfKids) {
int highestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] > highestNum) {
highestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + highestNum + "%");
}
public static void markLowest(int numOfKids) {
int lowestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < lowestNum) {
lowestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + lowestNum + "%");
}
public static void markFailing(int numOfKids) {
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < 50) {
System.out.println(studentName[i] + " is failing with a mark of " + studentGrade[i] + "%");
}
}
}
}
Looks like the argument passed to the classAvg() is not the numOfKids (or size of array) but the option selected by the user from the menu. Trying passing 'numOfKids' instead of passing 'options' as an argument to the function
case 3:
classAvg(options); break;
Better still use studentGrade.length instead of passing argument.
case 3:
classAvg(options); break;
You are passing in the options, but the method wants numOfKids. In this case options will always be 3.
Try passing in numOfKids instead.
Another problem I see is that both average and numOfKids are integers, which causes chopping remainders and rounding to 0 if the denominator is greater. Perhaps change from
average = (average/numOfKids) * 100;
to
average = ((double) average)/ numOfKids * 100;
I think it is better to create a class called Student, with properties name and grade. for more OOP design.
public class Student{
int[] grades;
String name;
public Student(int[] grade, String name){
this.grade = grade;
this.name = name;
}
public double getAverage(){
return (average/(double)numOfKids) * 100;
}
...
}
And average is of type int and numOfKids too, so the division is not gonna be precise. try this average = (average/(double)numOfKids) * 100;
/*
* 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:.
I want to overwrite the first element of my transaction array when it gets full. So when I print the array, it is always showing the latest transactions.
I think the problem is in the moveTrans method or the findNr method but I'm not sure and I can't figure out what is wrong.
Code:
import java.util.Scanner;
import java.util.*;
public class BankoTest {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int amount = 0;
int choice = 0;
int [] trans = new int[4];
int sum;
int balance = 0;
while (choice != 4)
{
choice = menu();
switch(choice)
{
case 1://
System.out.print("Deposit. Amount? :");
amount = scan.nextInt();
balance = balance + amount;
makeTransactions(trans, amount);
break;
case 2://
System.out.print("Withdra. Amount?");
amount = scan.nextInt();
balance = balance - amount;
makeTransactions(trans, -amount);
break;
case 3:
showTransactions(trans, balance);
break;
case 4:
System.out.println("Thank you. ");
break;
}
}
}
public static int menu()
{
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Saldo ");
System.out.println("4. End ");
System.out.println();
System.out.println("Choice: ");
choice = scan.nextInt();
return choice;
}
public static void showTransactions(int [] trans, int balance)
{
System.out.println();
System.out.println("Transactions summary :");
System.out.println();
for(int i = 0; i < trans.length-1; i++)
{
if(trans[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(trans[i] + "\n");
balance = balance + trans[i];
}
}
// Printing saldo.
System.out.println();
System.out.println("Current balance: " + balance + " kr" + "\n" );
System.out.println();
}
//Puts amount last among the transactions that are stored in the array. Using the findNr method to find the first available spot
//in the array. moveTrans is used to make room for the new transaction when the array is full.
public static void makeTransactions(int [] trans, int amount )
{
int position = findNr(trans);
if(position == -1)
{
moveTrans(trans);
position = findNr(trans);
trans[position] = amount;
}
else
{
trans[position] = amount;
}
}
public static int findNr(int [] trans)
{
int position = -1;
for(int i = 0; i <= trans.length-1; i++)
{
if(trans[i] == 0)
{
position = i;
break;
}
}
return position;
}
public static void moveTrans(int [] trans)
{
for(int i = 0; i < trans.length-1; i++)
trans[0] = trans[i + 1] ;
}
}
just modify the following method alone
public static void makeTransactions(int[] trans, int amount) {
int position = findNr(trans);
if (position == -1) {
moveTrans(trans);
position = findNr(trans);
trans[position] = amount;
} else {
if (position != 0 && position == trans.length - 1) {
// shift the elements back
for (int i = 0; i < position; i++)
trans[i] = trans[i] + 1;
trans[position - 1] = amount;
}else
trans[position] = amount;
}
}
Please check this it may help some thing to you
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int choice = 0;
int[] trans = new int[4];
int sum;
int balance = 0;
while (choice != 4) {
choice = menu();
switch (choice) {
case 1://
System.out.print("Deposit. Amount? :");
amount = scan.nextInt();
balance = balance + amount;
makeTransactions(trans, amount);
break;
case 2://
System.out.print("Withdra. Amount?");
amount = scan.nextInt();
balance = balance - amount;
makeTransactions(trans, -amount);
break;
case 3:
showTransactions(trans, balance);
break;
case 4:
System.out.println("Thank you. ");
break;
}
}
}
public static int menu() {
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Saldo ");
System.out.println("4. End ");
System.out.println();
System.out.println("Choice: ");
choice = scan.nextInt();
return choice;
}
public static void showTransactions(int[] trans, int balance) {
System.out.println();
System.out.println("Transactions summary :");
System.out.println();
for (int i = 0; i < trans.length - 1; i++) {
if (trans[i] == 0) {
System.out.print("");
}
else {
System.out.print(trans[i] + "\n");
// balance = trans[i];
}
}
// Printing saldo.
System.out.println();
System.out.println("Current balance: " + balance + " INR" + "\n");
System.out.println();
}
// Puts amount last among the transactions that are stored in the array.
// Using the findNr method to find the first available spot
// in the array. moveTrans is used to make room for the new transaction when
// the array is full.
public static void makeTransactions(int[] trans, int amount) {
int position = findNr(trans);
if (position == -1) {
moveTrans(trans);
System.out.println("Your transaction limit is over.");
// position = findNr(trans);
// System.out.println("Position -------> "+position);
// trans[position] = amount;
} else {
trans[position] = amount;
}
}
public static int findNr(int[] trans) {
int position = -1;
for (int i = 0; i <= trans.length - 1; i++) {
if (trans[i] == 0) {
position = i;
break;
}
}
return position;
}
public static void moveTrans(int[] trans) {
System.out.println("------Your Transaction Details----------");
for (int i = 0; i < trans.length; i++) {
System.out.println("Transation " + (i + 1) + " :: " + trans[i]);
trans[0] = trans[i];
}
System.out.println("----------------------------------------");
}
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");
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();
}