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();
}
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.
Have a task to get N numbers from console, find the longest and the shortest ones and their length. The task is not difficult and works correctly, but I decided to make a check, if the console input corresponds the conditions of the task:
Are there only Integer numbers.
Are the exactly N numbers, not more/less.
I decided to write a boolean method isInputCorrect(), which would take the Scanner and check if the input is correct, but it doesn't work correctly.
public static void main(String[] args) {
int n = 5;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Hello, please enter " + n + " integer numbers:");
while (!isInputCorrect(sc,n)){
System.out.println("Wrong! Try again:");
sc.next();
}
} while (!isInputCorrect(sc, 5));
String scLine = sc.nextLine();
String[] arr = scLine.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isInputCorrect(Scanner sc, int n){
boolean flag = true;
for (int i = 0; i < n; i++){
if (sc.hasNextInt()){
sc.next();
}else {
flag = false;
break;
}
}
return flag;
}
EDIT
This code still doesn't work. I realize, that the problem is in isDigit(). And exactly in regular conditions in last if statement. It is something like this:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
This method takes the console input as a string, then it checks, how many numbers(strings) does it contain, are there any negative numbers and so on. But it can be applied only for substrings(words without whitespace). In my case it can be applied to arr[i].
So I modified it to split String into array[] and tried to check every single element. I've got:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
but it returnes true even when input is:
1 3213 w 15 3
I can't understand, what is the problem? The full code is:
public static void main(String[] args) {
int n = 5;
boolean validInput = false;
String input;
do {
System.out.println("Please enter " + n + " integer numbers:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
if (isDigit(input, n)) {
validInput = true;
} else {
System.out.println("Wrong input! Try again: ");
}
}
while (!validInput);
String[] arr = input.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
SOLVED
Thanks to everybody, your help was really usefull. I finally found the problem
It was in isDigit() method. It was checking out every element of array, and switched a flag according to the last result. I wrote "break" to stop the further checking if there was at least one false flag in loop.
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else{
for (String s: arr){
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
else {
if (s.matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
}
}
return flag;
}
You may use regular expressions to verify that the input contains only integer numbers:
int n = 5;
// ... your current code
String scLine = sc.nextLine();
if (!scLine.matches("\\d+(?:\\s+\\d+)*")) {
throw new IllegalArgumentException("input contained non-integers");
}
String[] arr = scLine.split("\\s+");
if (arr.length != n) {
throw new IllegalArgumentException("found " + arr.length + " number inputs but expected " + n + ".");
}
you can check if input string has only numbers as below
public boolean isDigit(String input) {
if (input == null || input.length() < 0)
return false;
input = input.trim();
if ("".equals(input))
return false;
if (input.startsWith("-")) {
return input.substring(1).matches("[0-9]*");
} else {
return input.matches("[0-9]*");
}
}
EDIT:
allowing user to re-enter untill valid number is entered
boolean validInput = false;
do
{
System.out.println("Enter the number ");
// get user input
String input sc.nextLine();
if(isDigit(input))
validInput = true;
else
System.out.println("Enter valid Number");
}
while (!validInput );
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");
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();
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++) {