My code is not printing - java

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++) {

Related

Java programming, look for the connection of a key in the array

/*
* 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:.

LetterCase Count Java

I have to read in a file to my project and then read the file line by line to find the percent of upper case and lower case letters. My output should be 4 lines stating the percent of upper and lower for that specific line in the file. This is what I have to far but it doesn't quite work:
Scanner inFile = new Scanner(new File("file.txt"));
int upper = 0;
int lower = 0;
int total;
double percentU = 0.0;
double percentL = 0.0;
while (inFile.hasNext()) {
String line = inFile.nextLine();
for (int x = 0; x < line.length(); x++)
{
if (Character.isUpperCase(line.charAt(x)))
{
upper++;
}
if (Character.isLowerCase(line.charAt(x)))
{
lower++;
}
total = upper + lower;
percentU = upper/total;
percentL = lower/total;
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
}
}
When you divide an int by another int the result will be also an int. So for example if you divide 30 by 50 the result will be 0 instead of 0.6.
More information:
How to make the division of 2 ints produce a float instead of another int?
Integer division: How do you produce a double?
Division of integers in Java
I Just change these lines removed if (Character.isLowerCase(line.charAt(x))):
if (Character.isUpperCase(line.charAt(x))) {
upper++;
}
if (Character.isLowerCase(line.charAt(x))) {
lower++;
}
To:
if (Character.isUpperCase(line.charAt(x))) {
upper++;
} else {
lower++;
}
And moved these lines out of while loop:
total = upper + lower;
percentU = (float)upper/total;
percentL = (float)lower/total;
System.out.println("total: " + total);
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
Try this solution it's ok:
public static void main(String[] args) {
Scanner inFile = null;
int upper = 0;
int lower = 0;
int total = 0;
double percentU = 0.0;
double percentL = 0.0;
try {
inFile = new Scanner(new File("C:\\temp\\file.txt"));
while (inFile.hasNext()) {
String line = inFile.nextLine();
for (int x = 0; x < line.length(); x++) {
if (Character.isUpperCase(line.charAt(x))) {
upper++;
} else {
lower++;
}
}
}
total = upper + lower;
percentU = (float)upper/total;
percentL = (float)lower/total;
System.out.println("total: " + total);
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

How could i add up the values in each row of the array?

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");

Exception in thread "main" java.lang.NoSuchMethodError: main

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();
}

Need help reading a file in java

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());

Categories

Resources