I am new to CS and I am doing this online java class which is a joke tbh. I say that because the books we got are $15 books, custom made that were used for a summer camp that was "taught" to kids. There is no where in the book that has actual java information, it is just a bunch of programs. I did a bit of searching around and I can't seem to find what I am looking for.
One thing we have to do is modify the program so it can display first and last name. I have looked and seen that you can do two strings to get first and last name. Is there something that will get the entire line in java?
package computegrades;
import java.util.Scanner;
public class ComputeGrades {
public static void main (String[] args) {
String[] names = getNames();
int[] scores = getScores(names);
double average = computeAverage(scores);
int highestIndex = getHighest(scores);
int lowestIndex = getLowest(scores);
System.out.format("Average = %3.2f\n", average);
System.out.println("Highest = " + names[highestIndex] + ": " + scores [highestIndex]);
System.out.println("Lowest = " + names[lowestIndex] + ": " + scores [lowestIndex]);
printLetterGrades(names, scores);
}
public static void printLetterGrades(String[] names, int[] scores) {
for (int i = 0; i < names.length; i++) {
if (scores[i] >= 90) {
System.out.println(names[i] + ": A");
} else if (scores[i] >= 80) {
System.out.println(names[i] + ": B");
} else if (scores[i] >= 70) {
System.out.println(names[i] + ": C");
} else if (scores[i] >= 60) {
System.out.println(names[i] + ": D");
} else {
System.out.println(names[i] + ": F");
}
}
}
public static String[] getNames() {
Scanner input = new Scanner(System.in);
System.out.println("How many students?");
int n = input.nextInt();
System.out.println("Please enter their first names:");
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.print("name " + (i + 1) + ": ");
names[i] = input.next();
}
System.out.println("Thank you.");
return names;
}
public static int[] getScores(String[] names) {
System.out.println("Now, please enter their scores:");
Scanner input = new Scanner(System.in);
int[] scores = new int[names.length];
for (int i = 0; i < names.length; i++) {
System.out.print(names[i] + "'s ");
System.out.print("score: ");
while(!input.hasNextInt()){
input.next();
System.out.println("Please enter an integer for the score");
System.out.print("scores: ");
}
scores[i] = input.nextInt();
}
return scores;
}
public static double computeAverage(int[] scores) {
double sum = 0;
for (int i = 0; i < scores.length; i++) {
sum += scores[i];
}
return sum / scores.length;
}
public static int getHighest(int[] scores) {
int highestIndex = Integer.MIN_VALUE;
int highestScore = Integer.MIN_VALUE;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > highestScore) {
highestScore = scores[i];
highestIndex = i;
}
}
return highestIndex;
}
public static int getLowest(int[] scores) {
int lowestIndex = Integer.MAX_VALUE;
int lowestScore = Integer.MAX_VALUE;
for (int i = 0; i < scores.length; i++) {
if (scores[i] < lowestScore) {
lowestScore = scores[i];
lowestIndex = i;
}
}
return lowestIndex;
}
}
Being new to Java, one of the resources you need to have on hand is the Oracle documentation pages, for example:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
That will guide you on what a Scanner can do.
Specifically, you should look for
.nextLine()
Related
I'm trying to simplify this Java code by adding arrays, but I'm having difficulty.
The code that I have so far that works:
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
char number0 = '0';
char number1 = '1';
char number2 = '2';
char number3 = '3';
char number4 = '4';
char number5 = '5';
char number6 = '6';
char number7 = '7';
char number8 = '8';
char number9 = '9';
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == number0) {
count0++;
}
else if (line.charAt(i) == number1) {
count1++;
}
else if (line.charAt(i) == number2) {
count2++;
}
else if (line.charAt(i) == number3) {
count3++;
}
else if (line.charAt(i) == number4) {
count4++;
}
else if (line.charAt(i) == number5) {
count5++;
}
else if (line.charAt(i) == number6) {
count6++;
}
else if (line.charAt(i) == number7) {
count7++;
}
else if (line.charAt(i) == number8) {
count8++;
}
else if (line.charAt(i) == number9) {
count9++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
System.out.println(" 0 " + count0);
System.out.println(" 1 " + count1);
System.out.println(" 2 " + count2);
System.out.println(" 3 " + count3);
System.out.println(" 4 " + count4);
System.out.println(" 5 " + count5);
System.out.println(" 6 " + count6);
System.out.println(" 7 " + count7);
System.out.println(" 8 " + count8);
System.out.println(" 9 " + count9);
System.out.println(" -----------");
}
}
}
However, it's kind of a brute-force attack. The spot of difficulty I'm running into is figuring out where to create and pass arrays. Since the code has to read the external file, should the arrays be created and passed in the while statement?
For further reference, the text file that is being read looks like this:
Thistle Map
The goal is to count the occurrences of digits only.
As you stated, you could use arrays.
I would suggest 2 arrays
One to hold the digits to catch
Second one for the counts
Initialization of the arrays
char[] numbers = new char[10];
//initialize of numbers(char) to count
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (char) ('0' + i);
}
int[] counts = new int[10]; //no initialization needed because int is default 0
In the for-loop where you iterate over the line, add a nested for loop, that iterates over the numbers-array. Here is the whole while loop:
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
for(int j = 0; j < numbers.length; j++) {
if(line.charAt(i) == numbers[j]) {
counts[j]++;
}
}
}
}
For the output just use another for over the arrays:
for(int i = 0; i < numbers.length; i++) {
System.out.println(" "+ numbers[i] +" " + counts[i]);
}
Edit: Another solution using a Map
//...
Map<Character, Integer> charCounts = new HashMap<>();
for (int i = 0; i < 10; i++) {
charCounts.put((char) ('0' + i), 0);
}
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
charCounts.computeIfPresent(line.charAt(i), (key, val) -> val + 1);
}
}
//...
for (Character number : charCounts.keySet()) {
System.out.println(" " + number + " " + charCounts.get(number));
}
With this solution you can easily extend your program to count any occuring character. Just remove the initialization of the map and add this line below the computeIfPresent.
charCounts.putIfAbsent(line.charAt(i), 1);
With Java 8 you can use Files.lines to get a Stream of all the lines in a file.
Then you can transform the stream to a stream over every char using flatMap and in the end collect it to a map that has the Character as key and the count of the character as value.
try (Stream<String> stream = Files.lines(Paths.get(fileName)) {
Map<Character, Long> charCountMap = stream
.flatMap(line -> line.chars().mapToObj(c -> (char) c))
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(" 0 " + charCountMap.getOrDefault('0', 0));
} catch (IOException e) {
e.printStackTrace();
}
Probably the way I would do it in a real world scenario, because it's short, but just for practice the other answers are better.
Yes. I would say it can be simplified a great deal with an array. You don't need seperate sentinels for the values, you can check they are in range and then use Character.digit to parse them. Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) >= '0' && line.charAt(i) <= '9') {
count[Character.digit(line.charAt(i), 10)]++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < count.length; i++) {
System.out.printf(" %d %d%n", i, count[i]);
}
System.out.println(" -----------");
}
You can use a single array for this and index notation. Each array index should hold the quantity of digits. Much more clear.
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
try {
int c = Character.getNumericValue(line.charAt(i));
count[c] += 1;
} catch (Exception e) { }
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < 10; i++)
System.out.println(" " + i + " " + count[i]);
System.out.println(" -----------");
}
}
}
I am working through a coding assignment and am close to completion save for my final print statement which needs to match names w/ scores for max and min.
I have been able to get appropriate values in two sentences using two if statements, but I am a bit stumped on how to get my indexing correct to align names to scores w/ max and min.
I am not able to use classes or additional / different methods other than arrays and indexing.
//Create method StudentMax
private static int StudentMax(int[] Scores) {
int ScoreMax = Scores[0];
for (int i = 0; i < Scores.length; i++){
if (Scores[i] > ScoreMax){
ScoreMax = Scores[i];
}
}
return ScoreMax;
}
//Create method StudentMin
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
}
}
return ScoreMin;
}
public static void main(String[] args) {
//Call Scanner
Scanner scan = new Scanner(System.in);
//User Welcome
System.out.println("Welcome to the student score sorter.");
System.out.println("\nThis program will accept a number of student names and score values, then find the highest and lowest score.");
System.out.println("\nThen will return the names and max/min scores.");
//User Prompt Enter number of students
System.out.println("\nHow many students would you like to enter: ");
int StudentCount = scan.nextInt();
//Create arrays: Scores, StudentFirst, StudentLast
int [] Scores = new int[StudentCount];
String [] StudentFirst = new String [StudentCount];
String [] StudentLast = new String [StudentCount];
for (int i = 0; i < Scores.length; i++) {
System.out.println("\nStudent " + (i+1)+":");
System.out.println("\nEnter Student's name:");
StudentFirst[i] = scan.next();
StudentLast[i] = scan.next();
System.out.println("\nEnter Student's score (0-100):");
Scores[i] = scan.nextInt();
}
int max = StudentMax(Scores);
int min = StudentMin(Scores);
for (int i = 0; i < Scores.length; i++) {
System.out.println("\n"+StudentFirst[i] + " " + StudentLast[i] +": " + Scores[i]);
}
for (int i = 0; i < Scores.length; i++) {
if (Scores [i] == max) {
System.out.println("\n"+ StudentFirst[i] +" "+ StudentLast[i] + " has the highest score => " +max+ " and " + StudentFirst[i]+" " + StudentLast[i]+ " has the lowest => " +min);
}
}
//This is the sentence format that I need to make work, but I am struggling to understand how to align the index for names and scores.
//System.out.println("\n"+StudentFirst[i] +" "+ StudentLast[i]+ " has the highest score => " +max+ " and " +StudentFirst[i] +" "+ StudentLast [i]+ " has the lowest score => " +min);
//Scan Close
scan.close();
//Close Program
}
}
Pass back the index not the value
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
int index = 0;
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
index = i;
}
}
return index;
}
Then you can use it later
int index = StudentMax(Scores);
System.out.println("\n"+ StudentFirst[index] +" "+ StudentLast[index] + " has the highest score => " +Scored[index]);
Note Please pay attention to Java naming conventions
I'm writing code for class, and the code works fine when I run it in Dr. Java in class. However when I input it for grading, I get an error that reads:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:247)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
I have no idea what this means, we haven't covered this sort of thing and I am not a very experienced programmer, sorry. My code is as follows;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int indexFirst = 0;
int indexSecond = 0;
int[] first = new int[10000];
int[] second = new int[10000];
System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
do {int value = scanner.nextInt();
if (value < 0) {
break;
}
first[indexFirst++] = value;
} while(true);
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
do {int value = scanner.nextInt();
if (value <= 0) {
break;
}
second[indexSecond++] = value;
} while(true);
System.out.println("First Array:");
for (int i = 0; i < indexFirst; i++) {
System.out.print(first[i] + " ");
}
System.out.println("\n");
System.out.println("Second Array:");
for (int i = 0; i < indexSecond; i++) {
System.out.print(second[i] + " ");
}
System.out.println("\n");
for (int i = 1; i < indexFirst; i++) {
if (first[i-1] > first[i] ) {
System.out.println("ERROR: Array not in correct order");
return;
}
}
for (int i = 1; i < indexSecond; i++) {
if (second[i-1] > second[i] ) {
System.out.println("ERROR: Array not in correct order");
return;
}
}
int[] merged = new int[indexFirst + indexSecond];
int curIdx1 = 0;
int curIdx2 = 0;
for(int mergedIdx = 0; mergedIdx < merged.length; mergedIdx++) {
if (curIdx2 == indexSecond) {
merged[mergedIdx] = first[curIdx1++];
} else if (curIdx1 == indexFirst) {
merged[mergedIdx] = second[curIdx2++];
} else if (first[curIdx1] < second[curIdx2]) {
merged[mergedIdx] = first[curIdx1++];
} else {
merged[mergedIdx] = second[curIdx2++];
}
}
System.out.println("Merged Array:");
for (int i = 0; i < merged.length; i++) {
System.out.print(merged[i] + " ");
}
}
}
If anyone has any input on how to fix this, it would be much appreciated.
import java.util.Scanner;
public class scores
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("\f");
int classSize, counterScore, counterName;
String name;
double score,average, sum;
System.out.print("Enter size of class: ");
classSize = input.nextInt();
int[] scoreArray = new int[classSize];
String[] nameArray = new String[classSize];
counterScore=1;
counterName = 1;
average = 0;
sum = 0;
for (int x = 0; x < classSize; x++)
{
input.nextLine();
System.out.print("Student " + counterName++ + " Name: ");
nameArray[x] = input.nextLine();
System.out.print("Student " + counterScore++ + " Score: ");
scoreArray[x] = input.nextInt();
sum = sum + scoreArray[x];
average = sum / classSize;
}
System.out.println(average);
}
}
I have to make an app that allows me to say how many people took a test and then enter their names and scores. I have used two different arrays as one is a string and one a double. My output is meant to read which names got under the average and display the name. I do not know how to combine the two arrays so that it recognizes that this score is related to this name so display that name.
I think your best option is to create a POJO with two fields (name and score) and create an array of it:
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
You can simply iterate through the two arrays together in a single iteration and populate an array of the custom type containing a String and double. (i.e. a Student class)
public class Student {
public String name;
public double score;
public Student(String name, double score) {
this.name = name;
this.score = score;
}
}
List<Student> students = new ArrayList<Student>();
for (int x = 0; x < classSize; x++)
{
input.nextLine();
System.out.print("Student " + counterName++ + " Name: ");
nameArray[x] = input.nextLine();
System.out.print("Student " + counterScore++ + " Score: ");
scoreArray[x] = input.nextInt();
sum = sum + scoreArray[x];
average = sum / classSize;
// populate array of student
students.add(new Student(nameArray[x], scoreArray[x]));
}
Note that in this case, you don't need to have the scoreArray and nameArray anymore for better memory utilization.
You can use (add this after your first loop):
for (int i = 0; i < classSize; i++)
{
if(scoreArray[i] < average) {
System.out.println(nameArray[i])
}
}
Or if you want it all on one line:
System.out.println("The following students are below average: ")
boolean first = true;
for (int i = 0; i < classSize; i++)
{
if(scoreArray[i] < average) {
if(!first) {
System.out.println(", ");
first = false;
}
System.out.print(nameArray[i])
}
}
Also, you should move the line average = sum / classSize; outside of your loop, there's no point in re-calculating the average each time.
To find out the highest value, keep a temporary variable for the name and another for the highest value, and loop through the students:
String highestName = "";
double highestValue = 0;
for (int i = 0; i < classSize; i++) {
if(scoreArray[i] > highestValue) {
highestName = nameArray[i];
highestValue = scoreArray[i];
}
}
System.out.println(highestName + " has the highest grade.")
Or use this to print more than one student if there's a tie:
String[] highestNames = new String[classSize];
int numHighest = 0;
double highestValue = 0;
for (int i = 0; i < classSize; i++) {
if(scoreArray[i] > highestValue) {
highestNames[0] = nameArray[i];
numHighest = 1;
highestValue = scoreArray[i];
} else if(scoreArray[i] > highestValue) {
highestNames[numHighest] = nameArray[i];
numHighest = numHighest + 1;
}
}
System.out.println("The following student(s) has/have the highest grade: ")
boolean first2 = true;
for (int i = 0; i < numHighest; i++)
{
if(!first2) {
System.out.println(", ");
first2 = false;
}
System.out.print(highestNames[i])
}
}
You can also combine the content of the loop for printing students with grades below average with the one for finding the highest grades to make your program more efficient:
String[] highestNames = new String[classSize];
int numHighest = 0;
double highestValue = 0;
System.out.println("The following students are below average: ")
boolean first = true;
for (int i = 0; i < classSize; i++)
{
if(scoreArray[i] < average) {
if(!first) {
System.out.println(", ");
first = false;
}
System.out.print(nameArray[i])
}
if(scoreArray[i] > highestValue) {
highestNames[0] = nameArray[i];
numHighest = 1;
highestValue = scoreArray[i];
} else if(scoreArray[i] > highestValue) {
highestNames[numHighest] = nameArray[i];
numHighest = numHighest + 1;
}
}
So my code works completely; the only thing now is a very simple problem that I cannot figure out. I have to make the program loop back to the beginning if the user type restart and I cannot think how to that.
import java.util.Scanner;
public class MutantGerbil {
public static String []foodName;
public static int [] maxAmount;
public static Gerbil [] gerbilAttributes;
public static int [] consumption;
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
String userInput1 = keyboard.nextLine();
int food = Integer.parseInt(userInput1);
foodName = new String[food]; //array of food names
maxAmount = new int[food]; // array of max amount of food given everyday
for (int i = 0; i < food; i++){
System.out.println("Name of food item" + (i+1) +": " );
String foodType = keyboard.nextLine();
foodName[i] = foodType;
System.out.println("Maximum consumed per gerbil: ");
String consumption = keyboard.nextLine();
int consumption2 = Integer.parseInt(consumption);
maxAmount [i] = consumption2;
}
System.out.println("How many gerbils are in the lab?");
String userInput2 = keyboard.nextLine();
int numberOfGerbils = Integer.parseInt(userInput2);
gerbilAttributes = new Gerbil [numberOfGerbils];// Array with the gerbil attributes
for (int i = 0; i < numberOfGerbils; i++)
{
consumption = new int[food]; // Array with amount of the food the gerbil eat each day
System.out.println("Gerbil" + (i+1) + "'s" + "lab ID: ");
String gerbilID = keyboard.nextLine();
System.out.println("What name did the students give to "+ gerbilID);
String gerbilName = keyboard.nextLine();
for (int j = 0; j < food; j++)
{
System.out.println(gerbilID + " eats how many " + foodName[j] + " per day?");
String gerbilComsumption = keyboard.nextLine();
int gerbilFood = Integer.parseInt(gerbilComsumption);
if (gerbilFood <= maxAmount[j])
{
consumption[j] = gerbilFood;
}
}
System.out.println("Does " + gerbilID + " bite?");
boolean biter = keyboard.nextBoolean();
System.out.println("Does " + gerbilID + " try to escape?");
boolean flightRisk = keyboard.nextBoolean();
keyboard.nextLine();
Gerbil temp = new Gerbil (gerbilID, gerbilName, consumption, biter, flightRisk);
gerbilAttributes [i] = temp;
}
boolean end1 = false;
while (! end1){
System.out.println("What information would you like to know");
sortGerbilArray (gerbilAttributes);
String userInput3 = keyboard.nextLine();
if (userInput3.equalsIgnoreCase("average"))
{
String average1 = foodAverage();
System.out.println(average1);
}
if (userInput3.equalsIgnoreCase("search"))
{
System.out.println("Enter a Gerbil ID to search for");
userInput3 = keyboard.nextLine();
Gerbil findGerbil = searchForGerbil(userInput3);
if (findGerbil == null)
{
System.out.println("Error");
}
else {
String h = ("Name: " + findGerbil.getName());
if (findGerbil.getAttacker())
{
h+= " (will bite, ";
}
else
{
h+= " (will not bite, ";
}
if (findGerbil.getFilghtRisk())
{
h+= "will run away), ";
}
else
{
h+= "will not run away), ";
}
h+= "Food:";
for (int i = 0; i < foodName.length; i++){
h+=" " + foodName[i] + "-";
h+= findGerbil.getConsumption2()+"/"+ maxAmount[i];
if (i < foodName.length-1)
{
h+=",";
}
System.out.println(h);
}
}
}
if (userInput3.equalsIgnoreCase("restart")){
}
if (userInput3.equalsIgnoreCase("quit"))
{
System.out.println("Good-bye!");
break;
}
}
}
private static void sortGerbilArray(Gerbil[]sortGerbil){
for (int i = 0; i < sortGerbil.length; i++){
for (int j = 0; j < sortGerbil.length - i - 1; j++){
if(sortGerbil[j].getID().compareToIgnoreCase(sortGerbil[j+1].getID())>0){
Gerbil t = sortGerbil[j];
sortGerbil[j] = sortGerbil[j+1];
sortGerbil[j+1] = t;
}
}
}
}
private static String foodAverage()
{
double average = 0.0;
double totalMaxAmount = 0;
double totalConsumption = 0;
String averageFood = "";
for (int i = 0 ; i < gerbilAttributes.length;i++)
{
for(int j = 0; j < maxAmount.length; j++)
{
totalMaxAmount += maxAmount[j];
}
totalConsumption += gerbilAttributes[i].getConsumption();
average = totalConsumption/totalMaxAmount*100;
averageFood += gerbilAttributes[i].getID() + "(" + gerbilAttributes[i].getName() + ")" + Math.round(average) + "%\n";
totalMaxAmount = 0;
totalConsumption = 0;
}
return averageFood;
}
private static Gerbil searchForGerbil (String x) {
for (Gerbil l: gerbilAttributes){
if (l.getID().equals(x)){
return l;
}
}
return null;
}
}
there are two solutions.
1. wrap your code in "while" loop. but it will be difficult for you because your code is so messy :(
change the code as follow
import java.util.Scanner; public class MutantGerbil {
public static String []foodName;
public static int [] maxAmount;
public static Gerbil [] gerbilAttributes;
public static int [] consumption;
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
String userInput1 = keyboard.nextLine();
int food = Integer.parseInt(userInput1);
foodName = new String[food]; //array of food names
maxAmount = new int[food]; // array of max amount of food given everyday
for (int i = 0; i < food; i++){
System.out.println("Name of food item" + (i+1) +": " );
String foodType = keyboard.nextLine();
foodName[i] = foodType;
System.out.println("Maximum consumed per gerbil: ");
String consumption = keyboard.nextLine();
int consumption2 = Integer.parseInt(consumption);
maxAmount [i] = consumption2;
}
System.out.println("How many gerbils are in the lab?");
String userInput2 = keyboard.nextLine();
int numberOfGerbils = Integer.parseInt(userInput2);
gerbilAttributes = new Gerbil [numberOfGerbils];// Array with the gerbil attributes
for (int i = 0; i < numberOfGerbils; i++)
{
consumption = new int[food]; // Array with amount of the food the gerbil eat each day
System.out.println("Gerbil" + (i+1) + "'s" + "lab ID: ");
String gerbilID = keyboard.nextLine();
System.out.println("What name did the students give to "+ gerbilID);
String gerbilName = keyboard.nextLine();
for (int j = 0; j < food; j++)
{
System.out.println(gerbilID + " eats how many " + foodName[j] + " per day?");
String gerbilComsumption = keyboard.nextLine();
int gerbilFood = Integer.parseInt(gerbilComsumption);
if (gerbilFood <= maxAmount[j])
{
consumption[j] = gerbilFood;
}
}
System.out.println("Does " + gerbilID + " bite?");
boolean biter = keyboard.nextBoolean();
System.out.println("Does " + gerbilID + " try to escape?");
boolean flightRisk = keyboard.nextBoolean();
keyboard.nextLine();
Gerbil temp = new Gerbil (gerbilID, gerbilName, consumption, biter, flightRisk);
gerbilAttributes [i] = temp;
}
boolean end1 = false;
while (! end1){
System.out.println("What information would you like to know");
sortGerbilArray (gerbilAttributes);
String userInput3 = keyboard.nextLine();
if (userInput3.equalsIgnoreCase("average"))
{
String average1 = foodAverage();
System.out.println(average1);
}
if (userInput3.equalsIgnoreCase("search"))
{
System.out.println("Enter a Gerbil ID to search for");
userInput3 = keyboard.nextLine();
Gerbil findGerbil = searchForGerbil(userInput3);
if (findGerbil == null)
{
System.out.println("Error");
}
else {
String h = ("Name: " + findGerbil.getName());
if (findGerbil.getAttacker())
{
h+= " (will bite, ";
}
else
{
h+= " (will not bite, ";
}
if (findGerbil.getFilghtRisk())
{
h+= "will run away), ";
}
else
{
h+= "will not run away), ";
}
h+= "Food:";
for (int i = 0; i < foodName.length; i++){
h+=" " + foodName[i] + "-";
h+= findGerbil.getConsumption2()+"/"+ maxAmount[i];
if (i < foodName.length-1)
{
h+=",";
}
System.out.println(h);
}
}
}
if (userInput3.equalsIgnoreCase("restart")){
main();
}
if (userInput3.equalsIgnoreCase("quit"))
{
System.out.println("Good-bye!");
break;
}
}
}
private static void sortGerbilArray(Gerbil[]sortGerbil){
for (int i = 0; i < sortGerbil.length; i++){
for (int j = 0; j < sortGerbil.length - i - 1; j++){
if(sortGerbil[j].getID().compareToIgnoreCase(sortGerbil[j+1].getID())>0){
Gerbil t = sortGerbil[j];
sortGerbil[j] = sortGerbil[j+1];
sortGerbil[j+1] = t;
}
}
}
}
private static String foodAverage()
{
double average = 0.0;
double totalMaxAmount = 0;
double totalConsumption = 0;
String averageFood = "";
for (int i = 0 ; i < gerbilAttributes.length;i++)
{
for(int j = 0; j < maxAmount.length; j++)
{
totalMaxAmount += maxAmount[j];
}
totalConsumption += gerbilAttributes[i].getConsumption();
average = totalConsumption/totalMaxAmount*100;
averageFood += gerbilAttributes[i].getID() + "(" + gerbilAttributes[i].getName() + ")" + Math.round(average) + "%\n";
totalMaxAmount = 0;
totalConsumption = 0;
}
return averageFood;
}
private static Gerbil searchForGerbil (String x) {
for (Gerbil l: gerbilAttributes){
if (l.getID().equals(x)){
return l;
}
}
return null;
} }