my exercise is with collect soccer cards inside an arraylist.
inside my code I have to insert the methods: "add, search, remove, print and modify".
From input I must save all data of name of player, surname and country after that from output someone can ask me about player so i can tell it from code.
My problem is i can't add some thing from input and i don't know how to continue with another methods after input with Scanner.
MAIN:
package figurines;
import java.util.*;
public class Figurines {
public ArrayList<Giocatori> lista = new ArrayList<Giocatori>();
public static void main(String[] args) {
System.out.println("1 Penaldo 2 Pessi 3 Neymar 4 Buffon");
Scanner searchBar = new Scanner(System.in);
System.out.println("Inserisci I dati del giocatore");
String search = searchBar.nextLine().toUpperCase();
for (Giocatori liste : lista) {
if (liste.getCognome().equalsIgnoreCase(search)) {
System.out.println(" Nome = " + liste.getNome() +" Paese= " + liste.getPaese());
}
}
}
}
CLASS WHERE I CAN ADD METHODS
package figurines;
import java.util.*;
public class Gestione {
public void input(){
ArrayList<Giocatori> list = new ArrayList<Giocatori>();
Scanner tastiera = new Scanner(System.in);
System.out.println("Inserisci il nome del giocatore: ");
String name;
String surname;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter first name: ");
name = input.nextLine();
System.out.println("Please Enter last name: ");
surname = input.nextLine();
}
}
SOME ARRAY METHODS:
package figurines;
import java.util.*;
public class Giocatori {
private String nome;
private String cognome;
private String paese;
public Giocatori(String nome, String cognome, String paese) {
this.nome = nome;
this.cognome = cognome;
this.paese = paese;
}
public String getNome() {
return nome;
}
public String getCognome() {
return cognome;
}
public String getPaese() {
return paese;
}
}
Well, your classes Gestione and Figurines don't make much sense. Why would you have List of players in your Figurines class? These are basics and you should know, how to make classes and functions.
This is my recommended implementation of Gestione class:
public class Gestione {
private List<Giocatori> list = new ArrayList<>();
public void add(Giocatori giocatori) {
list.add(giocatori);
}
public Giocatori search(String cognome) {
// search by surname
for (Giocatori g : list) {
if (g.getCognome().equals(cognome)) return g;
}
return null;
}
public void remove(Giocatori giocatori) {
list.remove(giocatori);
}
public void print() {
for (Giocatori g : list) {
System.out.println(g);
// create toString method in Giocatori
}
}
public void modify() {
// I don't know what modify should do
}
public List<Giocatori> getList() {
return list;
}
}
Related
import java.util.Arrays;
import java.util.Scanner;
public class employee{
public String name;
public class employee_address{
String street_name;
String city;
String zipcode;
String state;
String country;
}
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt();
employee[] employees_list = new employee[no_of_employees];
for(int i = 0;i < no_of_employees;i++){
employees_list[i].name = user_input.nextLine();
employees_list[I].employee_address = // this is it ?
}
}
}
In the code above I do understand that the employee_address is a class and can't be accessed
directly without an instance being created like in the code, that makes no sense. but how can I create an instance of the employee_address class that is associate with each employee.
like in the code above 'employee_address' is associated with every employee but how can the class 'employee_address' be initialised and how can I set the street_name, city and the rest of the members in the address class. any ideas would be appreciated.
You can't directly create an instance of inner class, the reason because since it is the property of another instance we always need to use it though the instance of parent variable.
Let's say you have a class, which have two propeties:
public class Employee {
public String name;
public EmployeeAddress emAddress;
}
to access emAddress you need to use through the instance of Employee class, for example -
Employee object = new Employee();
EmployeeAddress empAdd = object.new EmployeeAddress();
Full code:
public class Employee {
public String name;
public EmployeeAddress emAddress;
public class EmployeeAddress {
String street_name;
String city;
String zipcode;
String state;
String country;
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "EmployeeAddress [street_name=" + street_name + ", city=" + city + ", zipcode=" + zipcode
+ ", state=" + state + ", country=" + country + "]";
}
}
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt(); // let's say no_of_employees = 1
Employee[] employees = new Employee[no_of_employees];
for (int i = 0; i < no_of_employees; i++) {
Employee object = new Employee();
object.setName("Virat Kohli");
EmployeeAddress empAdd = object.new EmployeeAddress();
empAdd.setCity("New Delhi");
empAdd.setCountry("India");
empAdd.setState("Delhi");
empAdd.setStreet_name("Chandni Chalk");
empAdd.setZipcode("741124");
object.setEmAddress(emAddress);
employees[i] = object;
}
System.out.println(employees[0]);
user_input.close();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeAddress getEmAddress() {
return emAddress;
}
#Override
public String toString() {
return "Employee [name=" + name + ", emAddress=" + emAddress + "]";
}
public void setEmAddress(EmployeeAddress emAddress) {
this.emAddress = emAddress;
}
}
I have modified your code to sonar standard.
Below code uses Java naming conventions (which your code does not).
Notes after the code.
import java.util.Scanner;
public class Employee {
private String name;
private EmployeeAddress address;
public class EmployeeAddress {
String streetName;
String city;
String zipcode;
String state;
String country;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int noOfEmployees = userInput.nextInt();
Employee[] employeesList = new Employee[noOfEmployees];
for (int i = 0; i < noOfEmployees; i++) {
employeesList[i] = new Employee();
employeesList[i].name = userInput.nextLine();
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
employeesList[i].address = employeeAddress;
employeesList[i].address.streetName = userInput.nextLine();
}
}
}
An inner class is a normal class. It is not a member of its enclosing class. If you want class Employee to have an [employee] address, as well as a [employee] name, you need to add another member variable to class Employee whose type is EmployeeAdress.
Employee[] employeesList = new Employee[noOfEmployees];
The above line creates an array but every element in the array is null. Hence you need to first create a Employee object and assign it to an element of the array. Hence the following line in my code, above:
employeesList[i] = new Employee();
Since EmployeeAddress is not a static class, in order to create a new instance, you first need an instance of the enclosing class, i.e. Employee. Hence the following line in the above code.
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
Since all your code is in class Employee, in method main you can directly access the members of both class Employee and EmployeeAddress. Nonetheless you need to be aware of the different access modifiers in java.
A few hints:
stick to naming conventions: class names in Java start with capital letters
use (class) definitions before using them (collect them at the top if not inconventient)
if you are sure you want to use inner classes, set them static, unless you want them to be entangled in generics.
Usually normal classes in each their own file are a lot more flexible and far easier to use
if you use objects that only carry public data, try to use final keyword and initialize them ASAP
use proper objects first, and after finishing them assign them to arrays. avan better would be the use of ArrayList and the like
if Employee contains EmployeeAddress, it should initialize it if conventient. so an object is always responsible for its own stuff
Use try/resrouce/catch
scanner.nextInt() can be problematic with newline/line breaks. For user input better readLine() and parse input
Code:
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
static public class EmployeeAddress {
public final String street_name;
public final String city;
public final String zipcode;
public final String state;
public final String country;
public EmployeeAddress(final Scanner pScanner, final PrintStream pOutPS) {
street_name = readLine(pScanner, pOutPS, "Please enter Street Name:");
city = readLine(pScanner, pOutPS, "Please enter City Name:");
zipcode = readLine(pScanner, pOutPS, "Please enter Zip Code:");
state = readLine(pScanner, pOutPS, "Please enter State:");
country = readLine(pScanner, pOutPS, "Please enter Country:");
}
}
static public String readLine(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
pOutPS.print(pPrompt);
final String value = pScanner.nextLine();
pOutPS.println();
return value;
}
static public int readInt(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
return Integer.parseInt(readLine(pScanner, pOutPS, pPrompt));
}
public final String name;
public final EmployeeAddress address;
public Employee(final Scanner pScanner, final PrintStream pOutPS) {
name = readLine(pScanner, pOutPS, "Please enter Employee Name: ");
System.out.println("Name: " + name);
address = new EmployeeAddress(pScanner, pOutPS);
}
public static void main(final String[] args) {
try (final Scanner user_input = new Scanner(System.in);
final PrintStream output = System.out;) {
final int no_of_employees = readInt(user_input, output, "Please enter number of users: ");
final Employee[] employees_list = new Employee[no_of_employees]; // either this line
final ArrayList<Employee> employees = new ArrayList<>(); // or this line
for (int i = 0; i < no_of_employees; i++) {
output.println("Creating user #" + (i + 1) + "...");
final Employee newEmployeeWithAddress = new Employee(user_input, output);
employees_list[i] = newEmployeeWithAddress; // either this line
employees.add(newEmployeeWithAddress); // or this line
}
}
}
}
I wish to add objects to an arrayList until user inputs "no" in a Do While loop, I can't make it work, this is what I have so far:
ArrayList<Humano> lista = new ArrayList<>();
Scanner input = new Scanner(System.in);
do {
Humano h = new Humano();
System.out.println("Name");
h.setNombre(input.nextLine());
System.out.println("Age");
h.setEdad(input.nextInt());
lista.add(h);
System.out.println("wish to continue?");
} while ();//user inputs "no"
Class, attributes, setters and getters.
public class Humano {
private String nombre;
private int edad;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getEdad() {
return edad;
}
public void setEdad(int edad) {
this.edad = edad;
}
}
Try this
import java.util.Scanner;
import java.util.*;
public class Test
{
public static void main(String []args){
ArrayList lista = new ArrayList();
Scanner input = new Scanner(System.in);
String userInput;
do {
System.out.println("Name");
lista.add(input.nextLine());
System.out.println("SurName");
lista.add(input.nextLine());
System.out.println("wish to continue?");
userInput = input.nextLine();
System.out.println("your input is " + userInput);
} while (!userInput.equalsIgnoreCase("NO"));
//whether user types "no" or "No" or "nO" or "NO", it will consider all cases.
}
}
I'm new at java so sorry for the inconsistencies.
I'm creating a library program and I'm having trouble calling a method from the Book class in the Patron class.
In the Patron class I have a method checkOutBook() which a user can input a book to check out. However I'm having trouble accessing the setStatus() method in Book. I know I have to call it against an instance of the Book class but I'm unsure how to do so with a user inputed string.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Book implements BookInterface {
Scanner input = new Scanner(System.in);
static ArrayList < String > UserList = new ArrayList < String > ();
static ArrayList < String > BookList = new ArrayList < String > ();
public String title;
public String author;
public Book book;
private String status;
private String borrower;
public Book(String t, String a) {
title = t;
author = a;
}
//constructor create new book
public Book(String newTitle) {
title = newTitle;
}
public String toString() {
return title + " " + author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getStatus(String book) {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setBorrower(String borrower) {
this.borrower = borrower;
}
public String getBorrower(String checkPatron) {
return borrower;
}
public String getBook(String checkPatron) {
return book;
}
public void setBook(Book bookCheckOut) {
this.book = bookCheckOut;
}
}
public void CheckOutBook() {
Scanner inputread = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Enter full patron name: ");
String borrower = inputread.nextLine();
System.out.println("Enter book title to check out: ");
String bookCheckOut = inputread.nextLine();
if (Book.BookList.contains(bookCheckOut)) {
Book.BookList.remove(bookCheckOut);
Book.setStatus("OUT"); //error message
Book.setBorrower(borrower); //error message
System.out.println("----------" + bookCheckOut + " has been checked out!----------");
System.out.println("-------------------BOOK STATUS:---------------------");
System.out.println("Book Title: " + bookCheckOut);
System.out.println("Book Status: Checked out");
System.out.println("Borrower: " + borrower);
System.out.println("Due Date: " + dueDate);
System.out.println("----------------------------------------------------");
I attempted to do this but it didn't work either :(
Thank you for your help!
Book bookCheckOut = new Book(bookCheckOut); //error: constructor Book(book) undefined
bookCheckOut.setStatus("OUT");
bookCheckOut.setBorrower(borrower);
bookCheckOut.setBook(bookCheckOut);
Book bookCheckOut = new Book(bookCheckOut); <~ I think you are getting confused because you already defined bookCheckOut as a String from the scanner and in this line you are setting it to a book object. Try changing the first bookCheckOut in this line to something else. Syntax: Book bookObjectName = new Book("String");
For the setStatus and setBorrower error you are trying to use those methods as if they were static. To fix this don't call Book.setStatus but replace Book with your instantiated book object name. Example: Book b = new Book ("Asd","abc"); b.setStatus("xyz");
Also, why do have two scanners?
Change Book.BookList from ArrayList<String> to Map<String, Book> as shown below:
public class Book {
static Map<String, Book> BookList = new HashMap<>();
...
Then in CheckOutBook() change:
if (Book.BookList.contains(bookCheckOut)) {
Book.BookList.remove(bookCheckOut);
Book.setStatus("OUT"); //error message
Book.setBorrower(borrower); //error message
...
To:
Book book = Book.BookList.get(bookCheckOut);
if (book != null) {
Book.BookList.remove(bookCheckOut);
book.setStatus("OUT");
book.setBorrower(borrower);
...
I tried to create ArrayList with Ingredients object and then iterate through this list but this is only showing the last added ingredient. For example when I'm adding two ingredients (mushrooms, tomatoes) in arrayList are only tomatoes with index 0 and 1.
import java.util.ArrayList;
import java.util.List;
public class Ingredients {
private String ingredientName;
private int ingriedientQuantity;
List<Ingredients> ingredients;
public Ingredients() {
this.ingredients = new ArrayList<>();
}
public void addIngredient(Ingredients ingredient) {
ingredients.add(ingredient);
}
public String getIngredientName() {
return ingredientName;
}
public void setIngredientName(String ingredientName) {
this.ingredientName = ingredientName;
}
public int getIngriedientQuantity() {
return ingriedientQuantity;
}
public void setIngriedientQuantity(int ingriedientQuantity) {
this.ingriedientQuantity = ingriedientQuantity;
}
public void showIngredients() {
for (Ingredients ingredientI : ingredients) {
System.out.println(ingredientI.getIngredientName() + " " + ingredientI.getIngriedientQuantity());
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Ingredients ing = null;
boolean exitFlag = false;
String name;
int quantity;
int option = 0;
String o;
while (!exitFlag) {
System.out.println("1 - Add");
System.out.println("2 - Show");
System.out.println("3 - Exit");
option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
ing = new Ingredients();
do {
System.out.println("Product name: ");
name = sc.nextLine();
ing.setIngredientName(name);
System.out.println("Quantity");
quantity = sc.nextInt();
sc.nextLine();
ing.setIngriedientQuantity(quantity);
System.out.println("Add more? Y/N");
o = sc.nextLine();
ing.addIngredient(ing);
} while (!o.equalsIgnoreCase("N"));
break;
case 2:
ing.showIngredients();
break;
case 3:
exitFlag = true;
break;
default:
System.out.println("Error");
break;
}
}
sc.close();
}
}
Is better way to do it?
Your class design is wrong. Create a separate class Ingredient with properties IngredientName and IngredientQuantity. The Ingredients class maintains an ArrayList for Ingredient objects.
A sample Ingredient class may look like:
import java.util.ArrayList;
import java.util.List;
public class Ingredient {
private String ingredientName;
private int ingriedientQuantity;
public Ingredient() {
}
public String getIngredientName() {
return ingredientName;
}
public void setIngredientName(String ingredientName) {
this.ingredientName = ingredientName;
}
public int getIngriedientQuantity() {
return ingriedientQuantity;
}
public void setIngriedientQuantity(int ingriedientQuantity) {
this.ingriedientQuantity = ingriedientQuantity;
}
}
Your Ingredients can be implemented as:
import java.util.ArrayList;
import java.util.List;
public class Ingredients {
List<Ingredient> ingredients;
public Ingredients() {
this.ingredients = new ArrayList<Ingredient>();
}
public void addIngredient(Ingredient ingredient) {
ingredients.add(ingredient);
}
public void showIngredients() {
for (Ingredient ingredientI : ingredients) {
System.out.println(ingredientI.getIngredientName() + " " + ingredientI.getIngriedientQuantity());
}
}
}
I would personnaly create a "Recipe" Class as follow :
public class Recipe {
private List<Ingredients> ingredients;
+ getters and setters
}
Then change a little bit your ingredient class :
public class Ingredient {
private String ingredientName;
private int ingredientQuantity;
...
}
Then in your main method create a Recipe at the beginning, and then in your while loop create a new instance of Ingredient each time and add it to your recipe.
So, I've got to write an invoice for a video store that has a Customer class which takes six attributes, the customer name (string), the street address (string), the city(String), the state(string), the zip code(string), and the telephone number. I had to use a parameterized constructor that receives the attributes as parameters as well as provide getters and setters. I believe I did this correctly.
Next I had to make a Video class that had four attributes, the video name (string), the year the video was released(integer), the video copy number(integer), and the daily rental rate(double). I had to do a parameterized constructor and getters and setters for this as well.
The problems start on my Invoice class which is to represent the rental of a video to a given customer, it is not finished, but is supposed to have four attributes, the customer renting the video, the video being rented, the date it was rented(as a inputted string), and the daily rental rate(double). It was also supposed to have three methods, the subtotal, the tax and the total. My problem is I've got the preset methods for the customers and the videos setup, I just have no clue how to effectively use them in an if statement. I don't know what I would put in my fourth test class to allow this to work. I am all but lost at this point, any push in the right direction would be greatly appreciated. here are my classes.
Customer:
public class Customer {
private String customerName;
private String streetAddress;
private String custCity;
private String custState;
private String custZip;
private String custPhone;
public Customer(String customerName, String streetAddress, String custCity, String custState, String custZip,
String custPhone) {
super();
this.customerName = customerName;
this.streetAddress = streetAddress;
this.custCity = custCity;
this.custState = custState;
this.custZip = custZip;
this.custPhone = custPhone;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCustCity() {
return custCity;
}
public void setCustCity(String custCity) {
this.custCity = custCity;
}
public String getCustState() {
return custState;
}
public void setCustState(String custState) {
this.custState = custState;
}
public String getCustZip() {
return custZip;
}
public void setCustZip(String custZip) {
this.custZip = custZip;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
}
Video:
public class Video {
private String videoName;
private int videoYear;
private int copyNum;
private double rentalRate;
public Video(String videoName, int videoYear, int copyNum, double rentalRate) {
super();
this.videoName = videoName;
this.videoYear = videoYear;
this.copyNum = copyNum;
this.rentalRate = rentalRate;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public int getVideoYear() {
return videoYear;
}
public void setVideoYear(int videoYear) {
this.videoYear = videoYear;
}
public int getCopyNum() {
return copyNum;
}
public void setCopyNum(int copyNum) {
this.copyNum = copyNum;
}
public double getRentalRate() {
return rentalRate;
}
public void setRentalRate(double rentalRate) {
this.rentalRate = rentalRate;
}
Invoice (incomplete) :
import java.util.Scanner;
public class Invoice {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Customer Brandon = new Customer("Brandon James" , "112 Oak Street"
, "CityVille" , "Alabama" , "18229",
"912-2248");
Customer Judy = new Customer("Judy Vermooth" , "8008 Ribbit Ln.",
"Metropolis" , "Pennsylvania" , "24057", "241-8009");
Video Easter = new Video("Easter 2", 2002, 4, 2.49);
Video DareDevil3 = new Video ("Dare Devil 3", 2012, 2, 3.62);
if( Prog4.newRental = "Brandon"){
Customer Brandon = newCust
}
}
}
Prog4(incomplete):
import java.util.*;
public class Prog4 {
private String newRental;
private String vidName;
private String rentalDate;
private String daysRented;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter Customer Name: ");
String newRental = in.nextLine();
System.out.println("Enter Video Name: ");
String vidName = in.nextLine();
System.out.println("Enter Rental date in mm/dd/yyyy format: ");
String rentalDate = in.nextLine();
System.out.println("Enter Number of Days Rented");
int daysRented = in.nextInt();
}
public String getNewRental() {
return newRental;
}
public void setNewRental(String newRental) {
this.newRental = newRental;
}
public String getVidName() {
return vidName;
}
public void setVidName(String vidName) {
this.vidName = vidName;
}
public String getRentalDate() {
return rentalDate;
}
public void setRentalDate(String rentalDate) {
this.rentalDate = rentalDate;
}
public String getDaysRented() {
return daysRented;
}
public void setDaysRented(String daysRented) {
this.daysRented = daysRented;
}
}