For loop with user input whilst encapsulating in Java - java

I want to use a for loop to ask the user for the title, genre and rating of 3 movies and store the information in an array and then display the information back to them. The instance variables are private and getters and setters are used but I don't know how use the getters and setters in the MovieTestDriver class whilst trying to use a for loop to get information.
class Movie {
// Create instance variables for the Movie class.
private String title;
private String genre;
private int rating;
// Use getters and setters to set and display the variables.
// Getters.
public String getTitle() {
return title;
}
public String getGenre() {
return genre;
}
public int getRating() {
return rating;
}
// Setters.
public void setTitle(String newTitle) {
title = newTitle;
}
public void setGenre(String newGenre) {
genre = newGenre;
}
public void setRating(int newRating) {
rating = newRating;
}
void playIt() {
System.out.println(getTitle() + "- Now Playing!");
}
}
import java.util.Scanner;
public class MovieTestDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Creates a Movie array of size 3.
Movie[] movies = new Movie[3];
String getTitle;
String getGenre;
int getRating;
// Allows user to enter variables 3 times and populate movie object and store them in an array.
for (int i=0; i< movies.length; i++) {
System.out.println("Please enter the title of Movie " + (i+1));
getTitle = input.nextLine();
System.out.println("Please enter the genre of Movie " + (i+1));
getGenre = input.nextLine();
System.out.println("Please enter the rating (1-5) of Movie " + (i+1));
getRaing = input.nextInt();
}
}

Use another method to create a movie instance. And mayby another to display the movie:) That way your code will be clean and readable.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Creates a Movie array of size 3.
Movie[] movies = new Movie[3];
// Allows user to enter variables 3 times and populate movie object and store them in an array.
for (int i=0; i< movies.length; i++) {
movies[i] = inputMovie(input);
}
}
private static Movie inputMovie(Scanner input){
Movie movie = new Movie();
System.out.println("Please enter the title of Movie " + (i+1));
movie.setTitle(input.nextLine());
System.out.println("Please enter the genre of Movie " + (i+1));
movie.setGenre(input.nextLine());
System.out.println("Please enter the rating (1-5) of Movie " + (i+1));
movie.setRating(input.nextInt());
return movie;
}

Related

i need help seperate this main method to a class

I have this movie ticket program, which I want to have a class so it becomes a main method and a class and it's aching my mind .
import java.util.Scanner;
public class MovieTicket {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String[] movielist ={"1) Shutter Island","2) Devil's Advocate","3) Pulp Fiction","4) Resvouar Dogs"};
Ticket obj=new Ticket();
System.out.println("Welcome to Vox Cinemas");
System.out.println("Please ,Selcet a movie please");
for (int i =0; i<movielist.length;i++){
System.out.println(movielist[i]);
}
int number = sc.nextInt();
System.out.println("The movie you selected is:"+" "+movielist[number-1]);
System.out.println("How many seats would you lie:");
String seats = sc.next();
System.out.println("You've selected:"+seats+"Seats");
}
}
You need to create separate classes for Theatre, Movie, Ticket etc.
Something like below.
class Movie{
private String name;
private int runtime;
//add other fields like producer/actors/genre
public Movie(String name, int runtime) {
this.name = name;
this.runtime = runtime;
}
public String getName() {
return name;
}
public int getRuntime() {
return runtime;
}
}
class Ticket{
private int number;
private Movie movie;
private String screen; //Screen 1
private String seat; //A14
public Ticket(int number, Movie movie, String screen, String seat) {
//.. initiate variables here.
}
//write getters here
}
class VoxCinema{
private List<Movie> movies = new ArrayList<>();
private String address;
//theater details like name/timings etc.
public VoxCinema() {
}
public void addMovie(Movie movie) {
this.movies.add(movie);
}
public List<Movie> getAllMovies() {
return this.movies;
}
//write getters and setters
}
Then use them in your application like this:
public class TicketBookingApplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
VoxCinema vc = new VoxCinema();
vc.addMovie(new Movie("Shutter Island", 130));
vc.addMovie(new Movie("Devil's Advocate", 180));
/// add all movies
System.out.println("Welcome to Vox Cinemas");
System.out.println("Please ,Selcet a movie please");
List<Movie> movies = vc.getAllMovies();
for (int i = 0; i < movies.size(); i++) {
System.out.println(i + ") " + movies.get(i).getName());
}
int number = sc.nextInt();
Movie selectedMovie = movies.get(number);
System.out.println("The movie you selected is: " + selectedMovie.getName());
System.out.println("How many seats would you lie:");
String seats = sc.next();
System.out.println("You've selected:" + seats + "Seats");
// create tickets
Ticket t = new Ticket(3341, selectedMovie, "Screen 4", "D15");
//store tickets in VoxCinema object
}
}
Implement remaining parts or modify code as per your needs.

