I'm trying to make my code read a file. I can store a file but I'm not sure how to fix the error that I'm receiving to read the file.
Here is my main class:
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[6];
for (int x = 0; x < myHotel.length; x++) {
myHotel[x] = new Room();
}
String roomName = null;
String choice;
String emptyRoom = "empty";
int roomNum = 0;
initialise(myHotel);
while ( roomNum < 6 )
{
System.out.println("V: To View rooms");
System.out.println("A: To Move customer to room");
System.out.println("D: To Remove customer from room");
System.out.println("S: Store data into text file");
System.out.println("L: Read data from file");
choice = input.next();
if (choice.equals("V")) //views all the rooms
{
view(myHotel, roomName);
}
if (choice.equals("A"))
{
System.out.println("Enter room number (0-5) or 6 to stop:" );
roomNum = input.nextInt();
System.out.println("Enter the name for the room " + roomNum + " : " ) ;
roomName = input.next();
myHotel[roomNum].setName(roomName);
add(myHotel, roomName);
System.out.println(" ");
}
if (choice.equals("D"))
{
view(myHotel, roomName);
System.out.println("Enter room you want to remove a customer from: ");
roomNum = input.nextInt();
myHotel[roomNum].setName(emptyRoom);
delete(myHotel, roomName);
System.out.println("");
}
if (choice.equals("S"))
{
store(myHotel);
}
if (choice.equals("L"))
{
System.out.println("");
load(myHotel);
}
}
}
private static void initialise( Room hotelRef[] ) {
for (int x = 0; x < 6; x++ ) hotelRef[x].getName();
System.out.println( "initilise ");
}
public static void view(Room[] myHotel, String roomName){
System.out.println("All the rooms are shown below:");
for (int x = 0; x < 6; x++)
{
System.out.println("room " + x + " occupied by " + myHotel[x].getName());
}
}
private static void add(Room[] myHotel, String roomName){
for (int x = 0; x < 6; x++)
{
System.out.println("room " + x + " is occupied by " + myHotel[x].getName());
}
}
private static void delete(Room[] myHotel, String roomName){
for (int x = 0; x < 6; x++ )
{
System.out.println("room " + x + " occupied by " + myHotel[x].getName());
}
}
private static void store(Room myHotel[]) throws IOException{
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("myhotel.txt"));
for ( int x = 0; x < 6; x++)
{
writer.write(myHotel[x].getName());
writer.newLine();
writer.flush();
}
} catch(IOException ex) {
ex.printStackTrace();
}
System.out.println("You have stored the text file");
System.out.println("");
}
private static void load(Room myHotel[]) throws IOException{
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("myhotel.txt"));
for ( int x = 0; x < 6; x++){
myHotel[x].getName = reader.readLine(); //Receiving error here
}
} catch(IOException ex) {
ex.printStackTrace();
}
System.out.println("You have loaded the text file");
System.out.println("");
}
}
Here is my other class:
public class Room {
private String mainName;
int guestsInRoom;
public Room() {
mainName = "empty ";
System.out.println(" empty rooms ");
}
public void setName(String aName) {
System.out.println("You have moved a customer to a room ");
System.out.println("");
mainName = aName;
}
public String getName() {
return mainName;
}
}
I am not sure how to fix this - myHotel[x].getName = reader.readLine();
I have tried myHotel[x].setName = reader.readLine(); before even asking for help but I still receive the same errors as I do with getName.
I am receiving the error cannot find symbol, Symbol: Variable getName, Location: Room Class
Apologies for any messy coding or variables
I think you meant:
myHotel[x].setName(reader.readLine());
Related
import java.util.*;
public class NFA {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//The number of states
int states;
System.out.println("Enter the number of states:");
states = s.nextInt();
System.out.println("Enter the number of transition states:");
int transitions = s.nextInt();
//current state
int q[][] = new int [states][transitions];
System.out.println("Enter the transitions:");
for(int i=0; i<states; i++) {
System.out.println("State " + (i));
for(int j=0; j<transitions; j++) {
q[i][j] = s.nextInt();
}
}
System.out.println("Type in input:");
String state1;
state1 = s.next();
String in[] = state1.split("");
System.out.println("Transitions:");
System.out.println(" a b");
for(int i=0; i<states; i++) {
System.out.print("State:" + (i) + " ");
for(int j=0; j<transitions; j++) {
System.out.print("q" + q[i][j] + " ");
}
System.out.println("");
}
//Our input
int input[] = new int[in.length];
for(int i=0; i<in.length; i++) {
if(in[i].equals("a")) {
input[i] = 0;
}
if(in[i].equals("b")) {
input[i] = 1;
}
}
System.out.println("____________________________________________________________________________________________________");
int initial = 0;
int finalState = (states-3);
int currentState = initial;
int ip;
int nextState;
for(int i=0; i<in.length; i++) {
System.out.print("q" + currentState + "--" + input[i] + "-->");
ip = input[i];
nextState = q[currentState][ip];
currentState = nextState;
if(i==(in.length-1)) {
System.out.println("q" + currentState);
}
}
if(currentState==finalState) {
System.out.println("Accepted");
}else {
System.out.println("Rejected");
}
}
}
I need to have my program accept multiple final states. I have tried multiple options but can't seem to figure it out.
I tried changing "int finalState = (states-3);" to "int finalState = (states-1);" to see if it changed anything but the issue remains regardless.
I want my program to be flexible in implementing any NFA's.
I am trying to create a hotel database program that has a search function whereby the user can type a name that is staying in the hotel and the program will display the room number for that person. The code below does recognize when the name entered is the same as an existing name in the program, however it also comes up with an error every time:
Exception in thread "main" java.lang.NullPointerException
at hotel.Hotel.findroom(Hotel.java:113)
at hotel.Hotel.main(Hotel.java:51)
Java Result: 1
I have also left question marks '???' in the code at the bottom as I have no idea how to get the program to display the room number of the matching name.
public class Hotel {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String command;
Scanner input = new Scanner(System.in);
String roomName;
int roomNum = 0;
String[] hotel = new String[12];
initialise(hotel);
while ( roomNum < 11 )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter command : ");
command = input.next();
if (command.charAt(0) == 'a') {
addcustomer(hotel);
}
if (command.charAt(0) == 'v') {
viewoccupants(hotel);
}
if (command.charAt(0) == 'e') {
emptyrooms(hotel);
}
if (command.charAt(0) == 'd') {
deleteroom(hotel);
}
if (command.charAt(0) == 'f') {
findroom(hotel);
}
}
}
private static void initialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++ ) hotelRef[x] = "e";
System.out.println( "initilise ");
}
private static void viewoccupants(String[] hotel) {
for (int x = 0; x < 11; x++ )
{
System.out.println("room " + x + " occupied by " + hotel[x]);
}
}
private static void addcustomer(String[] hotel) {
String roomName;
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-10) or 11 to stop:" ) ;
roomNum = input.nextInt();
if (roomNum<11) {
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
else {
System.exit(0);
}
}
private static void emptyrooms(String[] hotel) {
for (int x = 0; x < 11; x++ )
{
if (hotel[x].equals("e"))System.out.println("room " + x + " is empty");
}
}
private static void deleteroom(String[] hotel) {
String x = "e";
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room to be vacated: " );
roomNum = input.nextInt();
if (roomNum<11) {
hotel[roomNum] = x;
}
else {
System.exit(0);
}
}
private static void findroom(String[] hotel) {
String roomName;
Scanner input = new Scanner(System.in);
System.out.println("Enter name: " ) ;
roomName = input.next();
for(int i = 0; i < hotel.length; i++){
if(hotel[i].equals(roomName)){
System.out.println(roomName + " is located in room " + i);
}
}
}
}
I got your problem. you need to declare the String[] hotel or String[] rooms as the global member. The scope of the String[] hotel would have been gone when the function execution is completed if you are using in another function or in main then it will be a different String array. So only you will be getting NPE. So your code should be like below,
public class Hotel {
/**
* #param args the command line arguments
*/
private static String[] hotel= new String[11];
public static void main(String[] args) {
String command;
Scanner input = new Scanner(System.in);
String roomName;
int roomNum = 0;
initialise();
while ( roomNum < 11 )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter command : ");
command = input.next();
if (command.charAt(0) == 'a') {
addcustomer();
}
if (command.charAt(0) == 'v') {
viewoccupants();
}
if (command.charAt(0) == 'e') {
emptyrooms();
}
if (command.charAt(0) == 'd') {
deleteroom();
}
if (command.charAt(0) == 'f') {
findroom();
}
}
}
private static void initialise( ) {
for (int x = 0; x < 11; x++ ) hotel[x] = "e";
System.out.println( "initilise ");
}
private static void viewoccupants() {
for (int x = 0; x < 11; x++ )
{
System.out.println("room " + x + " occupied by " + hotel[x]);
}
}
private static void addcustomer() {
String roomName;
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-10) or 11 to stop:" ) ;
roomNum = input.nextInt();
if (roomNum<11) {
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
else {
System.exit(0);
}
}
private static void emptyrooms() {
for (int x = 0; x < 11; x++ )
{
if (hotel[x].equals("e"))System.out.println("room " + x + " is empty");
}
}
private static void deleteroom() {
String x = "e";
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room to be vacated: " );
roomNum = input.nextInt();
if (roomNum<11) {
hotel[roomNum] = x;
}
else {
System.exit(0);
}
}
private static void findroom() {
String roomName;
Scanner input = new Scanner(System.in);
System.out.println("Enter name: " ) ;
roomName = input.next();
for(int i = 0; i < hotel.length; i++){
if(hotel[i].equals(roomName)){
System.out.println(roomName + " is located in room " + i);
}
}
}
}
Output:
initilise
Enter command : 1
Enter command : a
Enter room number (0-10) or 11 to stop:
1
Enter name for room 1 :
kalai
Enter command : f
Enter name:
kalai
kalai is located in room 1
Enter command :
you also could use lambda in java.
int i = 0;
hotel.asList().forEach(i++ -> s==roomName -> System.out.println(n " is located in room " + i));
You get a null pointer because you didn't initialize the last string inside hotel[]. Either you do that or you swap the object and parameter in function equals inside the loop in the findroom function. (roomname.equals(hotel[i])).
The problem originates because you created an array of 12 elements but then you always cicle index from 0 to 10, that is 11 elements, except in the find function where you cicle through the length of the array, that is 12 elements.
Always use "for(int i = 0; i < hotel.length; i++)" to cicle through your array.
my code (reads a text file, uses a class I built to sort through the data, and then outputs onto console), is not printing anything! Can somebody please tell me where my little mistake is! I know the VERY end is not finished yet. Please help!!!!!!!!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Product> products = new ArrayList<Product>();
// Enter file name
System.out.print("Enter database file name: ");
String fileName = in.nextLine();
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
System.out.println();
while (inputFile.hasNext()) {
Product p = new Product();
String title = inputFile.nextLine();
String code = inputFile.nextLine();
Integer quantity = inputFile.nextInt();
Double price = inputFile.nextDouble();
inputFile.nextLine();
String type = inputFile.nextLine();
Integer userReview = inputFile.nextInt();
// read in title
p.setName(title);
// read in iCode
p.setInventoryCode(code);
// read in quantity
p.setQuantity(quantity);
// read in price
p.setPrice(price);
// read in type
p.setType(type);
// read in user reviews
while (!userReview.equals(-1)) {
p.addUserRating(userReview);
userReview = inputFile.nextInt();
}
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
inputFile.close();
} catch (IOException e) {
System.out.println("There was an error reading from " + fileName);
}
}
private static String highRating(ArrayList<Product> p) {
int highestR = 0;
int indexOfHighestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() > highestR) {
highestR = p.get(i).getAvgUserRating();
indexOfHighestR = i;
}
}
int zero = 0;
String Star = " ";
while (highestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfHighestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static String lowestRating(ArrayList<Product> p) {
int lowestR = 0;
int indexOfLowestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() < lowestR) {
lowestR = p.get(i).getAvgUserRating();
indexOfLowestR = i;
}
}
int zero = 0;
String Star = " ";
while (lowestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfLowestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static double maxDollar(ArrayList<Product> p) {
double largestP = 0;
int indexOfLargestP = 0;
for (int i = 0; i < p.size(); i++) {
double price = p.get(i).getPrice();
if (p.get(i).getPrice() > largestP) {
largestP = p.get(i).getPrice();
indexOfLargestP = i;
}
}
return largestP;
}
private static int minDollar(ArrayList<Product> p) {
double smallestP = p.get(0).getPrice();
int indexOfSmallestP = 0;
for (int i = 0; i < p.size(); i++) {
if (p.get(i).getPrice() < smallestP) {
smallestP = p.get(i).getPrice();
indexOfSmallestP = i;
}
}
return indexOfSmallestP;
}
private static void inventoryList(ArrayList<Product> p) {
int count =
System.out.println("Product Summary Report: ");
System.out
.println("------------------------------------------------------------");
for (int i = 0; i < count; i++) {
System.out.println("Title: " + p.get(i).getName());
System.out.println("I Code: " + p.get(i).getInventoryCode());
System.out.println("Product Type: " + p.get(i).getType());
System.out.println("Rating: " + p.get(i).getAvgUserRating());
System.out.println("# Rat.: " + p.get(i).getUserRatingCount());
System.out.println("Quantity: " + p.get(i).getQuantity());
System.out.println("Price: " + p.get(i).getPrice());
System.out.println();
}
System.out
.println("-----------------------------------------------------------------");
// System.out.println("Total products in database: " + count);
System.out.println("Highest total dollar item: "
+ p.get(maxDollar(p)) + " ($"+ p.(maxDollar(p)) + ")");
System.out.println("Smallest quantity item: "
+ p.get(minQuantity(quantities)) + " ("
+ types.get(minQuantity(quantities)) + ")");
System.out.println("Lowest total dollar item: "
+ titles.get(minDollar(prices)) + " ($"
+ prices.get(minDollar(prices)) + ")");
System.out
.println("-----------------------------------------------------------------");
}
First...
After you've create an instance of Product, p, you will need to add it to the products list, otherwise you will lose it's reference and won't be able to use it again...
while (inputFile.hasNext()) {
Product p = new Product();
//...
products.add(p);
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
Second...
You will need to pass the products List to something that want's to use/display the information, for example inventoryList...
But wait, that's not working?
If we take a closer look at the the inventoryList method...
int count = 0;
//...
for (int i = 0; i < count; i++) {
We can see that count is always 0, so it will never print anything! You should be using p.size() instead, which is the actually length of the products List
//...
for (int i = 0; i < p.size(); i++) {
I am creating a program which acts as a translator for given words. I have created a text file with the data I am using, reading that into a 2D array (English in column 0, translation in column 1, 16 rows in total). I prompt the user to enter a string and pass that string, the 2D, and a blank String to hold the translation to my translation method (named: turnKlingon). I am using the String tokenizer to pick out specific words. My problem is that I cannot figure out how to search my 2D array in column 0 for the English and only print the column 1 translated word.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
System.out.println("Klingon Translator");
System.out.println();
System.out.println();
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
String Klingon = " ";
turnKlingon(Klingon, userString, translate);
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated to Klingon: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String Klingon, String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println("Number of Tokens: "+ numberOfWords);
int counter = 1;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
System.out.print(s2 + "_"); //string tokenizer
for(int r = 0; r < translate.length; r++)
{
for(int c = 0; c < translate[r].length; c++)
{
if (translate[r][c].compareTo(s2) == 0)
{
translate[0] = translate[1];
}
}
System.out.println(translate[0] + "," + translate[1]);
counter++; //string tokenizer
}//end while
}
}
}
After messing around with this code for a few hours I finally managed to solve my own problem. I also added a while true loop in the main method to allow the user to translating multiple times as well as an option to translate to another language (German) though I have omitted that method from this reply.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
Scanner input = new Scanner(System.in);
System.out.println("English to Klingon/German Translator");
System.out.println();
System.out.println();
while (true)
{
int again = 999;
int language = 999;
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
System.out.println("Would you like to translate to Klingon or German? \n Press 1 for Klingon: \n Press 2 for German: ");
language = input.nextInt();
if (language == 1)
{
turnKlingon(userString, translate);
}
else if (language == 2)
{
turnGerman(userString, translate);
}
else
{
System.out.println("Invalid input");
}
System.out.println();
System.out.println();
System.out.println("Would you like to translate another sentence? \n Press 1 for yes or 0 for no: ");
again = input.nextInt();
if (again == 0)
{
System.out.println("Goodbye!");
break;
}
else if (again == 1)
{
continue;
}
}
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println();
System.out.println("Any words that cannot be directly \n translated will remain in English");
System.out.println("____________________________________");
System.out.println();
System.out.print("Translation: ");
int counter = 1;
boolean found = false;
int translateCounter = 0;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
//string tokenizer
for(int r = 0; r < 16; r++)
{
for(int c = 0; c < 18; c++)
{
found = false;
if (translateCounter == 16)
{
System.out.print(s2+ " ");
translateCounter = 0;
break;
}
else if (translate[r][0].compareTo(s2) == 0)
{
found = true;
}
else if (translate[r][0].compareTo(s2) != 0)
{
found = false;
r++;
c = -1;;
translateCounter++;
continue;
}
if (found == true)
{
System.out.print(translate[r][1]+ " ");
translateCounter = 0;
c = -1;
r = -1;
break;
}
}
counter++;//string tokenizer
break;
}//end while
}
}
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();
}