I'm new to Java and I am trying to create a program where you can sign up members to a club and i've hit a wall when trying to add / create people.
I can't seem to figure out how to keep creating new objects of a class inside an if statement or switch. (Like lets say going through the switch and adding 10 new members).
public static void main(String[] args) throws NoSuchMethodException {
System.out.println("Opties: \n" +
"1) Add a member to the club.");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
scanner.nextLine();
do{
switch(choice){
case 1:
System.out.println("New member name: ");
String newMemberName = scanner.nextLine();
System.out.println("New member age: ");
int newMemberAge = scanner.nextInt();
scanner.nextLine();
System.out.println("""
New member category:\s
A) Player
B) Coach""");
String categoryChoice = scanner.nextLine();
if (categoryChoice.equalsIgnoreCase("a")){
} else if(categoryChoice.equalsIgnoreCase("b")){
} else break;
case 2:
///temp
}
} while(choice != 3);
And this is the class + subclass
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Player extends Person {
public Player(String name, int age) {
super(name, age);
}
}
class Trainer extends Person {
public Trainer(String name, int age) {
super(name, age);
}
}
You should not create the variable inside an if statement, you should create the variable before hand with a default value null then change the variable's value inside each if statement with the proper object:
public static void main(String[] args) throws NoSuchMethodException {
System.out.println("Opties: \n" +
"1) Add a member to the club.");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
scanner.nextLine();
Person person = null; //needs to be the super class
do{
switch(choice){
case 1:
System.out.println("New member name: ");
String newMemberName = scanner.nextLine();
System.out.println("New member age: ");
int newMemberAge = scanner.nextInt();
scanner.nextLine();
System.out.println("""
New member category:\s
A) Player
B) Coach""");
String categoryChoice = scanner.nextLine();
if (categoryChoice.equalsIgnoreCase("a")){
person = new Player(newMemberName, newMemberAge);
} else if(categoryChoice.equalsIgnoreCase("b")){
person = new Trainer(newMemberName, newMemberAge);
} else break;
case 2:
///temp
}
} while(choice != 3);
}
Since you are creating objects inside a loop it would make more sense to create an ArrayList<Person> instead of a single variable and during each iteration you add a new object to it:
ArrayList<Person> people = new ArrayList<Person>(); //needs to be the super class - an empty list
do { ...
if (categoryChoice.equalsIgnoreCase("a")){
people.add(new Player(newMemberName, newMemberAge));
} else if(categoryChoice.equalsIgnoreCase("b")){
people.add(new Trainer(newMemberName, newMemberAge));
} else break;
} while(choice != 3);
Related
I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).
I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.
I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".
(Yes, I tested this when I already inserted some data.)
Here's the full code:
package appartamento;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Appartamento {
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyb = new BufferedReader(input);
boolean attiva = true;
do {
System.out.println("what do you want to do?");
System.out.println("1 - check for a person");
System.out.println("2 - Add person");
int choice = Integer.parseInt(keyb.readLine());
Datiutente du[] = new Datiutente[10];
if (choice == 2){
System.out.println("How many people?");
int hm = Integer.parseInt(keyb.readLine());
for (int i=0;i<hm;i++){
du[i] = new Datiutente();
System.out.println("insert name:");
du[i].setName(keyb.readLine());
System.out.println("insert surname");
du[i].setSurname(keyb.readLine());
}
}
if (choice == 1){
System.out.println("which person are you searching?");
int vd = Integer.parseInt(keyb.readLine());
System.out.println("position: " + i);
System.out.println("Name: "+ du[i]);
System.out.println("Surname: " + du[i]);
}
} while (attiva = true);
}
}
and the class "Datiutente":
package appartamento;
public class Datiutente {
private String name;
private String surname;
private String codfis;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSurname(String surname){
this.surname = surname;
}
public String getSurname(){
return surname;
}
}
In every iteration you define the Datiutente du[] = new Datiutente[10];, so du is reset to {null,...,null} and the data saved in the previous iteration are replaced;
Try to define the array before the loop statement.
I found a way here:
You need to insert values on object creation, you can also use hashmaps
hashmap will benefit you more I think.
Code sample to fix your stuff.
class GFG {
public static void main(String args[]){
// Declaring an array of student
Student[] arr;
// Allocating memory for 2 objects
// of type student
arr = new Student[2];
// Initializing the first element
// of the array
arr[0] = new Student(1701289270, "Satyabrata");
// Initializing the second element
// of the array
arr[1] = new Student(1701289219, "Omm Prasad");
// Displaying the student data
System.out.println(
"Student data in student arr 0: ");
arr[0].display();
System.out.println(
"Student data in student arr 1: ");
arr[1].display();
}
}
class Student {
public int id;
public String name;
// Student class constructor
Student(int id, String name)
{
this.id = id;
this.name = name;
}
// display() method to display
// the student data
public void display()
{
System.out.println("Student id is: " + id + " "
+ "and Student name is: "
+ name);
System.out.println();
}
}
Basically, I just tried to learn linked lists but I can't seem to understand how to insert a bunch of data from different variables into it. Does it work as an array/ ArrayList? Before we end the loop we are supposed to store the data right, but how??
Let say I have variables ( name, age, phonenum).
'''
char stop='Y';
while(stop!='N'){
System.out.println("\nEnter your name : ");
int name= input.nextLine();
System.out.println("\nEnter your age: ");
int age= input.nextInt();
System.out.println("\nEnter your phone number: ");
int phonenum= input.nextLine();
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
stop = sc.nextLine().charAt(0);
}
'''
First, change your code to use appropriate types. Name and phone should be of type String, not int.
Define a class to hold your fields. Records are an easy way to do that.
record Person ( String name , int age , String phone ) {}
Declare your list to hold objects of that class.
List< Person > list = new LinkedList<>() ;
Instantiate some Person objects, and add to list.
list.add( New Person( "Alice" , 29 , "477.555.1234" ) ) ;
In the line above, I hard-coded some example data. In your own code, you will be passing to the constructor the variables you populated by interacting with the user.
list.add( New Person( name , age , phonenum ) ) ;
You can create an object which has name, age and phenomenon then create an insert method which you call in your while loop.
In psuedo code it would look something like this:
public class Data {
String name;
int age;
int phenomenon;
//constructor
//getters & setters
}
This class above will hold contain the user input. You can gather all the user input and store it in an array and perform the insert with array of data instead of inserting one object at a time
public void InsertData(LinkedList<Data> list, Arraylist<Data> input) {
for(Data d: input){
list.add(d);
}
}
You can read up on linkedlists a bit more here to understand how exactly linkedlists work and implement your own from scratch: https://www.geeksforgeeks.org/implementing-a-linked-list-in-java-using-class/
Try this
Possibility : 1
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<Object> list = new LinkedList<Object>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(name);
list.add(age);
list.add(phonenum);
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
possibility : 2
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<User> list = new LinkedList<User>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(new User(name, age, phonenum));
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
class User {
private String name;
private int age;
private long phonenum;
public User() {
}
public User(String name, int age, long phonenum) {
this.name = name;
this.age = age;
this.phonenum = phonenum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhonenum() {
return phonenum;
}
public void setPhonenum(long phonenum) {
this.phonenum = phonenum;
}
#Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", phonenum=" + phonenum + "]";
}
}
I'm trying to write this Registration Program for Sports Teams, but when I input a name and age which qualifies for a team, an java.lang.ArrayOutOfBoundsException occurs. Any idea why? The code and classes can be seen below.
The objective of the code is to fill out arrays in the Team Class, and print it out once the user inputs '3' in the Test Class.
public class Member {
public String name;
public int age;
public Member(String name, int age){
this.name = name;
this.age = age;
}
}
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
int choi;
Team basketball = new Team("Basketball", 2, 18, 21);
Team volleyball = new Team("Volleyball", 3, 17, 19);
do{
//MENU
System.out.println("Select Team");
System.out.println("--------------");
System.out.println("[1] Basketball");
System.out.println("[2] Volleyball");
System.out.println("[3] Exit");
System.out.println("---------------");
System.out.print("Choice: ");
choi = myScan.nextInt();
myScan.nextLine();
//SWITCH START
switch(pili){
//BASKETBALL CASE
case 1:
String name;
int age;
System.out.println("Basketball");
System.out.print("Enter Name: ");
name = myScan.nextLine();
System.out.print("Enter Age: ");
age = myScan.nextInt();
myScan.nextLine();
Member bball = new Member(name,age);
basketball.addMember(bball);
break;
//END CASE 1
//VOLLEYBALL CASE
case 2:
String name1;
int age1;
System.out.println("Volleyball");
System.out.print("Enter Name: ");
name1 = myScan.nextLine();
System.out.print("Enter Age: ");
age1 = myScan.nextInt();
Member vball = new Member(name1, age1);
volleyball.addMember(vball);
break;
//END CASE 2
//EXIT CASE
case 3:
System.out.println("Basketball Team Members");
for(int i = 0; i<2; i++){
System.out.println(basketball.members[i]);
}
System.out.println("Volleyball Team Members");
for(int i = 0; i<3; i++){
System.out.println(volleyball.members[i]);
}
break;
//CASE 3 END
} //END SWITCH
} //END DO
while(choi > 0 && pili < 3);
}
public class Team {
public String name;
public int memberCnt;
public int maxMember;
public Member [] members = new Member[maxMember];
public int minAge;
public int maxAge;
public Team(String name, int maxMember, int minAge, int maxAge){
this.name = name;
this.maxMember = maxMember;
this.minAge = minAge;
this.maxAge = maxAge;
}
public void addMember(Member memb){
boolean result = checkQualification(memb);
if(memberCnt < maxMember){
if (result){
members[memberCnt]=memb;
memberCnt++;
System.out.println("Welcome to the " + name);
}
else{
System.out.println("You are not qualified!");
}
}
else{
System.out.println(name + " Team is no longer accepting applicants");
}
}
public boolean checkQualification(Member memb){
return memb.age >= minAge && memb.age <= maxAge;
}
}
The error is because of
public int maxMember;
public Member[] members = new Member[maxMember];
Because at this moment maxMember values 0, so you're creating an empty array
Do the instantiation when you have the real value of maxMembers, in the constructor
public int maxMember;
public Member[] members;
public Team(String name, int maxMember, int minAge, int maxAge) {
this.name = name;
this.maxMember = maxMember;
this.members = new Member[maxMember];
this.minAge = minAge;
this.maxAge = maxAge;
}
Attribut maxMembers could not be an attribut, and you would use array's length in condition
if (memberCnt < members.length) {
Hello I'm still new to Java and OOP and am having issues trying to get my code to compile. I understand the issue with my code is the instantiation of the same object twice however I'm not sure how I can work around that to compile my code.
package week2;
import java.util.*
public class aBug {
aBug theBug = new aBug();
String Inspecies, Inname;
int Inx, Iny, Inenergy, Inid;
char Insymbol;
Scanner scan = new Scanner(System.in);
aWorld newWorld = new aWorld();
public static void main(String[] args) {
aBug theBug = new aBug();
theBug.mainMenu();
}
public void mainMenu() {
int choice;
do {
System.out.print("1\t Create bug\n");
System.out.print("2\t Enter world\n");
System.out.print("3\t Quit\n");
choice = scan.nextInt();
switch (choice) {
case 1:
bugInit();
break;
case 2:
System.out.println();
newWorld.mapInit(theBug.Inx, theBug.Iny, theBug.Insymbol);
System.out.println();
break;
}
} while (choice != 3);
}
public void bugInit() {
String species, name;
int x, y, energy, id;
char symbol;
System.out.print("Species: ");
species = scan.nextLine();
System.out.print("Name: ");
name = scan.nextLine();
System.out.print("X position: ");
x = scan.nextInt();
System.out.print("Y position: ");
y = scan.nextInt();
System.out.print("Energy: ");
energy = scan.nextInt();
System.out.print("ID: ");
id = scan.nextInt();
theBug.Insymbol = 'b';
theBug.Inspecies = species;
theBug.Inname = name;
theBug.Inx = x;
theBug.Iny = y;
theBug.Inenergy = energy;
theBug.Inid = id;
System.out
.format("\nThe bug is of the species %s, called %s, "
+ "with positions %d & %d, with energy amount: %d, and %d as it's id number\n\n",
theBug.Inspecies, theBug.Inname, theBug.Inx, theBug.Iny,
theBug.Inenergy, theBug.Inid);
}
}
In the constructor you have:
public class aBug {
aBug theBug = new aBug();
...
}
So while creating an instance of aBug (for example in your main) you call new aBug(), which calls the constructor again recurrently with out end overflowing the stack.
I am not sure why do you think you need to create an instance of the object within itself. So it's hard to give any hints. If I guess correctly, you merged the idea of aBug and "main program" in one class. You should split it and put aBug internal stuff in its own class.
Could you please help me figure out why when i add a new book it overwrites all of the books with the current one? ---------------------- |Name| -|ISBN|-|Author|
for example i add a book called |game| | of | Thrones|
and if i go & add a book named |Song| | of | Ice and fire |
no matter if there are 10 books there they will all be renamed according to the last entry
(here Song of ice and fire)
//Package ask1 main class Library
package ask1;
import java.lang.Object.*;
import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
public class library {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner(System.in);
Book vivlio = new Book();
System.out.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while (true) {
System.out.println("------------------MENU-------------------------------");
System.out.print("\nENTER UR CHOICE\n\t" +
"1:Add a new Book\n\t" +
"2:Edit Book Infos\n\t" +
"3:Search a Book (with ISBN)\n\t" +
"4:Show all the Books\n\t" +
"5:Delete a Book (with ISBN)\n\t" +
"6:Exit \n :");
int selection;
selection = input.nextInt();
if (selection == 1) {
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
} else if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if (editingBook == null) {
System.out.println("Sorry no book found with title name = " + title);
} else {
//ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
} else if (selection == 3) {
System.out.println("Searching a Book ");
} else if (selection == 4) {
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
} else if (selection == 5) {
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
} else if (selection == 6) {
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
} else {
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
here is the second class called Book
package ask1;
import java.util.Scanner;
public class Book {
Scanner input = new Scanner(System.in);
public String isbn;
public String name;
public String author;
public int number;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
String bookinfo = name + " ," + author + " ," + isbn;
public void setPrice(String newPrice) {
// TODO Auto-generated method stub
}
}
And the third class called Management
package ask1;
import java.util.Scanner;
public class Management {
Scanner input = new Scanner( System.in );
private Book[] books =new Book [60];
private String isbns = new Book().isbn;
private String name = new Book().name;
int current = 0;
//Number 1
public void AddBook(Book vivlio)
{
books[current]=vivlio;
current++;
}
//Number 3
//Number 4
public void PrintAllBooks()
{
for (int i=0;i<current;i++)
{
Book b = books[i];
System.out.println(b.name);
}
}
}
return searchBook;
}
}
The problem is that vivlio always means the same book. You only create one Book object, here:
Book vivlio = new Book();
and proceed to add it to the list several times, while changing its name each time. However, since it's just one book that happens to be on the list several times, when you change one you change all.
You can make it better by simply changing the scope. Move the creation of the book inside the loop:
while(true) {
Book vivlio = new Book();
...
Now vivlio is initialized to a different book each time, instead of using the same book all the time.
Your problem: You create Book vivlio = new Book(); once and re-use it every time. So whenever you set a parameter, you set it for this one book and therefore overwrite what you did before.
The easiest solution is to move
Book vivlio = new Book();
into your while loop.
That will create a new Book object each time you run through the loop.
By the way, there would be some ways to improve the code. For example, don't reference another object's attribute directly, but use getter and setter methods. Also, it is pretty standard to start function names with lower case chars.
Book object is created only once and after calling the following method.
public void AddBook(Book vivlio) {
books[current] = vivlio;
current++;
}
You are just assigning the same object object to array.
That means you are changing the values inside vivlio again and again but referencing the same object in array to different places thats why you are getting the same output in all the books.
Here is the right code for your reference.
public class library {
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner(System.in);
System.out
.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while (true) {
Book vivlio = new Book();
System.out
.println("------------------MENU-------------------------------");
System.out
.print("\nENTER UR CHOICE\n\t1:Add a new Book\n \t2:Edit Book Infos\n\t3:Search a Book (with ISBN)\n\t4:Show all the Books\n\t5:Delete a Book (with ISBN)\n\t6:Exit \n :");
int selection;
selection = input.nextInt();
if (selection == 1) {
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
}
else if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if (editingBook == null) {
System.out.println("Sorry no book found with title name = "
+ title);
} else {
// ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
}
else if (selection == 3) {
System.out.println("Searching a Book ");
} else if (selection == 4) {
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
} else if (selection == 5) {
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
} else if (selection == 6) {
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
} else {
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
}
Hope this might solve your problem.