Adding objects to an arrayList, until the user inputs "no" - java

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.
}
}

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.

Exercise With arraylist input with scanner

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;
}
}

Eshop login screen in command line java

i am new to java and i need some help. I want to create a login screen in command line.I have a menu class where at first i want the user to choose if he wants to login, sign up or exit. I am in the sign up case, where he puts his email,password and his identity, which is either Buyer or Owner(they are subclasses of a User class both). Buyer and Owner are two classes of my java project. I have thought of making an extra class Person(subclass to User), with variables String email, int password, User identity and i thought when the user of the eshop writes "Buyer" at the identity variable, the identity becomes buyer, so i can add him to an arraylist
If someone thinks that i should do it differently, i am glad to hear it.
import java.util.ArrayList;
import java.util.Scanner;
public class Menu{
Eshop Eshop = null;
ArrayList<Item> itemsList = new ArrayList<>();
ArrayList<Buyer> buyersList = new ArrayList<>();
User buyer = null;
User Owner = null;
boolean exit;//false
/* public static void main(String[] args){
Menu menu = new Menu();
menu.runMenu();
}
TEMPORARY MAIN TO RUN THE METHODS OF MENU CLASS
*/
Menu()
{
}
Menu(Eshop Eshop, User owner, ArrayList<Item> itemslist, ArrayList<User> buyerslist){
this.Eshop=Eshop;
this.Owner=owner;
itemsList = itemslist;
buyersList = buyerslist;
}
public void runMenu(){
printHeader();
while(!exit){
printMenu();
int choice = getInput();
performAction(choice);
}
}
public int getInput(){
Scanner kb = new Scanner(System.in);
int choice=-1;
while(choice<1 || choice >3){
try{
System.out.print("\n\nEnter your choice:");
choice = Integer.parseInt(kb.nextLine());
}
catch(NumberFormatException e){
System.out.println("Invalid selection plz try again.");
}
}
return choice;
}
public void printHeader(){
System.out.println("+-------------------------------------------+");
System.out.println("| |");
System.out.println("| Welcome to our Eshop Menu |");//+Eshop.getname();
System.out.println("| |");
System.out.println("+-------------------------------------------+");
}
public void printMenu(){
System.out.println("\nPlease make a selection:");
System.out.println("1)Login ");
System.out.println("2)Sign up");
System.out.println("3)Exit!!!!");
}
public void enteremail()
{
Scanner keyboard = new Scanner(System.in);
Scanner codeboard = new Scanner(System.in);
Scanner identityboard = new Scanner(System.in);
String email=null,identity=null;
int code=0;
System.out.println("\n\nEnter your email:");
email=keyboard.nextLine();
System.out.println("\nEnter your code:");
code=codeboard.nextInt();
System.out.println("\nEnter what you are Buyer or Owner");
identity=identityboard.nextLine();
Person p1= new Person(email,code,identity);
if(identity.equals("Buyer"))
buyersList.add(p1);//HERE IS MY PROBLEM HOW I MAKE THE IDENTITY OF PERSON CLASS TO BUYER
}
private void performAction(int choice){
switch(choice){
case 3:
exit = true;
System.out.println("Sta tsakidia!!!");
case 2:
}
}
}//THIS IS THE MENU CLASS
import java.util.ArrayList;
import java.io.*;
public class Person extends User{
int password=0;
String identity;
ArrayList <Person> personList=new ArrayList<Person>();
Person(String email,int password,String identity)
{
this.email=email;
this.password=password;
this.identity=identity;
}
public void Register(Person a)
{
personList.add(a);
}
public void setemail(String email)
{
this.email=email;
}
public String getemail()
{
return email;
}
public void setpassword(int password)
{
this.password=password;
}
public int getpassword()
{
return password;
}
public void setidentity(String identity)
{
this.identity=identity;
}
public String getidentity()
{
return identity;
}
}// THIS IS THE PERSON CLASS
public class Owner extends User
{
private boolean isAdmin;
Owner(String name,String email)
{
this.name=name;
this.email=email;
this.isAdmin=true;
}
}//Owner class
import java.io.*;
public class Buyer extends User
{
private int bonus=0,distance=0;
private double transfercost=0;//metaforika
protected buyerCategory category;//katigoria
private int pointcounter=0;//pointer twn agorwn
enum buyerCategory//Enum gia tin katigoria
{
BRONZE, SILVER,GOLD
}
Buyer(String name, String email,int bonus, ShoppingCart cart,int distance)//DHMIOURGOS
{
this.name=name;
this.email=email;
this.bonus=bonus;
if(bonus>=0 && bonus<100)
category=buyerCategory.BRONZE;
else if(bonus>100 && bonus<200)
category=buyerCategory.SILVER;
else if(bonus<0)
throw new IllegalArgumentException("Bonus has to positive or 0");
else
category=buyerCategory.GOLD;
this.category=category;
if(distance>=0 && distance<10)
transfercost=5;
else if(distance>=10 && distance<100)
transfercost=10;
else if(distance>=100)
transfercost=25;
else
System.out.println("Prepei na baleis thetiko distance");//Thelei exception
/*if(category == buyerCategory.SILVER)
transfercost=transfercost/2;
if(category == buyerCategory.GOLD)
transfercost=0;
*/
}
public void setbuyerCategory(Buyer buyer)
{
int temp;
temp=buyer.getbonus();
if (temp>=0 && temp<100)
category= buyerCategory.BRONZE;
if (temp>100 && temp<200)
category= buyerCategory.SILVER;
//transfercost = transfercost/2;
if (temp>200)
category= buyerCategory.GOLD;
//transfercost = 0;
}
public void awardBonus(Buyer buyer,ShoppingCart cart)
{
cart.CountShoppingCart(cart);
System.out.println("H aksia tis paraggelias sou einai:\t"+cart.calculateNet());
int ten=(int) cart.calculateNet()/10;
/*if (cart.gettotalprice()>=20 && cart.gettotalprice()<50)
temp=buyer.getbonus()+20;
else if(cart.gettotalprice()>=50 && cart.gettotalprice()<100)
temp=buyer.getbonus()+50;
else if (cart.gettotalprice()>100)
temp=buyer.getbonus()+100;
else //ligotero apo 20
temp=buyer.getbonus()+0;
*/
int temp= buyer.getbonus()+ten;
setbonus(temp);
setbuyerCategory(buyer);
if(category == buyerCategory.GOLD)
transfercost=0;
if(category == buyerCategory.SILVER)
transfercost=transfercost/2;
}
public void placeOrder(ShoppingCart so1,ItemOrdered ItemO,int quantity)
{
quantity=ItemO.getquantity();
so1.addItemOrdered(ItemO);
}
public String getname()
{
return name;
}
public String getemail()
{
return email;
}
public void setbonus(int bonus)
{
this.bonus=bonus;
}
public int getbonus()
{
return bonus;
}
public buyerCategory getCategory()
{
return category;
}
public int getdistance()
{
return distance;
}
public double gettransfercost()
{
return transfercost;
}
void print()
{
System.out.println("H stoixeia tou pelati einai:\nCategory:" +getCategory()+"\t\tName:" +getname()+ "\t\tEmail:"+getemail()+"\t\tBonus:" +getbonus()+"\t\tTransfercost:"+gettransfercost());
}
}

