Java Objects Array: How to print only first elements of objects? - java

I'm trying to create a program that takes book names, number of pages, and publishing year as user input. When user does not input anything to name field, program should ask user what will be printed: only names of the books or all information given by user. Here is my main code:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int index = 0;
Scanner reader = new Scanner(System.in);
ArrayList<Books> book = new ArrayList<>();
while (true) {
System.out.println("Name of the book: ");
String name = reader.nextLine();
if (name.isEmpty()) {
break;
}
System.out.println("Number of pages: ");
int pages = Integer.parseInt(reader.nextLine());
System.out.println("Year: ");
int year = Integer.parseInt(reader.nextLine());
book.add(new Books(name,pages,year));
}
while (true) {
System.out.println("What do you want to print?");
String whatwillbeprinted = reader.nextLine();
if (whatwillbeprinted.equals("everything")) {
while(index < book.size()) {
System.out.println(book.get(index));
index++;
}
}
if (whatwillbeprinted.equals("names")) {
while(index < book.size()) {
// print only names of the books
}
}
}
}
}
And here is my Java class named Books:
public class Books {
private String name;
private int pages;
private int year;
public Books(String name, int pages, int year) {
this.name = name;
this.pages = pages;
this.year = year;
}
#Override
public String toString() {
return this.name + ", " + this.pages + ", " + this.year;
}
}
Everything operates correctly until that last while-statement. How can I print only first elements of my objects (names of the books)? Thanks in advance.

