how to find two's best answers - java

I am trying to find two's greatest numbers that are entered from the console.
I found the first one, but the solution for the second one is not working. The program is compiling and running. Here is the code.
import java.util.Scanner;
public class FindingSecondHighestScore_4_09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double max = 1;
double score2 = 0;
String firstName = "";
String secondName = null;
System.out.println("Enter number of students: ");
int x = input.nextInt();
while(x > 0)
{
System.out.println("Enter Sudent's name");
String name = input.next();
System.out.println("Enter Student's score");
double score = input.nextDouble();
//find max
if(score > max)
{
max = score;
firstName = name;
}
//find second max
if(max < score2 || score < score2)
{
max = score2;
score = score2;
}
else if(max > score2 && score2 < score)
{
score2 = score;
secondName = name;
}
x--;
}
System.out.println("The student: " + firstName + " has the greatest score: " + max);
System.out.println("Second studemt " + secondName + " with second results: " + score2);
}
}

Here is a bit more elaborate implementation (my waking up excercise of today):
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TopScores {
private static final int TOP_SELECTION_SIZE = 2;
public static class Student {
private final String name;
private double score;
public Student(String name) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Name cannot be empty");
}
this.name = name;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public void setScore(String score) {
try {
this.score = Double.parseDouble(score);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal score: " + score);
}
}
#Override
public String toString() {
return String.format("%s with score %s", name, score);
}
}
public static void main(String[] args) {
List<Student> students = new ArrayList<TopScores.Student>();
System.out.println("Please enter students. Press <RETURN> to stop.");
Scanner input = new Scanner(System.in);
boolean enteringData = true;
while (enteringData) {
try {
System.out.print("Enter student's name: ");
Student student = new Student(input.nextLine());
System.out.print("Enter student's score: ");
student.setScore(input.nextLine());
for (int i = 0; i < students.size(); i++) {
if (student.getScore() > students.get(i).getScore()) {
students.add(i, student);
break;
}
}
if (students.size() == 0) {
students.add(student);
}
} catch (IllegalArgumentException e) {
enteringData = false;
}
}
int studentsToDisplay = Math.min(TOP_SELECTION_SIZE, students.size());
if (studentsToDisplay > 0) {
System.out.println("Top students:");
for (int i = 0; i < studentsToDisplay; i++) {
System.out.println("* " + students.get(i));
}
} else {
System.out.println("No students to display");
}
}
}
I created a separate class Student which holds name and score, validates the input and creates the display format for one student.
To determine the top scores I keep all the entered students sorted in a list by adding each new student in the correct position.
The user doesn't have to enter the number of students beforehand but can terminate data entry by entering an empty line (or an invalid score).
After data entry is finished the desired number of top scoring students is printed.
This approach is more flexible; printing the top 3 or top 10 students is a matter of changing the value of TOP_SELECTION_SIZE.
Most important takeaway: try to think in classes (in this case Student) where possible and delegate sensible responsibilities to each class.

Since this looks like homework, I will just give you a few hints:
When you find a new max, what should happen to score2?
Should you look for a new score2 even if you found a new max?

If we want to address the if structures, consider rearranging to something like this:
if (/* new score beats second score, but not first */) {
// replace second score
} else if (/* new score beats both first and second */) {
// move first score down to second
// assign a new first score
}
Let your thought process to correspond closely to the code, which will clarify what each block should do, thus localizing any logic errors.

I think when score is greater than max then have to shift max into second score and set max with new score....
And
When the score is between max and score2 then have to update score2 only with new score
//find max
if(score > max)
{
score2 = max;
max = score;
secondName = firstName;
firstName = name;
}
//find second max
if(score < max && score > score2)
{
score2 = score;
secondName = name;
}

Related

Out of bounds exception for my quicksort method

