String input to get a object - java

i need to retrive info form a private object but im stuck at this.. its keep say there is a
constructor error
public class Screen{
private movie movieObject;
private Screen(movie movieObject){
this.movieObject = movieObject;
}
private ArrayList<movie> movie = new ArrayList<movie>
public void add(){
String title = keyboard.readString("Enter movie title > ");
String name = keyboard.readString("Enter theatre name > ");
movie add = new movie(title,name) // there is error in this part

Maybe: Line 9 above...
new ArrayList<movie>();
Also if you use standard naming conventions for classes would help us and yourself.

Your last line is quite strange to me. Try instead:
movie.add(new movie(title,name));
Also maybe the movie list instanciation should be done in the constructor ?

Your letter casing is wrong
movie add = new movie(..)
Your class is Movie with capital M, not movie. You should be getting error all over the place, not just the above line
Also, you're missing the (); here new ArrayList<movie>();
And a ; here movie add = new movie(..). <--
But that still doesn't take away from the problems with the letter casing.
It does look like you want something more like this
ArrayList<Movie> movies = new ArrayList<Movie>();
public void add(){
String title = keyboard.readString("Enter movie title > ");
String name = keyboard.readString("Enter theatre name > ");
movies.add(new Movie(title, name));
}
Or maybe you should do something more like this, where your method add a movie, and doesn't concern itself with getting input from keyboard
public void addMovie(Movie movie) {
movies.add(movie);
}
Then in your main you can do something like this
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Screen screen = new Screen();
System.out.println("Enter a title");
String title = keyboard.nextLine();
System.out.println("Enter a name:);
String name = keyboard.nextLine();
screen.addMovie(new Movie(title, name));
}
The last examples make a lot more sense than the way you are trying to do it.

Related

ArrayList in Class A and user trigger the output from Class B. How do I correctly get an output from an ArrayList?

I doing a bigger school project (first part of basic objective programming in java - so not touched extended, polyphorism etc yet, thats next part), but run in to a small problem and tried for couple of days to find solution (thru books and internet). I constructed different ArrayLists in one class and different classes (at least two) should get access to them.
public class Customer
{
public void subMenuCustomer()
{
............code............
int subMenuCust;
ServiceLogic addCustomer = new ServiceLogic();
ServiceLogic listAllCustomers = new ServiceLogic();
while(true)
{
System.out.println("Please Choose your preference: ");
System.out.println("Create account, press \"1\": ");
System.out.println("Get list of clustomers, press \"2\": ");
System.out.println("Log out, press \"0\": ";
subMenuCust = input.nextInt();
switch(subMenuCust)
{
case 1 ://Call method createCustomer in class ServiceTech to add new customers
addCustomer.createCustomer(name, lastname, ssNo);
break;
case 3
listAllCustomers.getCustomer();
............more code..............
}
}
When user has added details (social secuity number, name and lastname) it is stored in seperate ArrayList. These three ArrayList are added(merge/concat) together to a fourth ArayList, listCustomer , so that all elements from the three ArrayList end up in same index [101 -54 Clark Kent, 242-42 Linus Thorvalds, ...].
import java.util.ArrayList;
import java.util.Scanner;
public class ServiceLogic
{
//Create new ArrayLists of Strings
private ArrayList<String> listSSNoCustomers = new ArrayList<>();
private ArrayList<String> listNameCustomers = new ArrayList<>();
private ArrayList<String> listLastnameCustomers = new ArrayList<>();
private ArrayList<String> listCustomers;
Scanner input = new Scanner(System.in);
public boolean createCustomer(String name, String lastname, String ssNo) //
{
System.out.println("Write social security number; ");
ssNo = input.next();
//loop to check that it is a uniq social security number
for(String ssNumber : listSSNoCustomers)
{
if (ssNumber.equals(ssNo))
{
System.out.println("This customer already exist. Must be uniq social security number.");
return true;
}
}
//If social security number is not on list, add it
//and continue add first name and surname
listSSNoCustomers.add(ssNo);
System.out.println(ssNo);
System.out.println("Write firstname; ");
name = input.next();
listNameCustomers.add(name);
System.out.println(name);
System.out.println("Write lastnamame; ");
surname = input.next();
listSurnameCustomers.add(lastname);
System.out.println(lastname);
return false;
}
public void setListCustomer(ArrayList<String> listCustomers)
{
this.listCustomers = listCustomers;
}
public ArrayList<String> getCustomer()
{
//ArrayList<String> listCustomers = new ArrayList<>();
for(int i = 0; i <listSSNoCustomers.size(); i++)
{
listCustomers.add(listSSNoCustomers.get(i) + " " + listNameCustomers.get(i) + " " + listFirstnameCustomers.get(i));
}
System.out.println("customer" + listCustomers);
return listCustomers;
}
}
According to the specification we got, when user want to see list of all customer the outputs should be in format [666-66 Bruce Wayne, 242-42 Linus Thorvalds, ...].
When user (staff) choose to enter details in class Customer ( Case 1 ) it works and elements get stored in the Arraylists for social security numbers, name and lastname (have checked that) .
The problem: when I run I can add customers, but when I try to get a list of customer the output: [] . I tried different solution, but same output only empty between the brackets.
So the question, how do I get ouput to work when user choose case 2 to get a list of all cutomers?

NullPointerException when using .size() in an Arraylist class

currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main

Selecting an instance to proceed with

Somehow I try to make a user selection of which cook has to prepare the food. I already created the variable whichcook and place that where cook1 used to stay. But I don't know how to carry on. I want to let the user select between either "Jan de Vries" or "SinBad" to prepare. So the methode deliverer.delivered(whichcook, customer); carries on with the selected name. I figure if have to use instanceof I guess, but don't know how to really do that. I know how to make a user-input and cases etc that's not the problem. It's more about how to isolate the right instance!!
Someone a key suggestion???
java
package KebabStore;
public class DamascusKebab
{
public static int cooksnumber;
public static int deliverersnumber;
#SuppressWarnings("unused")
public static void main(String[] args)
{
Cook cook1 = new Cook ("Jan de Vries", "Butcherknife 1", "1212-IS", "Allahmelo", 123456);
Cook cook2 = new Cook ("Sinbad", "Camelhumb 2","2323-IS", "Halal-lem", 654321);
Deliverer deliverer1 = new Deliverer ("Ali Baba", "Helmgras 11", "3434-JH", "Ji-Hattem",456789);
Deliverer deliverer2 = new Deliverer ("Muammar", "Zadeldreef 22", "4545-JH", "Moskemenade", 987654);
Customer customer = new Customer ("Piet Hein", "Klantlaan 25", "5656-KL", "Darmstadt");
cooksnumber = Cook.numberofcooks;
deliverersnumber = Deliverer.numberofdeliverers;
Cook whichcook = cook1;
deliverer.delivered(whichcook, customer);
}
}
How are going to get the user input?
if it's from the Scanner
Cook whichcook;
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt()
if (choice == 1)
whichcook = cook1;
else
whichcook = cook2;
deliverer.delivered(whichcook, customer);

If state rework, ignore-case clarification

So, I have a class that creates a Song object containing a Title: Artist: Album.
I prompt the user to ask for a particular artist, and from an ArrayList containing a master play list, the program returns a list, sorted by Title, for each particular artist. This was no problem. The issue I am having is at the point where the user asks for an artist that is not in the master play list. When I code this using an if/then/else, I am receiving one Sysout for every case in which the prompted artist does not match an artist in the master play list. Also, when the user inputs a proper artist, the correct, formatted Arraylist is generated, along with the Sysout for every artist that didn't match the prompted name (so, the entire master list essentially). I need to EITHER return a formatted ArrayList containing only the artist prompted, or a single statement, such as, "Artist not found in list." I've been stuck for a couple of hours, and need a couple of fresh minds on this, if you will. I know why it is happening, I just can't figure my way around my intended output. Also, a little help in understanding why ignoreCase() is not working for me (for checking the searchArtist against an instance variable of Song object) would a big help.
Below is the current code:
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
public class SongList {
public static void main(String[] args){
//An arraylist theList to accept a file containg title : artist : album
ArrayList<Song> theList = new ArrayList<Song>();
try{
Scanner in = new Scanner(System.in);
File inputFile;
// Prompts user for proper input
do{ System.out.println("Please enter a valid input file.");
String input = in.next();
inputFile = new File(input);
}while(!inputFile.exists());
Scanner inp = new Scanner(new FileReader(inputFile));
String line = "";
//Accepts a line that is greater in length that 2 (it assumes a colon, and one blank space)
while((inp.hasNextLine()))
{
line = inp.nextLine();
line = line.trim();
if(line.length() > 2){
Song n = createSong(line);
theList.add(n);
}
}
}
catch(Exception e){
System.out.println("Error with the input file: " + e.getMessage());
}
Collections.sort(theList); //Sorts by title
//An arrayList particularArtist that creates an arrayList of a specified artist as given by the user
ArrayList<Song> particularArtist = new ArrayList<Song>();
Scanner sa = new Scanner(System.in);
String searchArtist = "";
System.out.print("Please enter the name of an artist you'd like to find.");
searchArtist = sa.next();
//This is where I am having the issue.
for(Song theArtist : theList)
if(theArtist.getArtist().contains(searchArtist))
{
particularArtist.add(theArtist);
}
else{System.out.println("The artist you are looking for does not exist in the play list.");}
for(Song is : particularArtist)
System.out.println(is);
}
/*
* Method for creating a Song object given an input file. In the format "Title : Artist: Album," substrings
* are created at the colons, and white space is trimmed.
*/
public static Song createSong(String a) {
int index1 = a.indexOf(':');
int index2 = a.indexOf(':', index1 + 1);
Song s = new Song(a.substring(0, index1).trim(), a.substring(index1 + 1, index2).trim(), a.substring(index2 + 1).trim());
return s;
}
}
solution: if the match exists then add to the result list (particularArtist). If the result list is empty then print artist doesn't exist.
for(Song theArtist : theList) {
if(theArtist.getArtist().contains(searchArtist)) {
particularArtist.add(theArtist);
}
}
for(Song is : particularArtist) {
System.out.println(is);
}
if (particularArtist.size() == 0) {
System.out.println("The artist you are looking for does not exist in the play list.")
}

How do you send an array to an arraylist?

I am have trouble creating an array or object(with multiple fields) and sending it to an array-list. Any help would be greatly appreciated. I have spent hours looking through every video on YouTube with the words object and array-list in them and have been unable to find much help.
The program needs to prompt the user to pick a option (1. AddItem) then prompt the user for the name and format (dvd, vhs) and save multiple objects with these variables in an array-list. I either keep having the location where it is saved in memory returned to me or instead of multiple objects one large object is created.
Library:
import java.util.Scanner;
import java.util.ArrayList;
public class Library {
static ArrayList<Object> items = new ArrayList<Object>();
static int menuOption;
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
String title, format;
boolean right = false;
do{
displayMenu();
if (menuOption == 1){
System.out.println("Enter Title: ");
title = scan.next();
System.out.println("Enter format: ");
format = scan.next();
addNewItem(title, format);
} else {System.out.println(items);
}
} while (!right);
}
static int displayMenu(){
System.out.println("Menu: ");
System.out.println("1. Add New Item");
menuOption = scan.nextInt();
return menuOption;
}
static void addNewItem(String title, String format){
MediaItem b = new MediaItem();
b.setTitle(title);
b.setFormat(format);
items.add(b);
}
}
MediaItem:
public class MediaItem {
String title;
String format;
MediaItem(){
title = null;
format = null
}
MediaItem(String title, String format){
title = new String();
format = new String();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
The program will run if you:
1 - Change the line
static ArrayList<Object> items = new ArrayList<Object>();
to
static ArrayList<MediaItem> items = new ArrayList<MediaItem>();
2 - Change the line
System.out.println( items );
to
for ( MediaItem mi : items )
{
System.out.println( mi.getTitle() + ", " + mi.getFormat() );
}
3 - Insert a ";" at the end of the line
format = null
I did it here and it worked.
I either keep having the location where it is saved in memory returned to me
I am guessing you ran into this when you tried to either use System.out.println() to print a MediaItem, or you otherwise tried to automatically convert an object to a string. Whatever approach you took when you were seeing the memory addresses is probably the right way to do it, your problem was only in your displaying of the data.
Consider:
MediaItem item = ...;
System.out.println(item);
By default, Java doesn't know how to convert arbitrary objects to strings when you do stuff like that, and so it just spits out the class name and memory address. You either need to print the fields separately (e.g. Java knows how to display a String already), like:
System.out.println("Title: " + item.getTitle() + " Format: " + item.getFormat());
Or you can override toString() (declared in Object) to provide a custom string conversion:
class MediaItem {
...
#Override public String toString () {
return "Title: " + title + " Format: " + format;
}
}
And then you can print it directly:
System.out.println(item);
It is the default base implementation of Object.toString() that produces those strings with the memory address in them.
Based on your description, I'm guessing you had a roughly working implementation but ran into this issue and ended up changing around (and breaking) a bunch of other unrelated things to try and fix it.

Categories

Resources