please help me
I have to create a 4 function using switch method. And I have a problem with function 3(show list of video and song)
For more details, I suppose I should create a class likes MultimediaManagerment. After that, I create an Arraylist in it and add all the attributes to this for printing the song like:
listOfMultimedia.add(songlist)
listOfMultimedia.add(videoList)
But the problem is the attribute "name" &"duration" are in the superclass Mutimedia while the attribute "singer" is in subclass Song. For that reason, from class MultimediaManagerment I can not add all the attribute to my arrayList.
Any ideas guys?
import java.util.*;
abstract class Multimedia{
String name;
double duration;
Scanner sc= new Scanner(System.in);
Multimedia(){
name=null;
duration=0;
};
void createMultimedia(){
System.out.print("\nEnter name: ");
name = sc.nextLine();
System.out.print("\nEnter duration: ");
duration=sc.nextDouble();
}
};
//Function Create Video
class Video extends Multimedia{
Video(){};
public void createVideo(){
System.out.println("----Enter video information----");
super.createMultimedia();
}
public String toString() {
return name + " " + duration ;
}
}
//Function Create Song
class Song extends Multimedia{
String singer;
Song(){
singer=null;
}
public void createSong(){
System.out.println("----Enter song information----");
System.out.print("Enter singer: " );
singer =sc.nextLine();
super.createMultimedia();
}
public String toString() {
return singer + " " + name + " " + duration ;
}
}
//Function show data
class MultimediaManagement extends Multimedia{
List<Multimedia> listOfMultimedia = new ArrayList<Multimedia>();
MultimediaManagement(){
listOfMultimedia=null;
}
void addMultimedia(Multimedia multimedia){
Multimedia ob = new Song(name, duration, singer); //ERROR
}
}
public class Assign801 {
public static void menu(){
Scanner sc= new Scanner(System.in);
int func;
Video video = new Video();
Song song = new Song();
do
{
System.out.println("Please choose function:\n1. Add a new Video\n2. Add a new Song\n3. Show all multimedia\n4.Exit");
func = sc.nextInt();
} while (func < 0 || func >4);
switch (func) {
case 1:
video.createVideo();
menu();
break;
case 2:
song.createSong();
menu();
break;
case 3: // show list of video & song
case 4: break;
}
}
public static void main(String[] args) {
menu();
}
}
Related
I've got a linked list class with a controller class and a test class which is the main class. The code runs and accepts user input, however when I click to display all team members entered it is empty.
Where have I gone wrong? How do I get all the team members to entered to be displayed?
public class TeamMember {
private LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
this.teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
this.teamMembers = new LinkedList<>();
}
}
package com.view;
import com.controller.TeamMemberController;
import com.model.TeamMember;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TeamMemberTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
TeamMemberController teamMemberController = new TeamMemberController();
int userInput;
do {
System.out.println("1. Add a new team member");
System.out.println("2. Find and display a team member");
System.out.println("3. Remove a team member");
System.out.println("4. Display all team members");
System.out.println("0. Quit");
//Validate user input
try {
userInput = scan.nextInt();
scan.nextLine();
} catch (InputMismatchException e) {
//if anything other than an integer is entered.
//The "scan.nextLine" fix above will not be triggered.
//It has to appear in the catch as well.
scan.nextLine();
userInput = 5;
}
switch (userInput) {
case 0:
userInput = teamMemberController.quit();
break;
case 1:
System.out.println("**********\n" + teamMemberController.addTeamMember());
break;
case 2:
System.out.println("**********\n" + teamMemberController.findTeamMember());
break;
case 3:
System.out.println("**********\n" + teamMemberController.removeTeamMember());
break;
case 4:
teamMemberController.displayAllTeamMembers();
break;
default:
System.out.println("*** Please Make another selection ***");
System.out.println("");
break;
}
} while (userInput != 0);
}
}
package com.controller;
import com.model.TeamMember;
import java.util.LinkedList;
import java.util.Scanner;
public class TeamMemberController {
private TeamMember teamMember;
public TeamMemberController() {
String name = null;
this.teamMember = new TeamMember(name);
}
Scanner scan = new Scanner(System.in);
public String addTeamMember() {
System.out.println("To go back press 0");
String name = null;
boolean keepLooping = true;
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//user enters name
while (keepLooping) {
System.out.println("Enter team member name");
//project names MUST be UNIQUE
name = scan.nextLine();
if (name.equals("0")) {
return "team member not added";
}
if (!this.checkIfTeamMemberNameExists(name)) {
keepLooping = false;
} else {
System.out.println("Team Member already exists");
System.out.println("");
}
}
//add team member to collection
teamMembers.add(new TeamMember(name));
teamMember.setTeamMembers(teamMembers);
//returns true when a team member has been successfully added
return "Name: " + name + "\n--Added--";
}
public String findTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if the company has no team members no need to continue
if (teamMembers.isEmpty()) {
return "Sorry no team members";
}
//get here company must have team members
System.out.println("Enter team member name");
String name = scan.nextLine();
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return "Name: " + t.getTeamMembers();
}
}
return "Team member not found";
}
public String removeTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
System.out.println("Enter name of team member to remove");
System.out.println("Enter 0 to exit");
String projectToRemove = scan.nextLine();
boolean removed = false;
if (projectToRemove.equals("0")) {
return "No project removed";
}
//check existing team member names against the user input one
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(removeTeamMember())) {
teamMembers.remove(t);
removed = true;
}
}
if (removed) {
teamMember.setTeamMembers(teamMembers);
} else
return "No team member found";
return removeTeamMember() + " has successfully been removed";
}
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getTeamMembers() + " ");
}
}
public int quit() {
System.out.println("Are you sure you want to quit? y/n");
String userResponse = scan.nextLine();
boolean loop = true;
while (loop) {
if (userResponse.equalsIgnoreCase("y")) {
System.out.println("Program ending");
return 0;
} else if (userResponse.equalsIgnoreCase("n"))
return 5;
}
return 0;
}
public boolean checkIfTeamMemberNameExists(String name) {
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if a team member with the same name already exists return true
if (!teamMembers.isEmpty()) {
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return true;
}
}
}
return false;
}
}
This is the output I'm getting. How do I get it to print the names entered?
[1]: https://i.stack.imgur.com/FVhVm.png
The first problem is that TeamMembers don't remember the names you give them. Add a field for the name, and a method to retrieve it:
private String name;
public TeamMember(String name) {
this.name = name;
this.teamMembers = new LinkedList<>();
}
public String getName() {
return name;
}
The second problem is that displayAllTeamMembers does not display the "name" of the team member. There was no way it could have done it because the team members didn't even have a name, but now they do.
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getName());
}
}
A third possible problem is that each individual "team member" has a list of team members. That just seems confusing to me and makes me wonder if you have misread the instructions for this exercise.
Below is the minimum code change required to make your code work. But I would suggest to follow design patterns before if you a build a working prod ready system around this code.
public class TeamMember {
private static LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
if(teamMembers==null) {
teamMembers = new LinkedList<>();
}
}
}
//Main :
package DevAyo;
import java.util.Scanner;
public class Main {
private static Scanner scanner =new Scanner(System.in);
private static Album Alb =new Album("Kamikaze");
public static void main(String[] args) {
boolean quit = true;
while (quit){
System.out.println("Choose actions : ");
System.out.println("\t\t 1.Add new Songs to Album :");
System.out.println("\t\t 2.printSongs");
System.out.println("\t\t 3.Quit");
System.out.println("choose Action : ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice){
case 1:
AddSong();
break;
case 2:
Alb.printSongs();
break;
case 3:
quit=false;
break;
}
}
}
public static void AddSong(){
// System.out.println("Insert Album Name: ");
// String albumName =scanner.nextLine();
System.out.println("Pleas Enter Number of Songs :");
int Number = scanner.nextInt();
for (int i=0;i<Number;i++){
System.out.println("Enter Song Name "+(i+1)+": ");
String name=scanner.nextLine();
scanner.nextLine();
System.out.println("Enter Singer of Song "+(i+1)+": ");
String SingerName =scanner.nextLine();
System.out.println("Enter Song "+(i+1)+" released Day: ");
String ReleasedDay = scanner.nextLine();
System.out.println("Enter Length of the Song"+(i+1)+": ");
int SongLength=scanner.nextInt();
Songs song = Songs.creatSong(name,SingerName,ReleasedDay,SongLength);
if(Alb.addSOngs(song))
System.out.println("Songs added ! ");
else
System.out.println("Error ! ");
}
}`enter code here`
}
//Album Class
package DevAyo;
import java.util.ArrayList;
import java.util.Scanner;
public class Album {
public String AlbumName;
private static Scanner scanner = new Scanner(System.in);
ArrayList<Songs> ListofSongs;
public Album(String albumName) {
AlbumName = albumName;
this.ListofSongs=new ArrayList<Songs>();
}
public boolean addSOngs(Songs song){
if(findSong(song.getSongName())>=0){
System.out.println("Songs aLready Exisit ! ");
return false;
}
ListofSongs.add(song);
return true;
}
private int findSong(String songName){
for(int i=0; i<ListofSongs.size();i++){
Songs song = ListofSongs.get(i);
if(song.getSongName().equals(songName)){
return i;
}
}
return -1;
}
public void printSongs(){
for(int i=0;i<this.ListofSongs.size();i++){
System.out.println("Song Name: "+ this.ListofSongs.get(i).getSongName()+"\n"
+"Singer: "+this.ListofSongs.get(i).getSongSinger()+"\n"+"Song Released Day: "+this.ListofSongs.get(i).getSongDay()+
"\n"+"Song Length: "+this.ListofSongs.get(i).songLength+" min");
}
}
}
//Songs Class
package DevAyo;
public class Songs {
public static String songName;
public static String songSinger;
public static String songDay;
public static int songLength;
public Songs(String songName, String songSinger, String songDay, int songLength) {
this.songName = songName;
this.songSinger = songSinger;
this.songDay = songDay;
this.songLength = songLength;
}
public String getSongName() {
return this.songName;
}
public String getSongSinger() {
return this.songSinger;
}
public String getSongDay() {
return this.songDay;
}
public int getSongLength() {
return this.songLength;
}
public static Songs creatSong(String name, String singerName, String releasedDay, int songLength){
return new Songs(songName,songSinger,songDay,songLength);
}
}
i just tried so many was i can't undrestand why it displlays null , i 've created the constructor in both classes and still dosen't seem to work, honestly i've searched the internet about the problem but it's says that i should add constructor i've add them but nothing happpen anyway hope the code is clear , hope you guys can help thanks .
After a Scanner.nextInt(); leaves an empty line so the next time you call Scanner.nextLine(); it will give you that empty line.
If you want to avoid this, you could do one of this 2 options:
Parse
Always use Scanner.nextLine() and cast to the type of variable you want.
Example: int a = Integer.parseInt(scanner.nextLine());
Read that empty line
always you use the nextInt() immediately call nextLine()
Example:
int a = scanner.nextInt();
scanner.nextLine()
I have a program where data from a CSV file gets put into an ArrayList. On the user menu, the user will first press 1 to do just that, i.e., call the data from the CSV file and put it into the ArrayList, and then press 2 for the console to show the user what data is stored.
How can I execute option 2?
This is my menu:
public class Main {
public static void main(String args[]){
SimpleCarFactory factory = SimpleCarFactory.getInstance();
CarStore store = new CarStore(factory);
Car Vauxhall = store.createCar("Vaux");
Car Volvo = store.createCar("Vol");
Scanner input = new Scanner(System.in);
int choice;
do
{
userInput();
choice = input.nextInt();
switch(choice)
{
case 1:
vauxhall.getData();
System.out.println("Data for " + vauxhall.getName() + " car loaded successfully");
volvo.getData();
System.out.println("Data for " + vol.getName() + " car loaded successfully");
break;
case 2:
System.out.println(vauxhall.getData());
System.out.println(vauxhall.getData());
case 0:
System.out.println("BYE");
System.exit(0);
break;
}
System.out.println();
}while(choice !=0);
input.close();
}
}
This is my Car class:
public class Car {
static String name;
static FileParser fileParser = null;
ArrayList data = new ArrayList();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList getData() {
return data;
}
public void setData(ArrayList data) {
this.data = data;
}
public Card(String name) {
super();
this.name = name;
}
}
This is one of my sub-classes of Car:
public class Vauxhall extends Car {
public Vauxhall(String name) {
super(name);
// TODO Auto-generated constructor stub
}
static FileParser fileParser = null;
public ArrayList getData() {
fileParser = new FileParser();
ArrayList<String> data = fileParser.parseFile("filepath.csv");
List<Vauxhall> VauxhallList = fileParser.populateData(data);
return data;
}
}
Just store the data arraylists, and use them in case 2 (I also added a missing break statement) :
ArrayList vauxhallData = null;
ArrayList volvoData = null;
switch(choice)
{
case 1:
vauxhallData = vauxhall.getData();
System.out.println("Data for " + vauxhall.getName() + " car loaded successfully");
volvoData = volvo.getData();
System.out.println("Data for " + vol.getName() + " car loaded successfully");
break;
case 2:
System.out.println(vauxhallData);
System.out.println(volvoData);
break;
case 0:
System.out.println("BYE");
System.exit(0);
break;
}
I have been stuck on the same problem for days and have googled everything I can think of and I give up. I am trying to write a program where you're supposed to first create a person object, and afterwards be able to give that person different types of belongings. I'm putting each created person in an arraylist and every person is supposed to have their own inventory which is also an arraylist. I just don't understand how to add items to a specific persons arraylist and how to print that arraylist. Do I have to create a new instance of the arraylist 'belongings' every time I create a new person? and how do I access a certain persons arraylist? Appreciate any sort of feedback because I am super noob.
import java.util.ArrayList;
public class Sakregister extends Programskelett{
public static ArrayList<Person> personList = new ArrayList<Person>();
protected boolean nextCommand(){
String command = readString("> ").toLowerCase();
switch(command){
case "print list":
printAll();
System.out.println("Program is running");
break;
case "print person":
printUser();
System.out.println("Program is running");
break;
case "create item":
newItem();
break;
case "create user":
newUser();
break;
case "print richest":
printRichest();
System.out.println("Program is running");
break;
case "crash":
initCrash();
break;
case "quit":
System.out.println("Program has terminated");
return true;
default:
System.out.println("Not a valid command");
}
return false;
}
private void printAll() {
}
private void initCrash() {
for (Person thisPerson : personList) {
for (Item thisItem : thisPerson.belongings)
if (thisItem.name == "Stock"){
((Stock) thisItem).setStockCrash(0);
}
}
}
private void printRichest() {
}
private void newUser() {
System.out.println("enter name: ");
String name = keyboard.nextLine();
Person newPerson = new Person(name);
personList.add(newPerson);
System.out.println("Person added to list");
}
private boolean newItem() {
System.out.println("enter item type: ");
String itemType = readString("> ").toLowerCase();
switch(itemType){
case "trinket":
addTrinket();
break;
case "stock":
addStock();
break;
case "appliance":
addAppliance();
return true;
default:
System.out.println("Not a valid item type");
}
return false;
}
private void addAppliance() {
System.out.println("Enter name of appliance: ");
String appName = keyboard.nextLine();
System.out.println("Enter initial price: ");
int appInitialPrice = keyboard.nextInt();
System.out.println("Enter level of wear: ");
int appWear = keyboard.nextInt();
Appliance newAppliance = new Appliance(appName, appInitialPrice, appWear);
System.out.println("Enter name of owner: ");
Object owner = keyboard.nextLine();
for(Person entry : personList)
if(entry.equals(owner))
entry.belongings.add(newAppliance);
}
private void addStock() {
System.out.println("Enter name of stock entry: ");
String stockName = keyboard.nextLine();
System.out.println("Enter amount: ");
int stockAmount = keyboard.nextInt();
System.out.println("Enter price: ");
int stockPrice = keyboard.nextInt();
Stock newStock = new Stock(stockName, stockAmount, stockPrice);
System.out.println("Enter name of owner: ");
String owner = keyboard.nextLine();
keyboard.nextLine();
for(Person entry : personList) {
if(entry.equals(owner)) {
entry.belongings.add(newStock);
}
}
}
private void addTrinket() {
System.out.println("Enter name of trinket: ");
String trinketName = keyboard.nextLine();
System.out.println("Enter number of gems: ");
int trinketGems = keyboard.nextInt();
System.out.println("Choose gold or silver: ");
String trinketMineral = keyboard.nextLine();
keyboard.nextLine();
Trinket newTrinket = new Trinket(trinketName, trinketGems, trinketMineral);
System.out.println("Enter name of owner: ");
String owner = keyboard.nextLine();
for(Person entry : personList)
if(entry.equals(owner))
entry.belongings.add(newTrinket);
}
private void printUser() {
// TODO Auto-generated method stub
}
protected void printMainMenu(){
System.out.println("Choose a command: ");
System.out.println("start");
System.out.println("quit");
}
public static void main(String[] args) {
Sakregister registerProgram = new Sakregister();
registerProgram.run();
}
}
public class Item{
protected String name;
public Item(String name){
this.name = name;
}
public String getItemName() {
return name;
}
import java.util.ArrayList;
public class Person{
public String name;
public String items;
public ArrayList<Item> belongings = new ArrayList<Item>();
public Person(String name){
this.name = name;
}
public String getName(){
return name;
}
public String toString() {
return "Name: " + name;
}
}
" I just don't understand how to add items to a specific persons arraylist and how to print that arraylist"
Your persons are in the personList, so i would use personList.get(n) to get the nth Person.
To add items to the belongings you can use personList.get(n).belongings.add(item).
To print an arraylist you can use a normal foreach loop:
for(Item i:personList.get(n).belongings){
System.out.println(i.getItemName());
}
Do I have to create a new instance of the arraylist 'belongings' every time I create a new person?
The ArrayList belongings is a field inside the Person class. When you create a person with the constructor all of its fields and variables are created in the memory. This happens every time you create a person, so every object (in your case person in the personList) has its own fields like the belongings list.
The new instance of the ArrayList<Item> belongings is already being created each time you create a new Person object, so you don't need to create it again anywhere. However, there is currently no getter for belongings, so you need to write one to access a given person's belongings. You want something like this:
public ArrayList<Item> getBelongings() {
return belongings;
}
You'll need to write a public method that accepts an Item object and adds it to the belongings of that Person. You shouldn't need help with writing another public method that calls System.out.println() on the belongings directly or iterates through them and prints them out.
I am designing an Address Book and in order to make my AddressBookApp class work (which includes my main method) I have had to create instance variables and make them static in order for each method in my class to be able to access my Name, Email, and Phone objects. I assume that there is a better way, but am struggling to know what that is. Should I create the objects in the main method? Are instance variables the right way to go? Do you guys have any ideas as to how I can improve my design? (If you have any other design suggestions not related to my question then let me know)
Here is the code for my AddressBookApp class:
import java.util.Scanner;
public class AddressBookApp {
//Instance Variables
private static Name name;
private static Email email;
private static Phone phone;
//Constructor
public AddressBookApp() {
name = new Name();
email = new Email();
phone = new Phone();
}
//Main method
public static void main(String[] args) {
new AddressBookApp();
System.out.println("Welcome to the Address Book Application\n");
Scanner sc = new Scanner(System.in);
int menuNumber;
do {
menu();
menuNumber = sc.nextInt();
System.out.println();
if (menuNumber < 1 || menuNumber > 4){
System.out.println("Please enter a valid menu number\n");
} else if (menuNumber == 1) {
printEntries();
} else if (menuNumber == 2) {
addEntry();
} else if (menuNumber == 3) {
removeEntry();
} else {
System.out.println("Thanks! Goodbye.");
sc.close();
return;
}
continue;
} while (menuNumber != 4);
sc.close();
}
/**
* Prints out Main Menu
*/
public static void menu() {
System.out.println("1 - List entries\n" +
"2 - Add entry\n" +
"3 - Remove entry\n" +
"4 - Exit\n");
System.out.print("Enter menu Number: ");
}
/**
* Prints all entries in the Address Book
*/
public static void printEntries() {
name.printNames();
System.out.println();
email.printEmails();
System.out.println();
phone.printPhoneNumbers();
System.out.println();
}
/**
* Adds an entry to the Address Book
*/
public static void addEntry() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
name.addName(sc.nextLine());
System.out.print("Enter Email Address: ");
email.addEmail(sc.nextLine());
System.out.print("Enter Phone Number: ");
phone.addPhone(sc.nextLine());
System.out.println("\nRecord Saved.\n");
}
/**
* Removes and entry from the Address Book
*/
public static void removeEntry() {
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter the record number that you would like to remove: ");
int records = sc.nextInt();
name.removeNames(records - 1);
email.removeEmail(records - 1);
phone.removePhone(records - 1);
}
}
AddressBook and AddressBookApp should be two different classes. AddressBook should look like this:
public class AddressBook {
//Instance Variables
private Name name;
private Email email;
private Phone phone;
//Constructor
public AddressBook() {
name = new Name();
email = new Email();
phone = new Phone();
}
// more Constructors
public void setName(Name name) {
this.name = name
}
public Name getName() {
return name;
}
// more getters and setters
Your app can then create an instance of this in your main() method:
AddressBook book = new AddressBook();
book.setName(new Name("Jeff"));
//more operations on book
You can pass around the object book to any methods in which you need it or keep creating new instances. You can also have it as a static reference in your app class:
private static AddressBook book = new AddressBook();
// in your app class methods
book.burnBeforeReading();
Simple, create two classes: Main and AddressBook.
Main only has
public static void main(String[] args) {
new AddressBook().execute();
...
AddressBook only has instance methods.