System.out.print doesnt display customer data

I am writing a client database. I want to know the customer's name and hometown based on the customer number. When I enter number 2, I want to see Arya Stark, Edinburgh and when I enter number 1, I want to see Jon Snow, London. Why doesn't my program work? How to fix this?
package app;
import java.util.Scanner;
class Person {
String name;
String homeCity;
int customerNumber;
}
public class Customers {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String name;
System.out.print ("Give a customer card number: ");
name = input.next();
Person person1 = new Person();
person1.name = "Jon Snow";
person1.homeCity = "London";
person1.customerNumber = 1;
Person person2 = new Person();
person2.name = "Arya Stark";
person2.homeCity = "Edinburgh";
person2.customerNumber = 2;
System.out.println();
}
}
This should work:
class Person {
private String name;
private String homeCity;
private int customerNumber;
public Person(String name, String homeCity, int customerNumber) {
this.name = name;
this.homeCity = homeCity;
this.customerNumber = customerNumber;
}
public boolean isMatch(int num) {
return num == customerNumber;
}
#Override
public String toString() {
return name + " from " + homeCity;
}
}
import java.util.Scanner;
class Main {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Person person1 = new Person("Jon Snow", "London", 1);
Person person2 = new Person("Arya Stark", "Edinburgh", 2);
while(true) {
System.out.print("Give a customer card number: ");
String num = input.next();
if (person1.isMatch(Integer.parseInt(num))) {
System.out.println(person1);
} else if (person2.isMatch(Integer.parseInt(num))) {
System.out.println(person2);
} else {
System.out.println("Not found");
}
}
}
}

