Sorting Doubles using Comparator Program - java

I have developed a program that creates an array of Book Objects and sorts them based on user input. The sorting options are author-title-pages-price, and all work but the price sort. Please help me find where my application hangs... (I click the sort by price button and nothing shows up...)
My SchoolTextBook Class:
import java.util.Comparator;
public class SchoolTextBook {
private String author;
private String title;
private int pageCount;
private String ISBN;
private double price;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static Comparator<SchoolTextBook> BookPriceComparator
= new Comparator<SchoolTextBook>() {
public int compare(SchoolTextBook book1, SchoolTextBook book2) {
double price1 = book1.getPrice();
double price2 = book2.getPrice();
//ascending order
return Double.compare(price1, price2);
}
};
}
And my SchoolTextBookSort Class:
import java.util.Arrays;
import java.util.*;
import javax.swing.*;
public class SchoolTextBookSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] choices = {"Author", "Title", "Page Count", "Price"};
SchoolTextBook[] theBooks = new SchoolTextBook[5];
theBooks[0] = new SchoolTextBook();
theBooks[1] = new SchoolTextBook();
theBooks[2] = new SchoolTextBook();
theBooks[3] = new SchoolTextBook();
theBooks[4] = new SchoolTextBook();
theBooks[0].setAuthor("Ernest Hemingway");
theBooks[1].setAuthor("Mark Twain");
theBooks[2].setAuthor("William Shakespeare");
theBooks[3].setAuthor("Stephen King");
theBooks[4].setAuthor("William Faulkner");
theBooks[0].setTitle("A Farewell to Arms");
theBooks[1].setTitle("The Adventures of Huckleberry Finn");
theBooks[2].setTitle("Hamlet");
theBooks[3].setTitle("Salem's Lot");
theBooks[4].setTitle("The Sound and the Fury");
theBooks[0].setPageCount(332);
theBooks[1].setPageCount(320);
theBooks[2].setPageCount(196);
theBooks[3].setPageCount(439);
theBooks[4].setPageCount(326);
theBooks[0].setISBN("0099910101");
theBooks[1].setISBN("0142437174");
theBooks[2].setISBN("0521618746");
theBooks[3].setISBN("0450031063");
theBooks[4].setISBN("0679732241");
theBooks[0].setPrice(5.99);
theBooks[1].setPrice(7.60);
theBooks[2].setPrice(9.41);
theBooks[3].setPrice(16.56);
theBooks[4].setPrice(9.60);
int response = JOptionPane.showOptionDialog(
null // Center in window.
, "Please select a method to sort the books." // Message
, "Sort Text Books" // Title in titlebar
, JOptionPane.YES_NO_OPTION // Option type
, JOptionPane.PLAIN_MESSAGE // messageType
, null // Icon (none)
, choices // Button text as above.
, null // Default button's label
);
//... Use a switch statement to check which button was clicked.
switch (response) {
case 0:
Arrays.sort(theBooks, SchoolTextBook.BookAuthorComparator);
break;
case 1:
Arrays.sort(theBooks, SchoolTextBook.BookTitleComparator);
break;
case 2:
Arrays.sort(theBooks, SchoolTextBook.BookPagesComparator);
break;
case 3:
Arrays.sort(theBooks, SchoolTextBook.BookPriceComparator);
case -1:
//... Both the quit button (3) and the close box(-1) handled here.
System.exit(0); // It would be better to exit loop, but...
default:
//... If we get here, something is wrong. Defensive programming.
JOptionPane.showMessageDialog(null, "Unexpected response " + response);
}
show(theBooks);
}
public static String show(SchoolTextBook[] theBooks) {
StringBuilder sb = new StringBuilder(64);
sb.append("<html><table><tr><td>Author</td><td>Title</td><td>ISBN</td><td>Pages</td><td>Price</td></tr>");
sb.append("<tr>");
sb.append("<td>").append(theBooks[0].getAuthor()).append("</td>");
sb.append("<td>").append(theBooks[0].getTitle()).append("</td>");
sb.append("<td>").append(theBooks[0].getISBN()).append("</td>");
sb.append("<td>").append(theBooks[0].getPageCount()).append("</td>");
sb.append("<td>").append("$" + theBooks[0].getPrice()).append("</td></tr>");
sb.append("<tr>");
sb.append("<td>").append(theBooks[1].getAuthor()).append("</td>");
sb.append("<td>").append(theBooks[1].getTitle()).append("</td>");
sb.append("<td>").append(theBooks[1].getISBN()).append("</td>");
sb.append("<td>").append(theBooks[1].getPageCount()).append("</td>");
sb.append("<td>").append("$" + theBooks[1].getPrice()).append("</td></tr>");
sb.append("<tr>");
sb.append("<td>").append(theBooks[2].getAuthor()).append("</td>");
sb.append("<td>").append(theBooks[2].getTitle()).append("</td>");
sb.append("<td>").append(theBooks[2].getISBN()).append("</td>");
sb.append("<td>").append(theBooks[2].getPageCount()).append("</td>");
sb.append("<td>").append("$" + theBooks[2].getPrice()).append("</td></tr>");
sb.append("<tr>");
sb.append("<td>").append(theBooks[3].getAuthor()).append("</td>");
sb.append("<td>").append(theBooks[3].getTitle()).append("</td>");
sb.append("<td>").append(theBooks[3].getISBN()).append("</td>");
sb.append("<td>").append(theBooks[3].getPageCount()).append("</td>");
sb.append("<td>").append("$" + theBooks[3].getPrice()).append("</td></tr>");
sb.append("<tr>");
sb.append("<td>").append(theBooks[4].getAuthor()).append("</td>");
sb.append("<td>").append(theBooks[4].getTitle()).append("</td>");
sb.append("<td>").append(theBooks[4].getISBN()).append("</td>");
sb.append("<td>").append(theBooks[4].getPageCount()).append("</td>");
sb.append("<td>").append("$" + theBooks[4].getPrice()).append("</td>");
sb.append("</tr></table></html>");
JOptionPane.showMessageDialog(null, sb);
return sb.toString();
}
}