How do i take user input and store it successfully in an ArrayList? Then how do i get my program to show me all the elements in the ArrayList?

I want a program that stores details about staff in an arraylist. I'd like to prompt user for input and store each result in the arraylist. How do I do this? And how do i view everything stored in the arraylist after?
It doesn't need to reflect the code I have, just can't seem to figure out how i have a class with setters and getters and then create a new main class promting user for input and store that input in the arraylist.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class salesPersonMain {
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
//ask user for input and get input
System.out.println("Enter id: ");
int id = Integer.parseInt(input.nextLine());
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
List<salesPerson> sPerson = new ArrayList<salesPerson>();
sPerson.add(new salesPerson(id, firstName, lastName));
}
}
I have another class for the salesperson:
import java.util.ArrayList;
public class salesPerson<sPerson> {
//create variables for sales person
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) throws InputValidationException {
if (firstName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName)throws InputValidationException {
if (lastName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.lastName = lastName;
}
}
//creates array of salespeople
private ArrayList<sPerson> salesPerson;
public salesPerson() {
salesPerson = new ArrayList<>();
}
//adds new salesperson to the array
public void add(salesPerson sPerson) {
salesPerson.add((sPerson) sPerson);
}
You'll need a loop to repeatedly get the input:
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
List<salesPerson> sPerson = new ArrayList<salesPerson>();
// Loop forever
// Need a way to break the loop. One option: have the user
// input "q" for quit
while (true) {
//ask user for input and get input
System.out.println("Enter id ('q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
// This should be in try/catch in case parseInt fails
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
sPerson.add(new salesPerson(id, firstName, lastName));
}
// Print the list
sPerson.forEach(System.out::println);
}
So it prints out properly, you need to override the toString function in the salesPerson class:
public class salesPerson {
// Other code here.....
#Override
public String toString() {
return id + "," + firstName + " " + lastName;
}
}

Finding Percentages of elements inside an ArrayList<model>

So I am doing a project which I want to built a library with two ArrayLists one of the ArrayList'<'Book'>' BookList contains an element named quantity has to greater or equivalent to zero if the quantity of the book is above zero another element called status in the BookList is set to In-stock if it's equal to zero it's set to borrowed. I'm trying to create a method that looks at the BookList and shows the percentage of books that are borrowed. I have done this by going through the list and each time it finds a book with quantity below 1 in other words 0 the counter goes up by one so in the end I just substract the counter from the BookList.size(), divide the result with the BookList.size(), multiply it by 100 and fially print it.
Main Class
public class Main {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
int uinput;
Library nag;
try{
nag = new Library();
do{
System.out.println("Type 1 to add a book.");
System.out.println("Type 2 to show how many books are borrowed.");
uinput = keyb.nextInt();
if (uinput==1){
nag.addBook();
}
if (uinput==2){
nag.statistics();
}
}while (uinput > 0);
}
catch(Exception e){
System.out.println("Invalid entry.");
}
}//end of main
}//end of class
Book Class
public class Book {
private String Title;
private String Author;
private String ISBN;
private String Publisher;
private String Publication_Date;
private String Price;
private int Quantity;
private String Status;
public Book(){
Title= "";
Author="";
ISBN="";
Publisher="";
Publication_Date="";
Price="";
Quantity=1;
Status="IN-STOCK";
}
//getters
public String gettitle(){return Title;}
public String getauthor(){return Author;}
public String getisbn(){return ISBN;}
public String getpublisher(){return Publisher;}
public String getpublication_date(){return Publication_Date;}
public String getprice(){return Price;}
public int getquantity(){return Quantity;}
public String getstatus(){return Status;}
//setters
public void settitle(String t){Title = t;}
public void setauthor(String a){Author = a;}
public void setisbn(String is){ISBN = is;}
public void setpublisher(String p){Publisher = p;}
public void setpublication_date(String pd){Publication_Date = pd;}
public void setprice(String pr){Price = pr;}
public void setquantity(int q){Quantity = q;}
public void setstatus(String s){Status = s;}
}//end of class
Library Class
public class Library {
private ArrayList<Book> BookList;
public Library(){
BookList = new ArrayList<Book>();
}//end of constructor 1
public Library(ArrayList<Book> l) {
BookList = l;
}//end of constructor 3
public void addBook(){
try{
Scanner keyb = new Scanner(System.in);
Book bo = new Book();
System.out.println("Type the title: ");
String title_input;
title_input = keyb.nextLine();
bo.settitle(title_input);
System.out.println("Type the author: ");
String author_input;
author_input = keyb.nextLine();
bo.setauthor(author_input);
System.out.println("Type the isbn: ");
String isbn_input;
isbn_input = keyb.nextLine();
bo.setisbn(isbn_input);
System.out.println("Type the publisher: ");
String publisher_input;
publisher_input = keyb.nextLine();
bo.setpublisher(publisher_input);
System.out.println("Type the publication date: ");
String publication_date_input;
publication_date_input = keyb.nextLine();
bo.setpublication_date(publication_date_input);
System.out.println("Type the price: ");
String price_input;
price_input = keyb.nextLine();
bo.setprice(price_input);
System.out.println("Type the quantity: ");
int quantity_input = Integer.parseInt(keyb.nextLine());
if (quantity_input >= 0){
bo.setquantity(quantity_input);
if (quantity_input > 0){
bo.setstatus("IN_STOCK");
}
if(quantity_input == 0){
bo.setstatus("BORROWED");
}
BookList.add(bo);
System.out.println("Book added successfully.");
}
}catch(Exception e){
System.out.println("Invalid entry");
}//end of addBook()
public void statistics(){
Book bo = new Book();
int counter = 0;
for(int i=0; i < BookList.size();i++){
bo= BookList.get(i);
int holdquantity = bo.getquantity();
if (holdquantity < 1){
counter++;
}
}
double substraction=BookList.size() - counter;
double division= substraction/BookList.size();
double percentage = division * 100;
System.out.print(percentage + "%");
}//end of statistics()
}//end of class
The problem is that it keeps printing 100.0% when I have a book with quantity of zero and another book with quantity above zero.
So I wanted to know if the problem lies within this code or elsewhere.
Let's say your Book class is as follows:
package com.company;
public class Book {
private int quantity;
public Book(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
And your Main is as follows:
package com.company;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main (String[]args) {
List<Book> bookList = new ArrayList<>(){{
add(new Book(4));
add(new Book(0));
add(new Book(3));
add(new Book(7));
add(new Book(0));
add(new Book(0));
add(new Book(1));
add(new Book(9));
add(new Book(0));
add(new Book(5));
}};
int booksOutOfStock = 0;
for (int i = 0; i < bookList.size(); i++) {
if (bookList.get(i).getQuantity() == 0)
booksOutOfStock++;
}
double percentage = 100d / bookList.size() * booksOutOfStock;
System.out.printf("Out of total %d books, %d are out of stock, which makes %.2f%%", bookList.size(), booksOutOfStock,
percentage);
}
}
So check this code, compare it to yours and see where could the error be, or post complete code here so we can help more.
Output of code above:
Out of total 10 books, 4 are out of stock, which makes 40.00%
OK, so after you posted your code I reviewed it, and apart from doing some things the hard way, your code is "working", all I had to do was add a closing brace in Library class at the end of addBook() method after catch block:
catch(Exception e){
System.out.println("Invalid entry");
} --> } <--- (added)
//end of addBook()
And I fixed your percentage code logic, you code would print out the number of non borrowed books as borrowed percentage, here is that code changed:
double division= (double)counter/BookList.size();
double percentage = division * 100;
System.out.printf("%.2f", percentage);

How to add an integer to my arraylist?

I currently have my code set up so a student's name and subject is added to my arraylist, and then printed when user is done. How ever as I'm not wanting to add a string now, I want to add a student number, i'm unfamiliar with how to go about this. I have tried replacing set with add, and string with int, but to no prevail.
Here is my main code
import java.util.*;
public class StudentData
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
String yesNo = "true";
do
{
System.out.println("Enter student's name: ");
String name = in.next();
System.out.println("Enter student's subject: ");
String subject = in.next();
System.out.println("Enter student's number: ");
int number = in.nextInt();
Student s = new Student(name,subject,number);
s.setName(name);
s.setSubject(subject);
s.Number.add(number);
studentList.add(s);
do
{
System.out.println("Would you like to enter data for another student? Yes/No ");
yesNo = in.next();
}
while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
}
while (yesNo.equalsIgnoreCase("YES"));
for(int i = 0; i < studentList.size(); i++)
{
System.out.println(studentList.get(i).getName());
System.out.println(studentList.get(i).getSubject());
}
}
}
and
class Student
{
private String studentName;
private String studentSubject;
public Student(String name, String subject, int number )
{
setName(name);
setSubject(subject);
Number.add(number);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
public String getSubject()
{
return studentSubject;
}
public void setSubject(String subject)
{
studentSubject = subject;
}
public int getNumber()
{
return studentNumber;
}
public void Number.add(int number)
{
studentNumber = number;
}
}
As you are storing Student objects in your list you are also storing the member variables of each object as you entered them. So no different approach needs to be taken to store an integer.
You can declare your private int studentNumber; in your student class, add a getter and a setter for it and then modify your constructor so that setStudentNumber(number); would work in the same way as setting your two Strings up.
Then to iterate through your list you could make use of the 'enhanced-for' syntax instead of a plain old for loop, meaning:
for (Student s : studentList) {
System.out.println(s.getName());
System.out.println(s.getSubject());
System.out.println(s.getStudentNumber());
}
Hope that this helps, if you need anything more just give me a shout below.

Issue with a method for a library of objects

I'm trying to make a program that creates a library of different books, I have set a number of copies for each item in the library and every time I check out an Item I want it to deduct 1 copy from only the particular object I check out but instead it takes a copy away from all the objects. not sure how to fix the problem.
public abstract class Item{
private int identify;
private String title;
private int copies;
public Item(){
identify=0;
title="N/A";
copies=0;
}
public Item(int id, int copy, String t){
identify=id;
copies=copy;
title=t;
}
public void setIdentificationNumber(int id){
identify = id;
}
public void setTitle(String t){
title=t;
}
public void setNumberCopies(int num){
copies=num;
}
public int getIdentificationNumber(){
return identify;
}
public String getTitle(){
return title;
}
public int getNumberCopies(){
return copies;
}
public void checkOut(){
if(copies>0){
copies-=1;
System.out.println("You have checked out "+title+". Thank You");
}
else{
System.out.println("All copies of "+title+" are checked out!");
}
}
public void checkIn(){
copies+=1;
}
}
The problem may also be in my client method I have posted the code for that as well below.
import java.util.Arrays;
import java.util.Scanner;
public class Library{
static String title;
static String author;
static int id;
static int copies;
static String date;
static Book[] database = new Book[100];
static int count=0;
public static void main(String[] args){
int i;
Scanner s = new Scanner(System.in);
do{
addBook();
System.out.println("would you like to add another book?");
i=s.nextInt();
}while(i == 0);
database[0].viewDetails();
database[1].viewDetails();
checkingOut();
database[0].viewDetails();
database[1].viewDetails();
}
public static void addBook(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the book you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the author of the book you want to add to the collection");
author=s.nextLine();
System.out.println("Enter the publishing date of the book you want to add to the collection");
date=s.nextLine();
System.out.println("Enter the ID number of the book you want to add to the collection");
id=s.nextInt();
System.out.println("Enter the the number of copies that will be added into the collection");
copies=s.nextInt();
Book Book1 = new Book(date, author, copies, id, title);
database[count] = Book1;
count++;
}
public static void checkingOut(){
boolean found=false;
int idSearch;
int i=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the ID number of the book you want to check out");
idSearch=s.nextInt();
while(i<database.length && found!=true){
if(database[i].getIdentificationNumber() == idSearch){
found = true;
}
i++;
}
if(found==true){
database[i].checkOut();
System.out.println("There are "+database[i].getNumberCopies()+" copies left");
}
else{System.out.println("There is no book with that ID number!");}
}
}
In my addBook method I create a new object called book1 every time I make a new book, so I think that it may be changing all of the book objects every time I add a book. I'm not really sure of a better way to write the method.
here is my method for book also
public class Book extends WrittenItem{
public Book(){
super();
}
public Book(String date, String a, int copy, int id, String t){
super(a, date, copy, id, t);
}
public void viewDetails(){
System.out.println("ID: "+getIdentificationNumber()+"\nTitle: "+getTitle()+"\nAuthor: "+getAuthor()+" Date written: "+getDate()+"\nCopies available: "+getNumberCopies());
}
}
Any help would be greatly appreciated.
I can't 100% tell from your code, but I'm assuming Book extends Item. In that case, try something like this for Book constructor
public class Book extends Item {
String author;
String date;
public Book(String date, String author, int copies, int id, String title) {
super(id, copies, title); // Item constructor matches this super() call
// public Item(int id, int copy, String t)
this.author = author;
this.date = date;
}
}
You want Book to have the same copies at Item. So when you checkOut(), the Item number equals you input from the Book constructor. If you don't put the super() in the constructor, your Item copies will remain 0 and you will always get System.out.println("All copies of "+title+" are checked out!"); because copies is never > 0.
If your book is something like this,
public class Book extends Item {
private String date;
private String author;
public Book() {
}
public Book(String date, String author, int copies, int id, String title) {
super(id, copies, title);
this.author = author;
this.date = date;
}
void viewDetails() {
System.out.println("date:" + date + " author:" + author + " copies:" + getNumberCopies() + " id:" + getIdentificationNumber() + " title:" + getTitle());
}
}
Then your code should work fine, as i've tested, if you also add a break in your checkingOut() method,
public static void checkingOut() {
boolean found = false;
int idSearch;
int i = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the ID number of the book you want to check out");
idSearch = s.nextInt();
while (i < database.length && found != true) {
if (database[i].getIdentificationNumber() == idSearch) {
found = true;
break; //add this
}
i++;
}
if (found == true) {
database[i].checkOut();
System.out.println("There are " + database[i].getNumberCopies() + " copies left");
} else {
System.out.println("There is no book with that ID number!");
}
}

Categories

Resources