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.")
}
Related
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?
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I am doing a project for school, and I am trying to make it to where you can set up a name for yourself while going through a series of questions asked by the computer. I want the user to be able to change their name right after assigning it if they do not like what they put down or they typed something wrong.
Right now the program assigns the name the user wants correctly the first time, but when it goes back through the loop to change it to something else the string is left blank.
Console Output
'''
import java.util.*;
public class JavaInputProdject
{
public static void main(String args[])
{
int i=0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old=false;
boolean aAge=true;
String user="User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n"+un);
do
{
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \""+ user +"\"(true/false)");
System.out.print(un);
if(bob.nextBoolean()==true)
{
boo = true;
un = user + "> ";
}
else
{
if(i>=3)
{
System.out.println("Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n"+un);
bob.next();
i++;
}
} while(boo==false);
}
}
'''
You need to replace the line bob.next() (near the end of the do-while loop) with bob.nextLine().
I believe that bob.next() does not consume the newline that is entered as a result of hitting the <ENTER> key after the bob.nextBoolean() call. Hence the user = bob.nextLine(); line (at the start of the do-while loop) is consuming that newline on the second and subsequent loop iterations. So replacing bob.next() with bob.nextLine() will resolve the problem.
For the sake of completeness, here is the corrected code:
import java.util.Scanner;
public class JavaInputProdject {
public static void main(String[] args) {
int i = 0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old = false;
boolean aAge = true;
String user = "User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n" + un);
do {
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \"" + user + "\"(true/false)");
System.out.print(un);
if (bob.nextBoolean()) {
boo = true;
un = user + "> ";
}
else {
if (i >= 3) {
System.out.println(
"Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n" + un);
bob.nextLine();
i++;
}
} while (boo == false);
}
}
Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
when you want to get correct username based on false flag you doesnt init a value to user.
you should write something like this with bob.nextLine :
System.out.print("Bob> Please type in a new Username\n"+un);
user = bob.nextLine();
i++;
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
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.
can you help me to this, I wanted to add 2 integer coming from CSV and store it in txtfile, but the problem is it was string and if i convert it to an integer i've gots lots of error.. Thank you guys..
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
public static void main (String[]arg)throws Exception {
String readFile = "C:/Users/user/Desktop/student.csv";
String writeFile = "C:/Users/user/Desktop/data.txt";
// Read a comma-separated values (CSV) file.
BufferedReader CSVFile = new BufferedReader (new FileReader(readFile));
// Read line.
String dataRow = CSVFile.readLine();
// Create an array of student
List<Student> students = new ArrayList <Student> ();
// The while checks to see if the data is null. If
// it is, we’ve hit the end of the file. If not,
// process the data.
while (dataRow !=null){
String [] dataArray = dataRow.split(",");
System.out.println(dataRow);
Student student = new Student();
student.setStudentName(dataArray[0]);
student.setScore1(dataArray[1]);
student.setScore2(dataArray[2]);
students.add(student);
dataRow = CSVFile.readLine();
}
// Close the file once all data has been read.
CSVFile.close();
StringBuilder sb = new StringBuilder();
FileWriter fw = new FileWriter(writeFile);
for (Student s : students){
sb.append(s.studentName);
System.out.println(s.studentName + " - " + (s.score1 + s.score2));
// Writing to a text file.
fw.write(sb.toString());
}
// Close the file once all data has been written.
fw.close();
}
}
output:
che,cheche,chet
100,100,100
100,100,100
null - 0
null - 0
null - 0
it should br:
che,cheche,chet
100,100,100
100,100,100
che - 200
cheche -200
chet - 200
If the info you have provided is correct, then the main issue you have is the CSV data is in a columnar format, rather than a typical row format. By that, I mean the first row is name, with the next rows the scores. Each "column" of data matches up with the "header" at the same index.
Your example data:
che, cheche, chet -- row[0]
100, 100, 100 -- row[1]
100, 100, 100 -- row[2]
So row[0] is the name, but you are parsing te data as if the 1st item of a row is the name, and the 2nd and 3rd items are scores - which is not the case based on this sample data.
If you wanted scores you'd need to get the proper index for each row - so che would be row[1][0] and row[2][0].
If this is in fact the case, then you'll want to process the first row to get the names, then you'll want to process the remaining rows to get the scores.
You can try
int number = Integer.parseInt("your string here");
Example:
String one = "1";
String two = "2";
System.out.println(Integer.parseInt(one) + Integer.parseInt(two));
You have made few mistakes in the code.
The score variables in the student class should be integer.
To convert a string to Integer you need to use Integer.parseInt
method. Ideally your conversion should be at the stage when you are
setting the score values.
Why are you adding student object to an ArrayList. Can't you
directly write to the text file?