How can I sort this array based on user input? While using a constructor, I am returning values to the create the output. What I'd like to do is after receiving how the user would like to arrange his/her inputs, I'd like to perform something like an Arrays.sort(books[x].getBook());
But this does not work. Is there a way to arrange the returned values for each input? The following is the error I receive upon using the code below within each if statement, although getBooks() is very well in existence:
Error log
LibraryBookSort.java:56: error: cannot find symbol
Arrays.sort(books[x].getBooks());
^
symbol: method getBooks()
location: class LibraryBook
1 error
Code
public class LibraryBookSort {
public static void main(String[] args) {
LibraryBook[] books = new LibraryBook[5];
for (int x = 0; x < 5; x++) {
books[x] = new LibraryBook();
}
Scanner input = new Scanner(System.in);
for (int x = 0; x < 5; x++) {
// Get title
System.out.print("Enter the title of a book: ");
String title = input.nextLine();
books[x].setBook(title);
// Get author
System.out.print("Enter the author of this book: ");
String author = input.nextLine();
books[x].setAuthor(title);
// Get page count
System.out.print("Enter the number of pages for this book: ");
int pages = input.nextInt();
books[x].setPages(pages);
input.nextLine();
}
System.out.println("How would you like to organize your values?");
System.out.println("Sort by title > Enter 1: ");
System.out.println("Sort by author's last name > Enter 2: ");
System.out.print("Sort by page count > Enter 3: ");
int sortBy = input.nextInt();
// Sort by title
if(sortBy == 1) {
//????;
}
// Sort by author
else if(sortBy == 2) {
//????;
}
// Sort by page count
else if(sortBy == 3) {
//????;
}
// Print sorted array >> Use of constructor
for(int x = 0; x < 5; x++) {
System.out.println();
System.out.println("Book ");
System.out.println("Title: " + books[x].getBook());
System.out.println("Author: " + books[x].getAuthor());
System.out.println("Page Count: " + books[x].getPages());
}}}
The following will arrange my inputs using a comparator. However, the question remains, is there another approach to sorting this data outside of using a comparator?
class TitleComparator implements Comparator {
public int compare(Object book1, Object book2) {
String title1 = ((LibraryBook) book1).getBook();
String title2 = ((LibraryBook) book2).getBook();
return title1.compareTo(title2);
}}
I tried to add like this and it is working. Store the books inside the collection. So that you can make use of Collections.sort function and Comparator.
LibraryBookSort.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class LibraryBookSort {
private static ArrayList<LibraryBook> list;
public static void main(String[] args) {
LibraryBook[] books = new LibraryBook[5];
for (int x = 0; x < 5; x++) {
books[x] = new LibraryBook();
}
Scanner input = new Scanner(System.in);
list = new ArrayList<LibraryBook>();
for (int x = 0; x < 5; x++) {
// Get title
System.out.print("Enter the title of a book: ");
String title = input.nextLine();
books[x].setBook(title);
// Get author
System.out.print("Enter the author of this book: ");
String author = input.nextLine();
books[x].setAuthor(title);
// Get page count
System.out.print("Enter the number of pages for this book: ");
int pages = input.nextInt();
books[x].setPages(pages);
list.add(books[x]);
input.nextLine();
}
System.out.println("How would you like to organize your values?");
System.out.println("Sort by title > Enter 1: ");
System.out.println("Sort by author's last name > Enter 2: ");
System.out.print("Sort by page count > Enter 3: ");
int sortBy = input.nextInt();
// Sort by title
if(sortBy == 1) {
Collections.sort(list,new TitleComparator());
}
// Sort by author
else if(sortBy == 2) {
//????;
}
// Sort by page count
else if(sortBy == 3) {
//????;
}
for(LibraryBook st: list){
System.out.println(st.title+" "+st.author+" "+st.pages);
}
}}
Also added another class TitleComparator.java.
import java.util.Comparator;
public class TitleComparator implements Comparator <LibraryBook>{
#Override
public int compare(LibraryBook arg0, LibraryBook arg1) {
return arg0.title.compareTo(arg1.title);
}
}
This is for sort books based on the title. You can also add PageComparator and AuthorComparator for the other two options.
Related
So I'm making a program for a car dealership as my final project for my class. At this time I'd say I'm about 75% done, but I am having trouble figuring out how to update the users input in an array list. So each array list slot contains the year, make, model, color, and mileage of a car. I can add a new car, I can remove a car, and I can quit my program. I have tried many things, I've read many papers, blogs, forums, and my book for class, but its always updating with the programmers input.
package carDealer;
import java.util.ArrayList;
import java.util.Scanner;
public class VehicleInformation {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<VehicleInventory> car = new ArrayList<VehicleInventory>();
String userInput = "-";
while (!userInput.equals("q")) {
System.out.println("Commands: 'a' to add, 'd' to delete, 'e' to edit, 'q' to quit");
userInput = scnr.next();
if (userInput.equals("a")) {
System.out.println("Year: ");
int year = scnr.nextInt();
System.out.println("Make: ");
String make = scnr.next();
System.out.println("Model: ");
String model = scnr.next();
System.out.println("Color: ");
String color = scnr.next();
System.out.println("Mileage: ");
int mileage = scnr.nextInt();
VehicleInventory userCar = new VehicleInventory();
userCar.setMake(make);
userCar.setModel(model);
userCar.setYear(year);
userCar.setColor(color);
userCar.setMileage(mileage);
userCar.print();
addCar(car, userCar);
}
if (userInput.equals("d")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.remove(userNum - 1);
System.out.println("count: " + car.size());
}
if (userInput.equals("e")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.get(userNum - 1);
You can just do a loop to look up for the car model the user wants to update (it can be any other attribute), and once found update it's value with the desired one:
String vehicleToLookUp = "golf"; // This will be received by user input
String vehicleNewName = "golf gti"; // This will be received by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.get(i).setSomeAttribute(...); // Set the desired attribute here
}
}
Or if you want to substitute the whole object...
String vehicleToLookUp = "golf"; // This will be received by user input
VehicleInventory newVehicle = new VehicleInventory(); // You will set the attributes by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.set(i, newVehicle ); // Create your object and pass it here
}
}
Also, instead of all those if, you could use if/else if or even a switch/case for better performance/readability (think that even if your logic is true for first if, it will check for all the other if you created, wasting time and processing power.
Hello the StackOverflow community! I am recent Java learner with 1 year of experience only. I was asked to design a software that mimics a school DB, storing all names, class, roll, and other details. When asked to, it would display appropriate messages, like calculating performance, deleting records, etc. It is yet an incomplete work but the first part (accepting and storing details) are done. I have spent a lot of time behind this and the only thing I get is a nullPointerError. Sorry, but I have been asked to stick to the basics, so no glitzy code. I have used inheritance. The superclass is "Student".
public class Student {
int roll,age = 0; // Roll to be auto-updated
String cl,name;
// Marks variables now
int m_eng, m_math, m_physics, m_chem, m_bio = 0;
public Student(){
}
public Student(int a, String cla){
age = a;
cl = cla; // Assign values
}
void setMarks(int eng, int math, int phy, int chem, int bio){
m_eng = eng; m_math = math; m_physics = phy; m_chem = chem; m_bio = bio;
}
}
Here's the error:
java.lang.NullPointerException
at Application.accept_data(Application.java:35)
at Application.execute(Application.java:23)
at Application.input(Application.java:16)
at Application.main(Application.java:101)
Here is the code, though:
import java.util.Scanner;
public class Application extends Student {
static int n; static Scanner sc = new Scanner(System.in);
static Student s[];
void input(){
System.out.println("Enter the number of students: ");
n = sc.nextInt();
s = new Student[n]; // Create array for n students
System.out.println("Enter your choice: ");
System.out.println("1. Accept student's details ");
System.out.println("2. Display all records ");
System.out.println("3. Display data student-wise ");
System.out.println("4. Delete record");
System.out.println("5. Display performance status");
System.out.println("6. Exit");
execute();
}
static void execute(){
boolean correct = false;
while (!correct){
int op = sc.nextInt();
switch(op){
case 1: accept_data(); correct = true;
case 2: disp_data();correct = true;
case 3: disp_studentwise();correct = true;
case 4: del_record();correct = true;
case 5: performance();correct = true;
case 6: System.exit(0); correct = true;//Terminate
default: System.out.println("You must enter a choice. Kindly re-enter: ");correct = false;
}
}
}
static void accept_data(){
for (int i = 0; i<s.length; i++){
s[i].roll = i+1; //Autoupdate roll
System.out.println("Enter name: "); s[i].name = sc.nextLine();
System.out.println("Enter age: "); s[i].age = sc.nextInt(); // Refer to object prope.
System.out.println("Enter class: "); s[i].cl = sc.nextLine();
System.out.println("We're heading for marks entry!");
System.out.println("Enter marks in the following order: ENGLISH, MATH, PHYSICS, CHEMISTRY, BIOLOGY");
s[i].setMarks(sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt());
}
System.out.println("Thanks. Main menu, please enter your choice now: ");
execute();
}
static void disp_data(){
System.out.println("The system will display all stored information of students available.");
for (int i = 0; i<s.length; i++){
if (s[i].roll != -1){
continue; // In case record is deleted, it won't display
}
else {
printrec(i);
}
}
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void disp_studentwise(){
System.out.println("Enter the roll number");
int r = sc.nextInt();
boolean ok = (r>s.length||r<0)?false:true;
while (!ok){
System.out.println("Incorrect roll. Please re-enter: ");
r = sc.nextInt();
if (r>s.length) ok = false;
else ok = true;
}
printrec(r-1);
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void printrec(int n){
int i = n;
System.out.println("For roll number " + s[i].roll + ", details: ");
System.out.println("Name: " + s[i].name); System.out.println("Age: " + s[i].age);
System.out.println("Class: " + s[i].cl);
System.out.println("Subject \t Marks");
System.out.println("English: \t " + s[i].m_eng); // Display record with marks
System.out.println("Maths: \t " + s[i].m_math);
System.out.println("Physics: \t " + s[i].m_physics);
System.out.println("Chemistry: \t " + s[i].m_chem);
System.out.println("Biology: \t " + s[i].m_bio);
}
static void del_record(){
System.out.println("Enter the roll number you want to delete: ");
int rll = sc.nextInt();
for (int i = 0; i<s.length; i++){
if (rll == s[i].roll){
s[i].roll = -1; // Assign non-positive value to refer deleted items
}
}
}
static void performance(){
}
public static void main(String[] args){
Application ob = new Application();
ob.input(); // Start program
}
}
Can anyone point out what's going wrong? Why there's a problem with accepting details of students after pressing for the 1st option? It shows nullPointer on s[i].roll. Keep in mind that roll is autoupdated, and user doesn't intervene there. It serves as a primary key. An explanation would be beneficial, if possible of course, I am eager to learn. Thanks.
this :
s = new Student[n]; // Create array for n students
You are just creating an array of 'n' Student objects here ... that doesn't mean that your 'n' Students are initialized ... your array contains only 'null' values ...
you may want in your accept_data method do a :
for (int i = 0; i<s.length; i++){
s[i] = new Student();
s[i].roll = i+1; //Autoupdate roll
....
You are getting an NPE because you create an array of Students in your input method, but you never populate it with Student objects, so in accept_data, you're trying to access the roll field on a non-existent object.
You will need to fill in the array with new Student objects in your input method before you call accept_data.
I have an ArrayList of FlowerClass objects. Each of these FlowerClass objects has a name. I want to go through the ArrayList and count them. I want to display the amount of each. So if I have three FlowerClass objects named Rose, two named Daffodil, and one named Tulip...I want to display the following:
Found 3 Rose
Found 3 Daffodil
Found 3 Tulip
So far, I've gotten it to count correctly using two functions I made. The problem is that I iterate through the entire ArrayList...so it'll show me the results more than once. For example, if the user adds 3 Roses and 2 Daffodils...The output is like this:
Found 3 Roses
Found 3 Roses
Found 3 Roses
Found 2 Daffodils
Found 2 Daffodils
I know why the code does this but I don't know how to erase repeats of output. I also don't know how to implement Collections correctly. I've used Collections on an ArrayList of strings before...and it works. But this time I'd be using Collections on an ArrayList of Objects, and I want to check for the frequency of each specific name. Here is the main class:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class MainClass {
static ArrayList<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add flower to flowerpack.");
System.out.println("2. Remove flower from the flowerpack.");
System.out.println("3. Search for a flower in the flowerpack.");
System.out.println("4. Display the flowers in the flowerpack.");
System.out.println("5. Exit the program.");
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addFlower();
break;
case 2:
searchFlower();
break;
case 3:
displayFlowers();
break;
case 4:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
public static void addFlower(){
if (FlowerClass.numberFlowers() == 25){
System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
return;
}
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
}
public static void searchFlower(){
System.out.println("Enter the flower you want to search for.");
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
int occurrences = 0;
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if (userChoice.equals(name)){
occurrences++;
}
else if(occurrences == 0){
System.out.println("Match not found.");
return;
}
}
System.out.println("Found " + occurrences + " " + userChoice);
}
public static void searchFlower(String desiredFlower){
int occurrences = 0;
String userChoice = desiredFlower;
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if (userChoice.equals(name)){
occurrences++;
}
}
System.out.println("Found " + occurrences + " " + userChoice);
}
public static void displayFlowers(){
int repeats = 0;
/*for (FlowerClass flower: flowerPack){
System.out.println(flower.getName());
}
System.out.println("Number of flowers in pack: " + FlowerClass.numberFlowers());*/
//int occurrences = Collections.frequency(flowerPack, name);
//System.out.println(name + ": " + occurrences);
for (FlowerClass flower: flowerPack){
String name = flower.getName();
searchFlower(name);
}
}
}
Here is the FlowerClass:
public class FlowerClass {
public static int numberOfFlowers = 0;
public String flowerName = null;
public String flowerColor = null;
public int numberThorns = 0;
public String flowerSmell = null;
FlowerClass(){
}
FlowerClass(String desiredName, String desiredColor, int desiredThorns, String desiredSmell){
flowerName = desiredName;
flowerColor = desiredColor;
numberThorns = desiredThorns;
flowerSmell = desiredSmell;
numberOfFlowers++;
}
public void setName(String desiredName){
flowerName = desiredName;
}
public String getName(){
return flowerName;
}
public static int numberFlowers(){
return numberOfFlowers;
}
}
If you look at my last function in the main class, you'll see that I commented out the way I was attempting to implement Collections.frequency. I also tried making a multidimensional array of Strings and storing the names of the flowers and also the number of flowers in the arrays. This was counting everything correctly but I wasn't sure how to display the names alongside the counts. It was getting very messy so I abandoned that attempt for now in favor of trying these other two options. If I can find a way to erase repeated lines of output (or if I can find a way to get Collections to work) then I won't need to tinker with the multidimensional array.
Any tips would be very much appreciated. Thank you for your time.
Interesting code, but it doesn't work the way I would do it.
In this current case as you've done it, you would need to keep track of the flower names you have already encountered:
public static void displayFlowers(){
//int repeats = 0;
List<String> displayedFlowerTypes = new ArrayList<String>();
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if(!displayedFlowerTypes.contains(name))
{
displayedFlowerTypes.add(name);
searchFlower(name);
}
}
}
What I would rather do is maintain a Map that keeps track of the counts of the flower types, and just obtain the numbers for the types from that:
public class MainClass {
static List<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
static Map<String, Integer> flowerCount = new HashMap<String, Integer>();
public static void addFlower() {
if (FlowerClass.numberFlowers() == 25) {
System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
return;
}
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
if(!flowerCount.containsKey(desiredName))
{
flowerCount.put(desiredName, 1);
}
else
{
int currentCount = flowerCount.get(desiredName);
flowerCount.put(desiredName, currentCount+1));
}
}
That way, you could just display the flowers as the following:
public static void displayFlowers() {
for (String name : flowerCount.keySet()) {
//searchFlower(name);
System.out.println("Found " + flowerCount.get(name) + " " + name);
}
}
You could put your Flower(s) in a Set. But the easiest solution I can think of is to sort your flowers. So first, implement a Comparator<FlowerClass>
public static class FlowerComparator implements Comparator<FlowerClass> {
#Override
public int compare(FlowerClass o1, FlowerClass o2) {
return o1.getName().compareTo(o2.getName());
}
}
Then you can sort with Collections.sort(List, Comparator)
FlowerComparator flowerComparator = new FlowerComparator();
Collections.sort(flowerPack, flowerComparator);
And then your for loop needs to be something like this (to stop searching for the same flower),
String lastName = null;
for (int i = 0; i < flowerPack.size(); i++){
FlowerClass flower = flowerPack.get(i);
String name = flower.getName();
if (lastName == null || !lastName.equals(name)) {
lastName = name;
searchFlower(name); // or return the number found, and then add that count to i.
}
}
Im having some trouble printing out details ive put into my array. when i run my addBook i out in details of two books, but when i select option 2 from menu, i get a runtime error (outofbounds),
Above is resolved by adding [i] to the printline and changing my loop length.
The problem i am having now if my BookID from my loanbook, its not incrementing.
import java.util.Scanner;
public class library {
static Scanner keyboard = new Scanner(System.in);
static boolean run = true;
public static fiction [] fictionArray = new fiction[2];
public static nonfiction [] nonfictionArray = new nonfiction[2];
public static void main (String[] args){ // main class method
while (run){ // this while statement allows the menu to come up again
int answer = 0; // answer initialized to Zero
boolean isNumber;
do{ // start of validation
System.out.println("1. Add book"); // Menu selections
System.out.println("2. Display the books available for loan");
System.out.println("3. Display the books currently on loan");
System.out.println("4. Make a book loan");
System.out.println("5. Return book ");
System.out.println("6 Write book details to file");
if (keyboard.hasNextInt()){ // I would like to set values to =>1 <=6
answer = keyboard.nextInt(); // this is more validation for the input for menu selection
isNumber = true;
} else { // else if number not entered, it will prompt for the correct input
System.out.print(" You must enter a number from the menu to continue. \n");
isNumber = false;
keyboard.next(); // clears keyboard
}
}
while (!(isNumber)); // while to continue program after the do has completed
switch (answer){ // switch statement - uses answer from the keyboard to select a case
case 1:
addBook(); // adds book
break;
case 2:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}
}
static void addBook(){
loanbook [] loanArray = new loanbook[2];
String title,author;
int choice;
for(int x = 0; x < loanArray.length; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
for(int count = 0; count < fictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
fictionArray[count] = new fiction(title, author);
System.out.println("The book information you entered was : " + fictionArray[count].toString()); // this will show the entry which was inout to the array
count++; }}
else if (choice == 2) {
for(int count = 0; count < nonfictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
nonfictionArray[count] = new nonfiction(title, author);
System.out.println("The book information you entered was : " + nonfictionArray[count].toString()); // this will show the entry which was inout to the array
count++;}}
else{ int noBooks = loanArray.length;
for (int i=0; i<noBooks; i++){
System.out.print(loanArray[x]);
}}}} // addbook
} // Library end
Below is my Superclass , then my subclass
public class loanbook {
private String title,author;
private int bookID;
public loanbook(String pTitle,String pAuthor){
bookID = 0;
title = pTitle;
author = pAuthor;
bookID++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return "\n BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook
My subclasses are the same except for the class name and constructor
public class fiction extends loanbook {
String bookType;
private String getBookType; // Would be fiction
public fiction(String pTitle,String pAuthor){
super(pTitle,pAuthor);
} // constructor
protected void setBookType (String pBookType){
bookType = pBookType;
} // setter for bookType
protected String getBookType(){
return "Fiction";
}
public String toString(){
return super.toString() +" This book is : "+ getBookType();
}
} // class
You've declared your fictionarray and nonfictionarray to be of length 2. However, in your case 2, you are looping 5 times:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
Change it to 2. It's possible you changed the array length in the declaration, but forgot to change the loop iteration. In that case, you can just use the array's length:
for (int i = 0; i < fictionArray.length; i++) {
Additionally, it looks like you want to print out the specific array element, not the array itself:
System.out.println(fictionArray[i]);
and likewise for nonfictionarray and the nonfiction class.
Two things I see
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
You're trying to print the entire array System.out.println(fictionArray). You probably want System.out.println(fictionArray[i])
Also you should set your array sizes to 5 if you want to loop 5 times
I'm currently working on this project:
Create a simple Friends class with, as a minimum, the following:
-name and age fields
-appropriate constructors
-get/set methods
-toString() method
Create an ArrayList of Friends.
Write a program to manage your list of friends.
Run the program from a menu with the following options:
-Add a Friend
-Remove a Friend
-Display all Friends
-Exit
and I've come a ways, but I'm not sure I'm heading in the right direction.
Here's what I've got so far:
import java.util.ArrayList;
import java.util.Scanner;
public class Friends
{
public static void main( String[] args )
{
int menu;
menu = 0;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList< Friends > name = new ArrayList< >();
ArrayList< Friends > age = new ArrayList< >();
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while(menu != 4)
{
switch(menu)
{
case 1:
while(choice != 2)
{
System.out.println("Enter Friend's Name: ");
name.add = input.next();
System.out.println("Enter Friend's Age: ");
age.add(input.nextInt());
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
} break;
case 2:
System.out.println("Enter Friend's Name to Remove: ");
name.remove(input.next()); break;
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i));
}
for(int k = 0; k < age.size(); k++)
{
System.out.println(age.get(k));
}break;
}
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
System.out.println("Thank you and goodbye!");
}
public String name;
public int age;
public Friends( String friendsName, int friendsAge )
{
this.name = friendsName;
this.age = friendsAge;
}
public String toString()
{
return super.toString();
}
public void setName( String friendsName )
{
name = friendsName;
}
public void setAge( int friendsAge )
{
age = friendsAge;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
I have a few questions:
How do I utilize the Friends class to store user input? (What is wrong with line 34 and 36?)
When I display the friends it shows this:
John
Jen
Jeff
22
24
26
I'd like to have the name and age next to each other rather than all down a line. Any help would be greatly appreciated!
This is where I'm at now, but I messed something up and now it won't allow me to put an argument in "FriendsTest f = new FriendsTest();", but when I don't my friends list just says "null 0"
package friends;
import java.util.ArrayList;
import java.util.Scanner;
public class FriendsTest
{
public static void main( String[] args )
{
int menu;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList< FriendsTest > friends = new ArrayList< >();
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while(menu != 4)
{
switch(menu)
{
case 1:
while(choice != 2)
{
System.out.println("Enter Friend's Name: ");
String name = input.next();
System.out.println("Enter Friend's Age: ");
int age = input.nextInt();
FriendsTest f = new FriendsTest(name, age);
friends.add(f);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
} break;
case 2:
System.out.println("Enter Friend's Name to Remove: ");
friends.remove(input.next()); break;
case 3:
for(int i = 0; i < friends.size(); i++)
{
System.out.println(friends.get(i).name + " " + friends.get(i).age);
}
break;
}
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
System.out.println("Thank you and goodbye!");
}
public String name;
public int age;
}
Your logic is off. You never construct a Friends data structure. Also you should have one arrayList of friends and call it friends:
ArrayList<Friends> friends = new ArrayList<>();
This will store you friends data structure. The next thing you need to do is add your friends information to the friends data structure:
while (choice != 2) {
System.out.println("Enter Friend's Name: ");
String name = input.next();
System.out.println("Enter Friend's Age: ");
String age= input.nextInt();
Friends f = new Friends(name, age);
friends.add(f);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
Then to remove a friend, you have a slightly more complicated method where you have to iterate through the arrayList friends until you find the name of the friend then use the .remove() method.
Then to print your friends you would do:
for(int i=0;i<friends.length;i++) {
friends.get(i).toString();
}
Your toString() method in the Friends class should probably look like this:
public void toString()
{
System.out.println(this.getName() + " " + this.getAge());
}
You should use one ArrayList to store all of the information. If the friend class has properties for name and age then you do not need two arraylists to store them. If you follow that approach then
name.Remove(input.next());
will remove both the name and the age.
In order to display both the name and the age in one line, use only one loop to display both like this (assuming you replace names and age with one arraylist called friends):
for(Friend cFriend:friends){
System.out.println(cFriend.getName()+"\t"+cFreind.getAge());
}
There are a few mistakes here. First off, your arraylists aren't properly parametrized and you could do the same with just one list. What you want is:
ArrayList<Friends> listOfFriends = new ArrayList<Friends>();
You then want to modify your case 1 to have add a new instance of friends to the list, so you'd write:
listOfFriends.add(new Friends(name, age));
and remove can be simplified to
listOfFriends.remove(new Friends(name, age));
For your second question, you can fix it by changing the print statement to:
for(int i = 0; i < name.size(); i++)
{
System.out.println(listOfFriends.get(i).name + " " + listOfFriends.get(i).age);
}
break;
That should do it. Good luck!!
Java follow the concept of classes and object. What you have to do is to create a Class named Friend with required fields. Create an arraylist of Friend CLASS in a different java file or Class maybe named as ManageFriends. Also add the 4 cases under this head.
The following doesn't compile because age has been defined of type ArrayList<Friends>
age.add(input.nextInt()); // can't add an `Integer` to a list of `Friends`
For correcting the display modify case 3 to use a single for loop with a single println() within
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i) + " " + age.get(i));
}
break;
assuming the name and age arrays are the same size, you could just do this:
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i) + age.get(i));
}
also, there's no reason to store the ages and names in a seperate array, considering you have a Friends class anyway. Just store all the data in an ArrayList<Friends>
ArrayList<Friends> friendList = new ArrayList<Friends>();
string name ="";
int age ="";
System.out.println("Enter Friend's Name: ");
name = input.next();
System.out.println("Enter Friend's Age: ");
age = input.nextInt();
friendList.Add(new Friends(name,age);