You need to add break statements to some of your case conditions:
switch (response) {
case 0:
Arrays.sort(theBooks, SchoolTextBook.BookAuthorComparator);
break;
case 1:
Arrays.sort(theBooks, SchoolTextBook.BookTitleComparator);
break;
case 2:
Arrays.sort(theBooks, SchoolTextBook.BookPagesComparator);
break;
case 3:
Arrays.sort(theBooks, SchoolTextBook.BookPriceComparator);
break; // <---- Add this
case -1:
//... Both the quit button (3) and the close box(-1) handled here.
System.exit(0); // It would be better to exit loop, but...
break; // <---- Add this
default:
//... If we get here, something is wrong. Defensive programming.
JOptionPane.showMessageDialog(null, "Unexpected response " + response);
break; // <---- Add this
}
If you don't have break statements the program continues and evaluates all of the cases lower than it as if they were true. In other words, if case 3 was true it would do the sort, then it would move on to what happens in case -1 and act as if that was true, which causes the system to exit.

I have found that the problem resides in this code here:
case -1:
//... Both the quit button (3) and the close box(-1) handled here.
System.exit(0); // It would be better to exit loop, but...
default:
//... If we get here, something is wrong. Defensive programming.
JOptionPane.showMessageDialog(null, "Unexpected response " + response);
}
Not sure exactly what it is but this is what was hanging the application.

Related

ArrayList Collections error: which part of my code is wrong?