public class Books {
private String name;
private int pages;
private int year;
public Books(String name, int pages, int year) {
this.name = name;
this.pages = pages;`
this.year = year;
}
#Override
public String toString() {
return this.name + ", " + this.pages + ", " + this.year;
}
public String getName(){
return name;
}
}
Then calling book.getName () you can get the name of the book, now just write a loop in which display the name of each book
P.S confusion about the name of the class: The name Books is incorrect since the class stores information about only one book. Book - correct title
Book Title Code:
for(int i = 0;i<book.lenght;i++)
{
System.out.println("Name of book: " + book[i].getName());
}

Related

how to output the book's title, author, and show the bookID seperately?

I'm a new java learner. Now I need to set the bookID from 1000, and according to the total number of input IDs, book author, and book title, respectively show the book's information.
For example, when users enter 2, The Lord of the Rings; J. R. R. Tolkien; The Hunger Games; Suzanne Collins;
The output is Book ID: 1000 Title: The Lord of the Rings Author: J. R. R. Tolkien Status: Available Book ID: 1001 Title: The Hunger Games Author: Suzanne Collins Status: Available.
I have completed part of the programming, but now I do not how to write the code in the BOOK[] array.
code:
import java.util.Scanner;
class Book{
private Integer bookID = 1000;
static Integer nextID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
this.isBorrowed = false;
this.nextID = bookID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available");
System.out.println();
}
}
public class MyClass {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
int num=input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i=0; i<num; i++) {
books[i] =input.nextBook();
title = input.nextLine();
author = input.nextLine();
}
}
}
The following is my programming code, please help me see how to write the code of the array part, thank you very much!
This is how it should be done:
nextId must be static because it's the one and only variable that has your last book id.
bookID should not be static because it's different for each book.
Book class:
class Book{
private static Integer nextID = 1000;
private Integer bookID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
this.isBorrowed = false;
this.bookID = nextID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available");
System.out.println();
}
}
Main class:
import java.util.Scanner;
public class MyClass{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i = 0; i < num; i++) {
title = input.nextLine();
author = input.nextLine();
books[i] = new Book(title,author);
}
for (int i = 0; i < num; i++) {
books[i].show();
}
}
}
The following code has a "database" of 2 books. The user is prompted to enter the book id as you stated, it starts with 1000. If the book is found they see your information via the show() method. If this isn't what you want let me know. OR if you want to add a feature that allows the user to input books we can do that too..
Please always give user prompts like "enter a number" when you use scanner.
I went ahead and added so that the user can enter a book and immediately see that the book was stored with the correct id. its alternate main below
import java.util.Scanner;
public class Book {
private static Integer nextID = 1000;
private Integer bookID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
isBorrowed = false;
bookID = nextID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available\n");
}
public static void main(String[] args) {
// here we will create an array of 2 books as your data
Book books[] = new Book[2];
books[0] = new Book("blah", "blah bhal hald");
books[1] = new Book("java", "girl power");
Scanner input = new Scanner(System.in);
System.out.println("Enter the book id:");
int num = input.nextInt();
for (int i = 0; i < books.length; i++){
if (books[i].bookID == num){
books[i].show();
}
}
}
}
alternate main:
```public static void main(String[] args) {
// here we will allow the user to input book data and see the data
// returned with the new id.
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of books you wish to add:");
int num = input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i = 0; i < num; i++) {
System.out.println("enter the title:");
title = input.nextLine();
System.out.println("enter the author");
author = input.nextLine();
books[i] = new Book(title,author);
System.out.println("The book you entered is:");
books[i].show();
}
}

Print specific element of an arraylist in Java based on a given parameter

There's this task I'm working on, in which I have to make an arraylist based on an Author class, which has as its properties: ID, author's name, book and nationality. This aside, I had to make another class, which receives as a parameter the ID, and returns the corresponding author's info. My problem is that I wrote the code, but no matter what ID my input receives, it always retrieves the same author's information. Could anyone help me on this?
Author.java
public class Author {
private int id;
private String name;
private string book;
private string country;
public Author(int id, String name, String book, String country) {
this.id = id;
this.name = name;
this.book = book;
this.country = country;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getBook() {
return book;
}
public int getCountry() {
return country;
}
#Override
public String toString() {
return "Id: " + this.id + ", Name: " + this.name + ", Book:" + this.book + ", Country:" + this.country;
}
}
GetAuthor.java (class used to retrieve Author's info based on the ID)
public class GetAuthor {
public Author returnAuthor(int id, ArrayList<Author> list) {
Author author = null;
id = 0;
for (int i = 0 ; i < list.size() ; i++) {
if(author == null || author(i).getId() == id) {
author = list.get(i);
id = list.get(i).getId();
}
}
return author;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Author w1 = new Author(1, "Franz Kafka", " The Metamorphosis", "Austria");
Author w2 = new Author(2, "Neil Gaiman", "Sandman", "England");
Author w3 = new Author(3, "Jack Kerouac", "On The Road", "USA");
ArrayList<Author> authors = new ArrayList<>();
authors.add(w1);
authors.add(w2);
authors.add(w3);
for(int i = 0 ; i < authors.size() ; i++){
System.out.println(authors.get(i));
}
Scanner scan = new Scanner(System.in);
System.out.print("Enter the author's ID: ");
int num = scan.nextInt();
GetAuthor theAuthor = new GetAuthor();
Author author = theAuthor.returnAuthor(num,authors);
System.out.println(author);
}
}
public static Author returnAuthor(int id, ArrayList list) {
return list.stream().filter(auth -> auth.getId()==id).findFirst().orElse(null);
}
id = 0;
Here you override the passed-in value for id; that's probably why you always get the same answer.
if(author == null || author(i).getId() == id) {
This shouldn't even compile; author is not a method (in your example).

I have a text file but I only need to print certain aspects of the file

I have a text file that essentially resembles a student transcript but I only need to print the student, numbers of courses and then the courses in the this format:
Student A: # of courses
Course title 1
Course title 2
etc.
Student B: # of courses
Course title 1
Course title 2
etc.
Student C: # of courses
Course title 1
Course title 2
etc.
This is a portion of the text file:
Student A,Grade,Credit
Computer Applications,A,1
Career Investigations Phase I,A,1
English 9,A,1
World History II,A,1
Earth Science,A,1
Spanish I,A,1
Art I,A,1
Health & PE 9,B,1
Computer Information Systems,A,1
English 10 Honors,A,1
Geometry,B,1
World History I,A,1
Biology,A,1
Spanish II,A,1
Art II,A,1
Health & PE 10,B,1
"Design, Multimedia, and Web Technologies",C,1
Virginia & United States History,A,1
Algebra II,A,1
Chemistry I,A,1
Spanish III,A,1
Entrepreneurship Education,A,1
Advanced Entrepreneurship Education,A,1
Honors English 12,A,1
Economics and Personal Finance,A,1
AP English Language and Composition,A,1
AP Government and Politics: US,A,1
Mathematical Analysis/Pre-Calculus,A,1
Physics I,A,1
Introduction to Fashion Careers,A,1
Introduction to Culinary Arts,A,1
Career Interpretation - Phase II,A,1
My code so far just print the entire file. I've tried using system.out.println()
in the other places but nothing works. This is my code currently.
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Phase1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
Scanner file = new Scanner(new
FileReader("C:\\Users\\coderva.org\\Downloads\\FakeData.csv"));
ArrayList<Student> students = new ArrayList<Student>();
while(file.hasNextLine())
{
String line = file.nextLine();
String[] lines = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
System.out.println(line);
}
}
class Course
{
private char grade;
private double credit;
private String title;
public Course()
{
title = "";
grade = 'I';
credit = 0;
}
public Course(String title, char grade, double credit)
{
this.title= title;
this.grade = grade;
this.credit = credit;
}
public String getTitle()
{
return title;
}
public char getGrade()
{
return grade;
}
public double getCredit()
{
return credit;
}
public String toString()
{
return title + " " + grade + " " + credit;
}
}
class Student
{
private String name;
private ArrayList<Course> courses;
public Student()
{
name = null;
courses = null;
}
public Student(String name, ArrayList<Course> courses)
{
this.name = name;
this.courses = courses;
}
public void setName(String name)
{
this.name = name;
}
public void setCourses(ArrayList<Course> courses)
{
this.courses = courses;
}
public String getName()
{
return name;
}
public ArrayList<Course> getCourses()
{
return courses;
}
}
}
Okay, so in your code, you created a main class called Phase1, a course class called Course, and a student class called Student. The idea behind creating these classes is correct. Basically, in your main class, you want to run through each line of the input file and parse the contents. You need to determine if the line of the input file is a new student or a course that will be added to the current student. If the line contains a new student, you need to create a new student object using your Student class. Otherwise, you need to add a new course, using your course class, to add to a student's list of classes. Once you have parsed the whole file, you can then loop through the list of students and the list of courses that each student has.
Phase1 Class:
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Phase1 {
public static void main(String[] args) throws FileNotFoundException {
Scanner file = new Scanner(new FileReader("data.txt"));
ArrayList<Student> students = new ArrayList<Student>();
int currStudent = -1;
while(file.hasNextLine()) {
String line = file.nextLine();
String[] split = new String[3];
//Parse the line input, check if a course name has a comma (it has a comma if it is in quotation marks), otherwise proceed normally
if(line.indexOf('"') == -1) {
split = line.split(",");
} else {
split[0] = line.substring(line.indexOf('"')+1, line.lastIndexOf('"'));
split[1] = line.substring(line.lastIndexOf('"')+2, line.lastIndexOf(','));
split[2] = line.substring(line.lastIndexOf(',')+1,line.length());
}
//If the line contains a new student, create the student
if(split[0].contains("Student")) {
students.add(new Student(split[0],new ArrayList<Course>()));
currStudent++;
continue;
}
//Add course to the current student
students.get(currStudent).addCourse(split[0], split[1].charAt(0), Double.parseDouble(split[2]));
}
//Print all students
for(Student s : students) {
System.out.println(s.getName() + ": " + s.getCourses().size());
//Print all courses for each student
for(Course c : s.getCourses()) {
System.out.println(c.getTitle());
}
System.out.println();
}
file.close();
}
}
Course Class (Same as yours above):
public class Course
{
private char grade;
private double credit;
private String title;
public Course() {
title = "";
grade = 'I';
credit = 0;
}
public Course(String title, char grade, double credit) {
this.title= title;
this.grade = grade;
this.credit = credit;
}
public String getTitle() {
return title;
}
public char getGrade() {
return grade;
}
public double getCredit() {
return credit;
}
public String toString() {
return title + " " + grade + " " + credit;
}
}
Student Class (Slightly modified - Changed setCourses to addCourse):
import java.util.*;
public class Student {
private String name;
private ArrayList<Course> courses;
public Student() {
name = null;
courses = null;
}
public Student(String name, ArrayList<Course> courses) {
this.name = name;
this.courses = courses;
}
public void setName(String name) {
this.name = name;
}
public void addCourse(String title, char grade, double credit) {
this.courses.add(new Course(title,grade,credit));
}
public String getName() {
return name;
}
public ArrayList<Course> getCourses() {
return courses;
}
}
Let me know if you have any questions about understanding the code!

Why is there multiple output when I call from an arraylist?

import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}

Java Eclipse: My code's output is skipping a line and I don't know why [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
The title says it all. This is a basic Customer class that the user inputs their name/age/street address/city/state/zip code and then the program formats the input and returns it to the user. When I run this class it skips over the 'Street Address' and goes straight to 'City' and thus I can't get it to let me input my street address.
I've looked at a fairly similar issue in this thread here: Java is skipping a line (Strings in a Scanner ??)
However I haven't derived anything from that that has helped me solve this issue. I'm sure its extremely basic but I'm just unable to catch it and don't have much time to work on this today, so any tips/help are appreciated!
public class Customer {
String name;
String streetAddress;
String city;
String state;
String zip;
int age;
//default constructor
public Customer() {
name = "Unknown";
streetAddress = "Unknown";
city = "Unknown";
state = "Unknown";
zip = "Unknown";
age = 0;
}
//constructor to accept values for the above attributes
public Customer(String n, String sAdd, String c, String st8, String z, int a) {
name = n;
streetAddress = sAdd;
city = c;
state = st8;
zip = z;
age = a;
}
//getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String displayAddress() { //returns a string with the complete formatted address
String showAddress;
showAddress = ("\nStreet Address: " + streetAddress + "\nCity: " + city + "\nState: " + state + "\nZip Code: " + zip);
return showAddress;
}
public String displayAddressLabel() { //returns a string with the customers name/age
String nameAgeAddress;
nameAgeAddress = ("Name: " + name + "\nAge: " + age);
return nameAgeAddress;
}
//main method
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//creating an object of the Customer class
Customer actualCustomer = new Customer();
//getting info for displayAddressLabel() and displayAddress
System.out.println("Enter your name: ");
actualCustomer.setName(scan.nextLine());
System.out.println("Enter your age: ");
actualCustomer.setAge(scan.nextInt());
//issue is here
System.out.println("Enter your street address: ");
actualCustomer.setStreetAddress(scan.nextLine());
System.out.println("Enter the city you live in: ");
actualCustomer.setCity(scan.nextLine());
System.out.println("Enter the state you live in: ");
actualCustomer.setState(scan.nextLine());
System.out.println("Enter your zip code: ");
actualCustomer.setZip(scan.nextLine());
System.out.println(actualCustomer.displayAddressLabel());
System.out.println(actualCustomer.displayAddress());
}
}
After this line:
actualCustomer.setAge(scan.nextInt());
you should call:
scan.nextLine();
because after scan.nextInt() there is a new line character left to be read (after inputting int you press Enter to confirm your input and you're missing to read it from your Scanner). Instead of writing these two lines:
actualCustomer.setAge(scan.nextInt());
scan.nextLine();
You might want to change it to:
actualCustomer.setAge(Integer.parseInt(scan.nextLine()));
It will get rid of new line character.

Categories