Java - Adding 2 objects in an ArrayList

I'm pretty new to programming so I need help. I wanna add the SubjectGrades to the studentList ArrayList. But I think I'm doing the wrong way. What should I do for me to add the SubjectGrades to the ArrayList? Thanks
Here's my partial Main class.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
private static Scanner in;
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
//ArrayList<SubjectGrades> Grades = new ArrayList<SubjectGrades>();
in = new Scanner(System.in);
String search, inSwitch1, inSwitch2;
int inp;
do {
SubjectGrades sGrade = new SubjectGrades();
Student student = new Student();
System.out.println("--------------------------------------");
System.out.println("What do you want to do?");
System.out.println("[1]Add Student");
System.out.println("[2]Find Student");
System.out.println("[3]Exit Program");
System.out.println("--------------------------------------");
inSwitch1 = in.next();
switch (inSwitch1) {
case "1":
System.out.println("Input student's Last Name:");
student.setLastName(in.next());
System.out.println("Input student's First Name:");
student.setFirstName(in.next());
System.out.println("Input student's course:");
student.setCourse(in.next());
System.out.println("Input student's birthday(mm/dd/yyyy)");
student.setBirthday(in.next());
System.out.println("Input Math grade:");
student.subjectGrade.setMathGrade(in.nextDouble());
System.out.println("Input English grade:");
student.subjectGrade.setEnglishGrade(in.nextDouble());
System.out.println("Input Filipino grade:");
student.subjectGrade.setFilipinoGrade(in.nextDouble());
System.out.println("Input Java grade:");
student.subjectGrade.setJavaGrade(in.nextDouble());
System.out.println("Input SoftEng grade:");
student.subjectGrade.setSoftEngGrade(in.nextDouble());
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
break;
//end case 1
Here is my Student Class.
package santiago;
public class Student {
private String lastName;
private String firstName;
private String course;
private String birthday;
SubjectGrades subjectGrade = new SubjectGrades();
public SubjectGrades getSubjectGrade() {
return subjectGrade;
}
public void setSubjectGrade(SubjectGrades subjectGrade) {
this.subjectGrade = subjectGrade;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
And my SubjectGrades class
package santiago;
public class SubjectGrades{
Double mathGrade, englishGrade, filipinoGrade, javaGrade, softEngGrade, weightedAverage;
public Double getMathGrade() {
return mathGrade;
}
public void setMathGrade(Double mathGrade) {
this.mathGrade = mathGrade;
}
public Double getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Double englishGrade) {
this.englishGrade = englishGrade;
}
public Double getFilipinoGrade() {
return filipinoGrade;
}
public void setFilipinoGrade(Double filipinoGrade) {
this.filipinoGrade = filipinoGrade;
}
public Double getJavaGrade() {
return javaGrade;
}
public void setJavaGrade(Double javaGrade) {
this.javaGrade = javaGrade;
}
public Double getSoftEngGrade() {
return softEngGrade;
}
public void setSoftEngGrade(Double softEngGrade) {
this.softEngGrade = softEngGrade;
}
public Double getWeightedAverage(){
weightedAverage = ((mathGrade + englishGrade + filipinoGrade + javaGrade + softEngGrade)*3) / 15;
return weightedAverage;
}
public String getScholarStatus(){
String status = "";
if(weightedAverage <= 1.5) {
status = "full-scholar";
} else if (weightedAverage <= 1.75){
status = "half-scholar" ;
} else {
status = "not a scholar";
}
return status;
}
}
Your mistake:
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade));
You are adding the student, then trying to add a void. The return value of setSubjectGrade is void, so nothing will be added:
Just do:
student.setSubjectGrade(sGrade);
studentList.add(student);
Where sGrade is an Object of type SubjectGrades, which was populated in the same way
student.subjectGrade.setSoftEngGrade(in.nextDouble()); was populated.
Use
ArrayList <SubjectGrades> list;
in student class instead SubjectGrades subjectGrade = new SubjectGrades();.
and generate getters and setters
Just remove this line:
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
The way you have done it, the student object already has the subjectGrade attribute with its values set.
You can access it with studentList.get(0).getSubjectGrade()

Categories

Resources