I would be required to write an array list of Mobile, do some operations such as add, remove, update and display. However, when it comes to sorting objects in arraylist, I am a little bit confused.
I am talking and referring to https://beginnersbook.com/2017/08/comparator-interface-in-java/
In drive class
//Create an arraylist of Mobile
ArrayList<Mobile> themobile = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Mobile");
System.out.println("Please select a number in the following: ");
while (true) {
//A list of options
System.out.println("1. Diplay the next mobile.");
System.out.println("2. Display the previous mobile.");
System.out.println("3. Add a new mobile.");
System.out.println("4. Remove a new mobile");
System.out.println("5. Update a mobile.");
System.out.println("0. Exit");
//prompt user input
int choice = input.nextInt();
switch(choice) {
case 1:
//displayNext(themobile);
break;
case 2:
//displayPrevious(themobile);
break;
case 3:
addMobile(themobile);
break;
case 4:
removeMobile(themobile);
break;
case 5:
updateMobile(themobile);
break;
case 0:
System.out.println("Thank you for using a Mobile arraylist");
System.exit(0);
}
}
Collections.sort((themobile, new MobileByBrandName());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByMoNum());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByInS());
System.out.println("Sorted by brand name" + themobile);
}
In mobile class
public class Mobile implements Comparable<Mobile> {
private String brandName;
private int modelNumber;
private int internalMemoryS;
private int noOfAvailCameras;
public Mobile() {
}
public Mobile(String brandName, int modelNumber, int internalMemoryS, int noOfAvailCameras) {
this.brandName = brandName;
this.modelNumber = modelNumber;
this.internalMemoryS = internalMemoryS;
this.noOfAvailCameras = noOfAvailCameras;
}
public String getBrandName() {
return this.brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public int getModelNumber() {
return this.modelNumber;
}
public void setModelNumber(int modelNumber) {
this.modelNumber = modelNumber;
}
public int getInternalMemoryS() {
return internalMemoryS;
}
public void setInternalMemoryS(int internalMemoryS) {
this.internalMemoryS = internalMemoryS;
}
public int getNoOfAvailCameras() {
return noOfAvailCameras;
}
public void setNoOfAvailCameras(int noOfAvailCameras) {
this.noOfAvailCameras = noOfAvailCameras;
}
public int compareTo(Mobile m) {
return this.brandName.compareTo(m.getBrandName());
}
public String toString() {
return "Brand name: " + brandName + "Model number: " + modelNumber + "Internal memory space: " + internalMemoryS + "No of available cameras: " + noOfAvailCameras;
}
}
Each method has its own class & import java.util.*;
public class MobileByMoNum implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getModelNumber() - m2.getModelNumber();
}
}
public class MobileByBrandName implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getBrandName().compareTo(m2.getBrandName());
}
}
public class MobileByInS implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getInternalMemoryS() - m2.getInternalMemoryS();
}
}
Outcome:
TestMobile.java:48: error: unreachable statement
Collections.sort(themobile, new MobileByBrandName());
^
1 error
Any help and clarification is much appreciated. Thank you
As this code
while (true) {
never exits, the code below this loop is unreachable
Maybe System.exit(0); should maybe only be breaking the while loop.
Note break in a switch will not break the while loop
The code after while loop is never reached. You need to write some logic to break out of the while loop. One easy way to fix this is:
int choice = -1;
while (choice != 0) {
choice = input.nextInt();
switch (choice) {
//...other cases
case 0:
System.out.println("Thank you for using a Mobile arraylist");
}
}
Collections.sort(...);
System.out.println(...);
Put these lines inside while loop
Collections.sort((themobile, new MobileByBrandName());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByMoNum());
System.out.println("Sorted by brand name" + themobile);
Collections.sort(themobile, new MobileByInS());
System.out.println("Sorted by brand name" + themobile);
Also you can simplify the operation of comparison by using Comparator.comparing available from java 8 onwards. Like:
Comparator<Mobile> comparator = Comparator.comparing(new Function<Mobile,
#Override
public String apply(Mobile t) {
return t.getBrandName();
}
}).thenComparingInt(new ToIntFunction<Mobile>() {
#Override
public int applyAsInt(Mobile t) {
return t.getModelNumber();
}
}).thenComparingInt(new ToIntFunction<Mobile>() {
#Override
public int applyAsInt(Mobile t) {
return t.getInternalMemoryS();
}
});
Collections.sort(themobile, comparator);

How to add user input into an array