When i pass the value to my quick sort method it intialls sets the pivot to the list size but after going through the loop every value gets reset to zero and throws an out of bounds exception.
This is the method in question
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
This is the rest of the program
import java.io.IOException;
import java.util.*;
import java.util.HashMap;
import java.time.LocalDate;
public class BankingSystem {
private int option = 0;
int key;
Double newAccBalance;
String transType;
Double transAmount;
ArrayList<Transaction> list = new ArrayList<>();
HashMap<Integer, Account> accounts = new HashMap<>();
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws IOException, InputMismatchException{
BankingSystem bankingSystem = new BankingSystem();
bankingSystem.mainLoop();
}
public void mainLoop() {
option = 0;
while (option != 6) {
display();
option = getKeyboardInteger(keyboard);
if (option == 1) {
createAccount();
} else if (option == 2) {
showAccounts();
} else if (option == 3) {
transaction();
} else if (option == 4) {
deleteAccount();
} else if (option == 5) {
showTransactions();
}
}
}
void display(){
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Main Menu-------------------------------|
---------------------------------------------------------------|
Please select option |
1. Create Account |
2. Display Accounts |
3. Deposit/Withdraw |
4. Delete Account |
5. View Transactions |
6. Exit Program |
---------------------------------------------------------------|
>""");
}
public void createAccount() {
System.out.print("""
---------------------------------------------------------------|
------------------------Create Account Menu--------------------|
---------------------------------------------------------------|
1. Create Account |
2. Return to Main Menu |
""");
while (option == 1 && option !=2) {
System.out.print("Please enter the new account number > ");
int accNum = getKeyboardInteger(keyboard);
System.out.print("Please enter the name of the account holder > ");
String accName = getKeyboardString(keyboard);
System.out.print("Please enter the address of the account holder>> ");
String accAdd = getKeyboardString(keyboard);
System.out.print("Please enter the starting balance: ");
Double accOpBalance = getKeyboardDouble(keyboard);
LocalDate accOpDate = LocalDate.now();
System.out.print("Account open date: " + accOpDate);
Account newAccount = new Account(accNum, accName, accAdd, accOpDate, accOpBalance);
accounts.put(accNum, newAccount);
System.out.print("*Account " + accNum + " added to database* "+ "\n" + ">");
option = getKeyboardInteger(keyboard);
}
}
public void showAccounts() {
option = 0;
while (option == 1 || option != 2){
System.out.print("""
---------------------------------------------------------------|
-----------------------Show Account Menu-----------------------|
---------------------------------------------------------------|
1. View all Accounts |
2. Return to Main Menu |
>""");
option = getKeyboardInteger(keyboard);
for (Map.Entry<Integer, Account> accountEntry : accounts.entrySet()) {
System.out.println("Account key(number) = " + accountEntry.getKey() + accountEntry.getValue());
System.out.println("---------------------------------------------------------------|");
}
}
}
public void deleteAccount(){
int key;
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Delete Menu-----------------------------|
---------------------------------------------------------------|
1. Delete Account |
2. Main Menu |
>""");
while(option != -1) {
System.out.print("""
Select Account Number
>""");
key = getKeyboardInteger(keyboard);
accounts.remove(key);
option = getKeyboardInteger(keyboard);
}
}
public void transaction(){
option = 0;
while(option != 3){
System.out.println("""
---------------------------------------------------------------|
-----------------------Transaction Menu------------------------|
---------------------------------------------------------------|
Please select the type of transaction:
1. Deposit
2. Withdraw
3. Main Menu""");
option = getKeyboardInteger(keyboard);
switch(option){
case 1 -> {
doDeposit();
break;
}
case 2 -> {
doWithdrawal();
break;
}
}
}
}
public void doWithdrawal(){
transType = "Withdrawal";
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
System.out.print("How Much would you like to withdraw > ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount > getBalance) {
System.out.println("Insufficient funds");
}else{
newAccBalance = getBalance - transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void doDeposit(){
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
transType = "Deposit";
System.out.print("How Much would you like to deposit? ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount <= 0) {
System.out.print("Please enter a positive value!");
}else {
newAccBalance = getBalance + transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void showTransactions() {
option = 0;
key = getKeyboardInteger(keyboard);
list = accounts.get(key).transList;
myQuickSort(list);
while(option != 2) {
System.out.print("""
---------------------------------------------------------------|
-------------------Show Transactions Menu----------------------|
---------------------------------------------------------------|
1.View Transactions
2.Main Menu
>""");
for(int i = 0; i < accounts.get(key).transList.size(); i++){
System.out.print(accounts.get(key).transList.get(i));
}
option = getKeyboardInteger(keyboard);
}
}
public String getKeyboardString(Scanner keyboard){
while (true){
try{
return keyboard.next();
}catch(Exception e){
keyboard.next();
System.out.print("Something went wrong! Please try again" + "\n> ");
}
}
}
public int getKeyboardInteger(Scanner keyboard){
while(true){
try{
return keyboard.nextInt();
}catch(Exception e){
keyboard.next();
System.out.print("Not an option! Please enter a valid option" + "\n> ");
}
}
}
public Double getKeyboardDouble(Scanner Double){
while(true){
try{
return keyboard.nextDouble();
}catch (Exception e){
keyboard.next();
System.out.print("Not an option! Enter an Integer or Decimal value" + "\n>");
}
}
}
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
}
import java.time.LocalDate;
import java.util.ArrayList;
public class Account{
private int accNum;
private String accName;
private String accAdd;
private LocalDate accOpDate;
private Double accOpBalance;
public ArrayList<Transaction> transList;
public Account(int accNum, String accName, String accAdd, LocalDate accOpDate, Double accOpBalance){
setAccNum(accNum);
setAccName(accName);
setAccAdd(accAdd);
setAccOpDate(accOpDate);
setAccOpBalance(accOpBalance);
transList = new ArrayList<Transaction>();
}
public void setAccNum(int accNum){
this.accNum = accNum;
}
public int getAccNum(){
return accNum;
}
public void setAccName(String accName){
this.accName = accName;
}
public void setAccAdd(String accAdd){
this.accAdd = accAdd;
}
public void setAccOpDate(LocalDate accOpDate){
this.accOpDate = accOpDate;
}
public void setAccOpBalance(Double accOpBalance){
this.accOpBalance = accOpBalance;
}
public Double getAccOpBalance(){
return accOpBalance;
}
#Override
public String toString() {
return "\n" + "Account Number: " + accNum + "\n" + "Name: " + accName +
"\n" + "Account Holder Address: " + accAdd + "\n" +"Account open date: "
+ accOpDate + "\n" + "Account balance: " + accOpBalance;
}
}
import java.util.ArrayList;
public class Transaction extends ArrayList implements Comparable<Transaction> {
private Double transAmount;
private String transType;
public Transaction(Double transAmount, String transType){
this.transAmount = transAmount;
this.transType = transType;
}
public void setTransAmount(Double transAmount){
this.transAmount = transAmount;
}
public String getTransType(){
return transType;
}
public void setTransType(String transType){
this.transType = transType;
}
public Double getTransAmount(){
return transAmount;
}
#Override
public int compareTo(Transaction compareAcc){
if(this.transAmount < compareAcc.transAmount)
return -1;
else if (compareAcc.transAmount < this.transAmount)
return 1;
return 0;
}
#Override
public String toString() {
return "\n" + "Transaction type: " + transType +
"\n" + "Amount: " + transAmount + "\n";
}
}
Ive tried running through the code step by step in intellij but cant quite figure it out.
Well, I'd like to make this quick and easy to understand. The problem here is that it recurses infinitely. Everytime it reaches the
lesser = myQuickSort(lesser);
line is recurses. And keep in mind that the list parameter this method receives shrinks in size every time it recurses. Because, for example, the first time you give it a list of size 100 then it gets sorted into lesser/greater and then lesser invokes the method again and it recurses again but this time the arraylist given as the parameter is less than the first. Until it reaches a point where the list has pivot = 0 in it and when it's done sorting that it recurses for one final time and attempts to run this line of code.
Transaction pivot = list.get(list.size()-1);
Which attempts to get the Transaction at the -1 index since the list at this point is empty so the size = 0. This causes an ArrayIndexOutOfBoundsException.
This is a very problematic method and also keep in mind that you probably need a base case to stop it from recurring infinitely and also a few improvements in general.
Hope this helps.
Edit: also due to the infinite recursion this method could cause a stackoverflow error

Scanner cant read/incorrectly reading my input

I am writing a code whereby I have to input people's name and money value. However I have used a scanner but it does not read the name that I input into the console. Whatever name I put, the code will tell me that no such name is found. I have tried for many hours trying to resolve this, assistance would be appreciated! (there are 6 total cases but I only posted the first one since its the only one I'm having problems with)
The code is as such:
import java.util.Scanner;
public class Client {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
Change[] changeArray = new Change [10];
int numNames = 0;
System.out.println("Please enter at least 10 records to test the program");
String name = "";
int change = 0;
int flag = 0;
int[] totalNumberOfCoinsOf = {0,0,0,0,0};
for (int i = 0;i < changeArray.length;i++)
{
System.out.println("Enter name: ");
name = reader.nextLine();
do {
System.out.println("Enter coin value for the person");
change = Integer.parseInt(reader.nextLine());
if (change % 5 ==0) {
break;
}else if (change % 5 <2.5) {//round down to nearest 5 if change is less than 2.5
change = change - change %5;
break;
}
else if (change %5>=2.5)
{
change = Math.round(change * 100)/100; //round up to nearest 5 if change is more than 2.5
}
}while (true);
changeArray[i] = new Change(name, change);
numNames++;
do {System.out.println("Do you have another person to enter? (Y/N) ");
String choice = reader.nextLine();
if (i!=changeArray.length - 1) {
if(choice.toUpperCase().equals("Y")) {
break;
}else if (choice.toUpperCase().equals("N")) {
flag = 1;
break;
}
}
}while(true);
if (flag==1) {
break;
}
}
do {
System.out.println("\n[1] Search by name ");
System.out.println("\n[2] Search largest coin");
System.out.println("\n[3] Search smallest coin");
System.out.println("\n[4] Total coins");
System.out.println("\n[5] Sum of coins");
System.out.println("\n[6] Exit the program");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(reader.nextLine());
switch (choice) {
case 1:
System.out.print("Enter name to search: ");
name = reader.nextLine();
flag = 0;
for (int i = 0;i < numNames; i++) {
if (name.equals(changeArray[i].getName())) {
System.out.println("Customer: ");
System.out.println(changeArray[i].getName() + " " + changeArray[i].getCoinChangeAmount());
int[] coins = changeArray[i].getChange();
System.out.println("Change: ");
if(coins[0]!=0) {
System.out.println("Dollar coins: "+coins[0]);
}
if(coins[1]!=0) {
System.out.println("50 cents: "+coins[1]);
}
if(coins[2]!=0) {
System.out.println("25 cents: "+coins[2]);
}
if(coins[3]!=0) {
System.out.println("10 cents: "+coins[3]);
}
if(coins[4]!=0) {
System.out.println("5 cents: "+coins[4]);
}
flag++;
}
}
if (flag==0) {
System.out.println("Name: "+name);
System.out.println("Not found! ");
}
break;
//Change class
import java.util.Scanner;
public class Change {
private String name;
private int coinChangeAmount;
public Change() {
this.name = "no name";
this.coinChangeAmount = 0;
}
public Change(String name, int coinChangeAmount) {
this.name = "name";
this.coinChangeAmount = coinChangeAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoinChangeAmount() {
return coinChangeAmount;
}

Java - Printing n times a string which is included in an ArrayList of objects

There's an exercise I'm doing which asks the user for an integer (points) until the user input is -1. It then wants me to display the average of these points, the average of the passing points (those >50), the pass percentage, and finally the grade distribution which is the part that I'm facing the problem.
The Grade Distribution part basically awards a grade from 0 to 5, based on how many points each input is. For example, an input integer <50 points will get a 0 grade, while one >50 && <60 will get the grade 1 etc. After the user has finished submitting the points, it then calculates how many people have scored a specific grade and distributes that number as a string (stars). So say that the user submits five times the points integer 49, there will be five stars at the grade 0.
After hours of trying, I managed to solve it but probably in the most unreliable way ever. I have three java files. One for the main, one for the class Points and one for the class Grades. In the Grades class, I just have two instance variables, a string(stars) and the integer grade. In the Points class, where I calculate the averages etc, I also create a new ArrayList and through a method I call in the main program, named createFiveGrades, I add 5 seperate Grades objects. Then through the method pointsToGrade (that I again call in the main) I convert the points to grades and add stars in the objects of the aforementioned ArrayList when applicable.
The class Points:
public class Points {
private int points;
private int counter;
private int passingPoints;
private int passingCounter;
private ArrayList<Grades> distr;
public Points() {
this.points = 0;
this.counter = 0;
this.passingPoints = 0;
this.passingCounter = 0;
this.distr = new ArrayList();
}
public void addPoints(int points) {
//code
}
public double totalPointsAverage() {
//code
}
public int getPassingPoints() {
//code
}
public double passingPointsAverage() {
//code
}
public double passPercentage() {
//code
}
public void createFiveGrades() {
this.distr.add(new Grades());
this.distr.get(0).setGrade(0);
this.distr.add(new Grades());
this.distr.get(1).setGrade(1);
this.distr.add(new Grades());
this.distr.get(2).setGrade(2);
this.distr.add(new Grades());
this.distr.get(3).setGrade(3);
this.distr.add(new Grades());
this.distr.get(4).setGrade(4);
this.distr.add(new Grades());
this.distr.get(5).setGrade(5);
}
public void pointsToGrade(int po) {
if (po < 50) {
this.distr.get(0).addStars("*");
} else if (po >= 50 && po < 60) {
this.distr.get(1).addStars("*");
} else if (po >= 60 && po < 70) {
this.distr.get(2).addStars("*");
} else if (po >= 70 && po < 80) {
this.distr.get(3).addStars("*");
} else if (po >= 80 && po < 90) {
this.distr.get(4).addStars("*");
} else if (po >= 90 && po <= 100) {
this.distr.get(5).addStars("*");
}
}
public ArrayList<Grades> distribution() {
return this.distr;
}
The class Grades:
public class Grades {
private int grade;
private String stars;
public Grades() {
this.grade = 0;
this.stars = "";
}
public void setGrade(int n) {
this.grade = n;
}
public void addStars(String str) {
this.stars += str;
}
public String toString() {
return this.grade + ": " + stars;
}
}
The main:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Points points = new Points();
points.createFiveGrades();
System.out.println("Enter points in totals, -1 stops:");
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == -1) {
System.out.println("Point average (all): " + points.totalPointsAverage());
if (points.getPassingPoints() > 0) {
System.out.println("Point average (passing): " + points.passingPointsAverage());
} else {
System.out.println("Point average (passing): -");
}
System.out.println("Pass percentage: " + points.passPercentage());
System.out.println("Grade distribution: ");
for (int i=points.distribution().size()-1; i>=0; i--) {
System.out.println(points.distribution().get(i));
}
break;
} else if (input >= 0 && input <= 100) {
points.addPoints(input);
points.pointsToGrade(input);
}
Question: What other ways would be better to implement the Grade Distribution feature of the program? Please do not give me the solution, but rather something to think of. Thanks!
Instead of using a custom class for the grades, you could simply use a map from the grade (Integer) to the number of occurrences of this grade (Integer). Then you can build the star string only at print time based on the values stored in the map.

Why is my program not accepting input through the console? (Java)

I know it's a silly silly program. It's just to practice constructors.
public class PetRecord {
private String name = "Bob";
private int age;
private double weight;
public PetRecord(String initialName, int initialAge, double initialWeight) {
name = initialName;
if(initialAge < 0 || weight < 0) {
System.out.println("Error: Age or weight cannot be negative");
System.exit(0);
}
else {
age = initialAge;
weight = initialWeight;
}
}
public PetRecord(String initialName) {
name = initialName;
}
public void output() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
}
public void setAll(String newName, int newAge, double newWeight) {
name = newName;
if ((newAge < 0) || (newWeight < 0)) {
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else {
age = newAge;
weight = newWeight;
}
}
public void review() {
if(age < 8 && weight < 8) {
System.out.println("Your pets weight and age are healthy.");
}
if(age >= 8 && weight >=8) {
System.out.println("Your pets weight and age are unhealthy.");
}
else {
System.out.println("Come to my office for a proper assessment.");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PetRecord d = new PetRecord("Bob");
System.out.println("Please check if our current records are correct.");
d.output();
System.out.println("Are they correct?");
String answer = input.nextLine();
String yes = "Yes";
String no = "No";
if((answer.equals(yes))) {
System.exit(0);
}
if(answer.equals(no)) {
System.out.println("Please enter your pets name.");
String correctName = input.nextLine();
System.out.println("Age?");
int correctAge = input.nextInt();
System.out.println("Weight?");
double correctWeight = input.nextDouble();
d.setAll(correctName, correctAge, correctWeight);
System.out.println("Your updated records say: ");
d.output();
System.out.println("Would you like a health review?");
String answer1 = input.nextLine();
String yes1 = "yes";
String no1 = "no";
if(answer1.equals(yes1)) {
d.review();
}
if(answer1.equals(no1)) {
System.out.println("Thank you for using PetSystem. Goodbye.");
System.exit(0);
}
}
}
}
My program accepts input for String answer, but my program will not accept String answer1. I can't even type anything in the console after the program asks you if you would like a health review.
The issue comes from here
System.out.println("Your updated records say: ");
d.output();
Because you have printed something out in the middle of accepting input, you most likely have an extra newline token you have not dealt with. Prior to asking the "health review" question place the following code.
while (input.hasNextLine()) {
input.nextLine();
}
This will make sure that you clear out any extra tokens before continuing to accept user input.
you can,t type anything in the console after "if you would like a health review." because you code only runs ones you should put it in a loop to make it run more than once

Why is my program repeating itself. Java Error

I am supposed to make the program give the number of pets and the percentage of how many that are below 5lbs, 5-10lbs, and over 10lbs. The program keeps repeating the statements and I don't know why. I've been working on this problem for the past couple of days and I still can't figure it out. At times it seems like I fixed it but then later on it happens again. Can anyone clarify why this is happening? I need help please.
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.lang.Object;
public class SetPetWeight
{
public static void main(String[] args) {
ArrayList<Pet> list = new ArrayList<Pet>();
String name;
String answer;
int age;
Double weight;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter a String for Pet name: ");
name = keyboard.next();
System.out.println("Enter an int for Pet age: ");
age = keyboard.nextInt();
if(age <= 0)
System.out.println("Error! Enter a real age");
System.out.println("Enter a double for Pet weight: ");
weight = keyboard.nextDouble();
if(weight <= 0)
System.out.println("Error! Enter a real weight");
do
{
System.out.println("Do you want to enter another pet? Y/N");
answer = keyboard.nextLine();
keyboard.nextLine();
} while (answer.equalsIgnoreCase("Y"));
} while (name.length() < 0 && age < 0 && weight < 0);
System.out.println("The weight is now sorted by weight!");
Collections.sort(list, Pet.SortByWeight);
for (Pet p2 : list)
p2.writeOutput();
int average1 = 0;
int average2 = 0;
int average3 = 0;
for (Pet p : list)
{
if(p.getWeight() >= 0 && p.getWeight() <= 5)
{
++average1;
}
else if(p.getWeight() >= 5 && p.getWeight() <= 10)
{
++average2;
}
else if(p.getWeight() > 10)
{
++average3;
}
System.out.println("The average of pets under 5 pounds:" + average1);
System.out.println("The average of pets between 5 and 10 pounds:" + average2);
System.out.println("The average of pets over 10 pounds:" + average3);
}
}
}
Pet Class that is used for the SetPetWeight class and is compiled correctly and is used for the array.
import java.util.*;
public class Pet {
private String name;
private Integer age; // in years
private double weight; // in pounds
public void writeOutput() {
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName) {
name = newName;
// age and weight are unchanged.
}
public void set(int newAge) {
if (newAge <= 0) {
System.out.println("Error: illegal age.");
System.exit(0);
} else
age = newAge;
// name and weight are unchanged.
}
public void set(double newWeight) {
if (newWeight <= 0) {
System.out.println("Error: illegal weight.");
System.exit(0);
} else
weight = newWeight;
// name and age are unchanged.
}
public Pet(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
public static Comparator<Pet> SortByWeight = new Comparator<Pet>()
{
public int compare(Pet pet1, Pet pet2)
{
return (int)(pet1.getWeight() - pet2.getWeight());
}
};
}
Move keyboard.nextLine(); after weight = keyboard.nextDouble(); to consume the dangling newline character .
There are a few changes you may want to make.
1. Every time you retrieve user input for pet's name, age and weight. You may want to create an object of type pet to store this values and then add this to your ArrayList. Before you ask them if they wan to add another pet.
2. Remove the outer do while loop, and change the inter loop to include the "Enter a String for pet name: ".
3. Also check for validation for input.
do {
System.out.println("Enter a String for Pet name: ");
name = keyboard.next();
System.out.println("Enter an int for Pet age: ");
age = keyboard.nextInt();
if(age <= 0)
System.out.println("Error! Enter a real age");
System.out.println("Enter a double for Pet weight: ");
weight = keyboard.nextDouble();
keyboard.nextLine();
if(weight <= 0)
System.out.println("Error! Enter a real weight");
System.out.println("Do you want to enter another pet? Y/N");
answer = keyboard.nextLine();
keyboard.nextLine();
} while (answer.equalsIgnoreCase("Y"));

Categories