This is the parent class
public class Holding {
private String holdingId, title;
private int defaultLoanFee, maxLoanPeriod, calculateLateFee;
public Holding(String holdingId, String title){
this.holdingId = holdingId;
this.title = title;
}
public String getId(){
return this.holdingId;
}
public String getTitle(){
return this.title;
}
public int getDefaultLoanFee(){
return this.defaultLoanFee;
}
public int getMaxLoanPeriod(){
return this.maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the child class:
public class Book extends Holding{
private String holdingId, title;
private final int defaultLoanFee = 10;
private final int maxLoanPeriod = 28;
public Book(String holdingId, String title){
super(holdingId, title);
}
public String getHoldingId() {
return holdingId;
}
public String getTitle(){
return title;
}
public int getDefautLoanFee(){
return defaultLoanFee;
}
public int getMaxLoanPeriod(){
return maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getHoldingId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the menu:
public class LibraryMenu {
static Holding[]holding = new Holding[15];
static int hold = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int options = keyboard.nextInt();
do{
}
System.out.println();
System.out.println("Library Management System");
System.out.println("1. Add Holding");
System.out.println("2. Remove Holding");
switch(options){
case 1:
addHolding();
break;
default:
System.out.println("Please enter the following options");
}
}while(options == 13);
System.out.println("Thank you");
}
public static void addHolding(){
System.out.println("1. Book");
System.out.println("2. Video");
int input1 = input.nextInt();
switch(input1){
case 1:
addBook();
break;
case 2:
addVideo();
break;
default:
System.out.println("Please select the following options");
break;
}
}
public static void addBook(){
}
}
All i want is when a user wants to add a book, the user will type in the title and id for it and it will save into the array, and when it is done, it will go back to the menu. I cant seem to do it with my knowledge at the moment.
i tried to do this in the addBook() method
holding[hold] = new Book();
holding[hold].setBook();
the setBook method would be in the Book class, to complete the setBook, i have to make set methods for all the get method. But when i do this, the constructor is undefined.
public void setBook(){
System.out.println("Title: " + setTitle());
System.out.println("ID: " + setHoldingId());
System.out.println("Loan fee: " + setDefaultLoanFee());
System.out.println("Max Loan Period: " + setMaxLoanPeriod());
}
If there is anything wrong with my code, please feel free to say it to me :D
Thanks.
edit: After the user adds a book or video, when the user wants to print all the holdings, it will show the title, id, loan fee and max loan period. How do i do that?
edit2: Clean up a few parts that wasn't necessary with my question
I would suggest you to use "List of Object" concept in handling it.
1) You can define a List of Book object for example.
List<Book> bookList = new ArrayList<Book>();
2) Everytime when you hit AddBook() function, you can then do something like this.
//Create a temporary object of Book to get the user input data.
Book tempBook = new Book(holdingIDParam, titleParam);
//Add them to the list
bookList.Add(tempBook);
3) You can then use that list to your likings, whether to store them into a .txt based database or to use them throughout the program. Usage example:
bookList.get(theDesiredIndex).getBook() ...
I am not entirely sure of what you want but after paying focus on your bold text,this is what I can understand for your case. Feel free to correct me on your requirements if it doesn't meet.
Hope it helps :)

My Exception is not working

I am creating 3 things right now; a driver, a class and an exception.
Currently having trouble with my book store class recognizing the exceptions on my book class.
What am I doing wrong?
Driver: edited by the given suggestion by #Satoshi Kouno
import java.io.*;
import java.util.*;
public class BookStore{
public static void main(String arg[ ]) throws Exception{
Scanner sc = new Scanner(System.in);
int isbn=0;
int quantity = 0;
String title = "";
Book oneBook;
boolean exit = false;
List<Book> bookList = new ArrayList<Book>(); //here
while(true){
try{
sc = new Scanner(System.in);
System.out.print("Enter title: ");
title = sc.nextLine( );
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
System.out.println();
// Validation Codes
// Condition
if(isbn !=0 && quantity != 0 && !"".equals(title))
{
oneBook = new Book(title, isbn, quantity);
bookList.add(oneBook); //create a list in main
System.out.println("Book added in the list.");
}
else
{
System.out.println("Book not added");
break;
}
}
catch(InputMismatchException ime){
System.out.println("you did not enter a number");
}
catch (BookException be){
System.out.println(be.getMessage( )); //
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
} //main method
} //class
Class:
public class Book{
//instance variables
private String title = "";
private int isbn;
private int quantity;
public Book (String title, int isbn, int quantity)throws Exception{
//constructors
setTitle(title);
setIsbn(isbn);
setQuantity(quantity);
}
public String toString( ){ //toString Method
String s = "";
s = s + "Title: " + this.title + "\nISBN: " + this.isbn + "\nQuantity: " + this.quantity + "\n";
return s;
}
public String getTitle( ){
return this.title;
}
public int getisbn( ){
return this.isbn;
}
public int getquantity( ){
return this.quantity;
}
//mutator methods
public void setTitle(String newtitle )throws BookException{
if(newtitle.length()<1){
BookException be = new BookException( );
be.setMessage("Title cannot be blank");
throw be;
}
else{
this.title=newtitle;
}
}
public void setIsbn(int newisbn)throws BookException{
if (isbn <= 1000 || isbn >= 10000) {
this.isbn = newisbn;
}
else{
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
}
public void setQuantity(int newquantity)throws BookException{
if(newquantity>=0){
this.quantity = newquantity;
}
else{
BookException be = new BookException( );
be.setMessage("Quantity can't be a negative number.");
throw be;
}
}
}
And my exception class: edited #2
public class BookException extends Exception {
//instance variable
private String message = "";
public BookException(String message) {
super(message);
}
public void setMessage(String newMessage) {
this.message = newMessage;
}
public String getMessage() {
return this.message;
}
}
Trying to get my class to work with my driver but it's not working.
EDIT!! PSA
i forgot to point out the requirements of my driver class
Read the book title from the user
Read the book ISBN from the user
Read the book in stock quantity from the user
Your program should continue to read the book information from the user until all the entries from the user for all the fields are blank or zero.
Your program will store valid book objects into an ArrayList (only valid objects)
Your program will then print the list all the "valid" Books entered by the user in the reverse order in which the books were entered.
As the user is entering information, the program should give feedback such as reporting that an item has been added to the ArrayList, or reporting any errors found.
my book and exception class are not needed changes already
they just want me to make my own driver to run with both of them and their exceptions
Your class is not working to due this:
// Validation Codes
// Condition
if(isbn !=0 && quantity != 0 && title != null && title != "")
 
title != ""
This condition will be never and never verified so will not enter in the part of code where you create the Book object:
To compare String values just replace it by:
!"".equals(title);
#See String#equals() JavaDOC
or use apache lang classes (probably you will have to import it):
StringUtils.isNotEmpty(title);
Moreover:
I suggest you to modify your custom exception class adding the construct:
public class BookException extends Exception {
public BookException(String message) {
super(message);
}
}
And in Book#setTitle and the other one setters raise it by:
throw new BookException("Title cannot be blank!");
Hope this help.
Update:
Analysing the code i checked others things like:
if (isbn <= 1000 || isbn >= 10000) {
this.isbn = newisbn;
} else {
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
This check is wrong for me, probably you wanted to do this:
isbn >= 1000 && isbn <= 10000

Why end-of-file indicator isn't working in NetBeans?

I am practicing a programming task given in my course literature. The program will keep asking the user to enter student's grades until they enter end-of-file indicator.
What is happening in my case is typing ctrl+Z (on windows, as it instructs me in book) doesn't work. It happens nothing afetr I doing this. Is it a problem with my console window or program?
GradeBook class:
package gradebook;
import java.util.Scanner;
public class GradeBook {
private String courseName;
private int totalGrade;
private int gradeCounter;
private int aCount;
private int bCount;
private int cCount;
private int dCount;
private int fCount;
//Create a contructor
public GradeBook(String name) {
courseName = name;
}
GradeBook() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setCourseName(String name) {
courseName = name;
}
public String getCourseName() {
return courseName;
}
public void displayMessage() {
System.out.printf("Welcome to the course\n%s!\n\n", getCourseName());
}
public void inputGrade() {
//int gradeEnteredByuser;
Scanner input = new Scanner(System.in);
int gradeEnteredByuser;
System.out.printf("%s\n%s\n %s\n %s\n", "Enter the integer grade in the range 0-100", "Type the end-of file indicator to terminate input:",
"On Unix/Linux/Mac OS X type <Ctrl> d then press enter", "On windows type <Ctrl> z then press enter:");
while (input.hasNext()) {
//int gradeEnteredByuser;
gradeEnteredByuser = input.nextInt();
totalGrade += gradeEnteredByuser;
gradeCounter++;
incrementLetterGradeCounter(gradeEnteredByuser);
}
}
private void incrementLetterGradeCounter(int gradeEnteredByuser) {
switch (gradeEnteredByuser / 10)
{
case 9:
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case 7:
++cCount;
break;
case 6:
++dCount;
default:
++fCount;
}
}
public void displayGradeReport(){
System.out.println("\nGrade report");
if(gradeCounter!=0){
double average=(double)totalGrade/gradeCounter;
System.out.printf("Total of the %d grades entered is %d\n", gradeCounter,totalGrade);
System.out.printf("Class avereage is %.2f\n", average);
System.out.printf("%s\n%s\n%s\n%s\n%s\n%s\n",
"Number of students who received each grade:",
"A: ", aCount,
"B: ", bCount,
"C: ", cCount,
"D: ", dCount,
"F: ", fCount);
}else{
System.out.println("No grade were entered:re");
}
}
}
GradeBookTest class:
package gradebook;
import java.util.Scanner;
public class GradeBookTest {
public static void main(String[] args) {
GradeBook gb=new GradeBook("Introduction to computer science");
gb.displayMessage();
gb.inputGrade();
gb.displayGradeReport();
// TODO code application logic here
}
}

Struggling with objects, program does not work as expected(java)

So I have this cyclingmanager game, and I want to show a list of riders by names, and then I want to show their abilities when the user picks a rider. The program compiles and runs nicely, the problem is in my riders() method.It just does not print out c1, my first rider. Thanks in advance.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CyclingManager2 {
public static void main(String[] args) {
//menyvalgene
Menu m = new Menu();
m.choice();
}
}
class Menu {
Scanner in = new Scanner(System.in);
Cyclist cy = new Cyclist();
//choices
public void choice() {
int choice = -1;
while (choice != 0) {
System.out.println("Choose something: ");
System.out.println("-0 will exit the program" + "\n-Pressing 1 will open the database menu");
choice = in.nextInt();
switch(choice) {
case 0: choice = 0; break;
case 1: database(); break;
default: System.out.println("You have to choose either 0 or 1"); break;
}
}
}
public void database() {
System.out.println("Welcome to the database \nThese are the options:\n0 = Back to menu\n1: Riders");
int dbChoice = -1;
while (dbChoice != 0) {
System.out.println();
dbChoice = in.nextInt();
switch(dbChoice) {
case 0: dbChoice = 0; break;
case 1: cy.riders(); System.out.println("Press 0 for going back to the menu\nPress 1 for showing the riders");break;
default: System.out.println("Choose either 0 or 1"); break;
}
}
}
}
class Cyclist {
List<Cyclist> cyclists = new ArrayList<>();
private String name;
private int mountain;
private int timeTrial;
private int sprint;
private int age;
Cyclist c1 = null;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMountain(int mountain) {
this.mountain = mountain;
}
public int getMountain() {
return mountain;
}
public void setTimeTrial(int timeTrial) {
this.timeTrial = timeTrial;
}
public int getTimeTrial() {
return timeTrial;
}
public void setSprint(int sprint) {
this.sprint = sprint;
}
public int getSprint() {
return sprint;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void riders() {
abilities();
for (int i = 0; i < cyclists.size(); i++){
System.out.print(((Cyclist) cyclists).getName());
}
}
public void abilities() {
//Pardilla is created
c1 = new Cyclist();
c1.setName("Sergio Pardilla");
c1.setMountain(75);
c1.setTimeTrial(60);
c1.setSprint(60);
c1.setAge(30);
/*System.out.println(c1.getName() + "'s abilities:");
System.out.println("Mountain - " + c1.getMountain());
System.out.println("TimeTrial - " + c1.getTimeTrial());
System.out.println("Sprint - " + c1.getSprint());
System.out.println("Age - " +c1.getAge());
cyclists.add(c1); //adds Pardilla to cyclists arraylist*/
}
}
You have this for-loop:
for (int i = 0; i < cyclists.size(); i++) {
System.out.print(((Cyclist) cyclists).getName());
}
It is not going to work. You are casting the entire cyclists (an ArrayList) to one cyclist instance. You probably want to iterate over the contents of the ArrayList and get each Cyclist-object in the cyclists array. Try a foreach-loop:
for (Cyclist cyclist : cyclists) {
System.out.print(cyclist.getName());
}
or use a for loop with index based retrieval:
for (int i = 0; i < cyclists.size(); i++) {
cyclists.get(i).getName());
}
I think you want more something like:
public void riders() {
abilities();
for (int i = 0; i < cyclists.size(); i++){
System.out.print(cyclists.get(i).getName());
}
}
Another thing, is that I'm not sure you want List<Cyclist> cyclists = new ArrayList<>(); to be part of Cyclist class.
Two issues:
The part where you add your rider to the ArrayList is commented out.
The way you loop over your ArrayList is by no means correct. Try like this:
for (Cyclist cyclist : cyclists) {
System.out.println(cyclist.getName());
}
You should get Objects from List by calling it number: cyclists.get(i).getName())

Categories