I am doing a project in college which we are to create a java program to add golfers to a list of members. I am having trouble getting them added to the list!
This is my code so far:
*import java.util.*;
public class GolfClubTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Please enter number for:");
System.out.println("1: Joining Member:");
System.out.println("2: Remove an old Member:");
System.out.println("3: Search for a Member:");
System.out.println("4: View all");
//Ask User for input
Scanner input = new Scanner(System.in);
int i = input.nextInt();
if(i == 1){
//Clear scanner input buffer
input.nextLine();
System.out.println("Please enter Members name:");
String name = input.nextLine();
System.out.println("Please enter day:");
int day = input.nextInt();
System.out.println("Please enter month");
int month = input.nextInt();
System.out.println("Please enter year:");
int year = input.nextInt();
System.out.println("Please enter Handicap:");
int Handicap = input.nextInt();
System.out.println("Please enter Id:");
int MemId = input.nextInt();
//Clear scanner input buffer
input.nextLine();
//Ask user type of Member
System.out.println("Please enter type of Member:");
System.out.println("1 - Senior:");
System.out.println("2 - Junior:");
int i1 = input.nextInt();
if (i1 == 1){
//Create member object
Date join1 = new Date(day,month,year);
SeniorMembers s1 = new SeniorMembers(name,join1,Handicap,MemId);
//Display member details
System.out.println("**Senior Member has joined**");
System.out.println(s1);
return;
}
else if (i1 == 2){
Date join1 = new Date(day,month,year);
JuniorMembers j1 = new JuniorMembers(name,join1,Handicap,MemId);
//Display member details
System.out.println("**Junior Member has joined**");
System.out.println(j1);
}
else{
throw new IllegalArgumentException("Invalid input:");
}
}*
So I can get it to say the member has joined but it doesn't actually save the member. Can anyone help and tell me what I am missing?
ArrayList<SeniorMember> seniorMembersList = new ArrayList<>();
ArrayList<JuniorMember> juniorMembersList = new ArrayList<>();
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Please enter number for:");
System.out.println("1: Joining Member:");
.......
if (i1 == 1){
//Create member object
Date join1 = new Date(day,month,year);
SeniorMembers s1 = new SeniorMembers(name,join1,Handicap,MemId);
//
//Adding here
//
seniorMembersList.add(s1);
//Display member details
System.out.println("**Senior Member has joined**");
System.out.println(s1);
return;
}
else if (i1 == 2){
Date join1 = new Date(day,month,year);
JuniorMembers j1 = new JuniorMembers(name,join1,Handicap,MemId);
//
//Adding here
//
juniorMembersList.add(j1);
//Display member details
System.out.println("**Junior Member has joined**");
System.out.println(j1);
}
Then you can access these member objects where you need it using seniorMembersList.get(position);
Also, I think you'll get it from all the comments and answer, you can store your instances in Lists (for example as ArrayList<String>).
As your program is in a main method, the lists should be instantiate in this method.
Hint: when you'll go further in your implementation, use a more object oriented approach.
Related
My homework question is to Create a procedure called NoDuplicates which will prompt the user to enter 7 unique integers. As the user enters the numbers, ask them to re-enter a number if it has been entered previously. Output the 7 unique numbers.
I have tried a lot of different combinations of while and for loops but nothing works
import java.util.Scanner;
public class arrayexcersisespart3num1 {
public static void main(String []arg) {
Scanner input = new Scanner(System.in);
noDuplicates(input);
}
public static void noDuplicates(Scanner input) {
boolean check = true;
int jumbo;
int[]noDuplicates = new int [7];
System.out.println("Please enter a unique Name");
for (int i = 0; i<noDuplicates.length;) {
System.out.println("Enter a number");
jumbo = input.nextInt();
while(check ==true|| i>0) {
check = false;
System.out.println("Please enter another number");
jumbo = input.nextInt();
if (jumbo==(noDuplicates[i])) {
check = true;
System.out.println("this Name has been previously added. Please choose another number");
}
}
jumbo = noDuplicates[i];
System.out.print("this Number has been previously successfully added in position ");
System.out.println(i+1);
check = false;
i++;
}
}
}
I don't understand your code, but:
final int N = 7; // Constant, used multiple times throughout the program
Scanner sc = new Scanner (System.in);
int[] noDuplicates = new int[N];
noDuplicates[0] = sc.nextInt();
for(int i=1; i<N; i++){ // Loops through the array to put numbers in
int query = sc.nextInt(); // Number to be put into the array
for(int j=0; j<i-1; j++){
if(noDuplicates[j] == query){ // If they are the same
i--;
continue; // Tells them to input a new number, skips all code ahead
}
}
noDuplicates[i] = query;
}
Try this logic of Collection.contains then add it in collection. It will ask the input from user from console and check whether data store in List or Not. Like this it will ask the value from user for 7 unique time on list used that
public void uniqueDataCheckOnConsoleOnLimitByList() {
int capacity = 7;
List<String> dataList = new ArrayList<>(capacity);
while (capacity != 0) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (dataList.contains(s)) {
System.out.println("You already entered the number:" + s);
//System.out.println("Please Enter a New Number");
} else {
dataList.add(s);
capacity--;
}
}
}
As i did not check the requirement on Array. Please check it in case of array.
public void uniqueDataCheckOnConsoleOnLimitByArray() {
int capacity = 7;
String data[]= new String[capacity];
while (capacity != 0) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (containsArray(data, s)) {
System.out.println("You already entered the number:" + s);
//System.out.println("Please Enter a New Number");
} else {
data[capacity-1]=s;
capacity--;
}
}
}
public boolean containsArray(String data[],String input){
for(String s:data){
if(input.equalsIgnoreCase(s))
return true;
}
return false;
}
I am attempting to have my user read from my menu and make a selection either option 1 (add a product name, store name, purchase date and cost), option 2 display the arrayList with the purchase objects the were inputted and option 3 exit the program and thank the user for using my program all while have exceptions to ensure that the user doesn't input and valid entries. Now I need to be able to store to a txt file and have the ability to pull it back up for review or modification.
I built my menu and and I believe that I have setup my arrayList correctly for proper user input, I have methods for each string that the user will be inputting and exceptions to ensure that the inputs are valid
public static void main(String[] args) throws Exception {
//Create menu options
TheMenu();
}
public static void TheMenu() {
Scanner input = new Scanner(System.in);
String purchase[] = new String[4];
int option;
do { // loop until Exit (option 3) is selected
System.out.println("\nMenu Options");
System.out.println("\n1 Add a purchase");
System.out.println("\n2 Display a purchase");
System.out.println("\n3 Exit");
option = input.nextInt();
if (option == 1) {
displayPurchaseObjects(purchase);
}
if (option == 2) {
System.out.println();
}
while (option == 3)
System.out.println("Thank you for using purchase programmer!");
System.exit(3);
//Create a list to store Purchase objects
ArrayList<String> displayPurchaseObjects = new ArrayList<>();
while(input.hasNext()) {
System.out.println("Enter the product name ");
String productName = input.next();
System.out.print("Enter the store name");
String storeName = input.next();
System.out.println("Enter the purchase date (i.e. 06/30/2019) ");
int purchaseDate = input.nextInt();
System.out.println("Enter the cost ");
double cost = input.nextDouble();
}
}
}
public void productName(String productName) {
try {
for(int i = 1; i < productName.length(); i++) {
}
}
catch(Exception e) {
System.out.println("Please enter a product name ");
}
}
public void storeName(String storeName) {
try {
for(int i = 1; i < storeName.length(); i++) {
}
}
catch(Exception e) {
System.out.println("Please enter a store name");
}
}
public void purchaseDate(String date) {
DateTimeFormatter format = DateTimeFormatter.ofPattern(date);
try {
format.parse(date);
}
catch(Exception e) {
System.out.println("Invalid date");
}
}
public void cost(double newCost)
throws InputMismatchException{
double cost;
if(newCost >= 1)
cost = newCost;
else
throw new InputMismatchException("Cost must be a integer and more the $0 ");
}
I am receiving a compilation error because of a "}" which I cannot find the cause and the program should be allowing me to make a selection (1,2 or 3) and the should be able to add my purchase objects to my "displayPurchaseObjects" arrayList
If I have understood your question clearly, the problem at hand is the compilation error - not able to find a "}".
In your code, you are missing out the "}" after this -
do { // loop until Exit (option 3) is selected
System.out.println("\nMenu Options");
System.out.println("\n1 Add a purchase");
System.out.println("\n2 Display a purchase");
System.out.println("\n3 Exit");
option = input.nextInt();
if (option == 1) {
displayPurchaseObjects(purchase);
}
if (option == 2) {
System.out.println();
}
} while (option == 3);
System.out.println("Thank you for using purchase programmer!");
// Non zero exit code is only for abnormal termination. Use 0.
System.exit(0);
Before someone says 'We're not solving your homework, ask your teacher' I only get programming on a Wednesday and this is not homework. It's an extra task that i asked for
Anyways i'm trying to create a program that i can Input a game's name and price then display the titles of all the games(which are in an array) and then another option to display the total price of all games
The issue i'm having is that i can't add to the array(Hard to explain so here's my code )
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Java {
public static void main(String[] args) {
Java.mainMenu();
}
public static void mainMenu() {
// ArrayList titleArray
// PrimitiveArray priceArray
int choice = 0;
String again = "";
String[] gameTitle = new String[0];
Scanner user_input = new Scanner(System.in);
System.out.println(" Main Menu");
System.out.println("");
System.out.println("1) Enter Game Details");
System.out.println("2) Display Titles in Order");
System.out.println("3) Display Total Price");
System.out.println("");
System.out.println("Choice : ");
choice = user_input.nextInt();
if (choice ==1){
gameDetails(gameTitle);
} else if (choice ==2) {
displayTitles(gameTitle);
} else if (choice ==3) {
}
}
public static void displayTitles(String[] gameTitle) {
// Choice 2
System.out.println(Arrays.toString(gameTitle));
}
public static void gameDetails(String[] gameTitle) {
//Choice 1
String addGameTitle;
double addGamePrice;
Scanner user_input = new Scanner(System.in);
System.out.println("Enter the game Title : ");
addGameTitle = user_input.next();
Java.mainMenu();
}
}
So i run this and put 1 in, it asks me for the Title of the game i enter it but it doesn't get added to the array? Is it because of the way that i am Passing the array?
try doing an array list!
List<array length> <name> = new ArrayList<array length>
<arrayname>.add(<location in array>) = <something>
<arrayname>.add(<location in array>) = <something>
Unfortunately, you will need to have a set length of the array beforehand, which means you can't add to it after you have filled the capacity of the array.
hope this helps!
(Note: I'm relatively new to java myself so I could be forgetting something, or misremembering.)
My template opens with a menu of options. When the user chooses option 1, it asks them to input a number teamNumber. One must instantiate the class Team, then it writes it to an arraylist.
If there is at least one number in numberList, the user can select option 2. It asks them to input any of the numbers from the arraylist and searches it. If the number they input is found, then you input the team member. It will write the input to a private arraylist located in class TeamMember.
I'm very close to figuring this all out except for one problem. It seems that regardless of which stored team number I input after choosing option 2, the team member I add to teamList is added to ALL team numbers, not just the one I want it to be added to. So, say in option 1 I added a team 1 and a team 2. Then in option 2, I type 1 and proceed to enter the member. It ends up adding the team member to both team 1 and 2. Is there a way to fix this? I tried a few options but can't seem to wrap my head around it.
public class Main {
public static void main(String[] args) {
int choosing;
Scanner scan = new Scanner(System.in);
String input;
int teamNumber;
boolean stayInLoop;
ArrayList<Team> numberList = new ArrayList<Team>();
do {
stayInLoop = true;
System.out.println("1. Add a new team");
System.out.println("2. Add a new team member");
System.out.println("3. View teams");
input = scan.nextLine();
if (input.equals("1")) {
System.out.println("Enter a team number:");
teamNumber = scan.nextInt();
scan.nextLine();
Team addTeam = new Team(teamNumber);
numberList.add(addTeam);
}
if (input.equals("2")){
boolean foundIt = false;
boolean valid = true;
System.out.println("Team number:");
teamNumber = scan.nextInt();
scan.nextLine();
for (int a = 0; a < numberList.size() && foundIt == false; a++){
Team addTeam = numberList.get(a);
if (addTeam.findTeam() == teamNumber) {
foundIt = true;
System.out.println("Enter first name of team member:");
String teamMemberFirstName = scan.nextLine();
System.out.println("Enter first initial of last name:");
char firstInitialLastName = scan.nextLine().charAt(0);
TeamMember inputTeamMember = new TeamMember(teamMemberFirstName, firstInitialLastName);
inputTeamMember.addMember(inputTeamMember, valid = true);
int teamSize = (inputTeamMember.size(valid = true));
System.out.println("Team " + teamNumber + " has " + teamSize + " members!");
}
}
if (foundIt == false) {
System.out.println("Try again.");
}
}
}while (stayInLoop == true;)
}}
TeamMember:
public class TeamMember {
//the code provided in the task had teamList set to private, so I'm assuming it's required to be that way. I added static in order to eventually be able to call it with a method to view the team in option 3. But if the only solution involves changing the list to public, then so be it.
private final String teamMemberFirstName;
private final char firstInitialLastName;
private static ArrayList<TeamMember> teamList = new ArrayList<>();
public TeamMember(String teamMemberFirstName, char firstInitialLastName) {
this.teamMemberFirstName = teamMemberFirstName;
this.firstInitialLastName = firstInitialLastName;
}
public int addMember(TeamMember member, boolean valid) {
valid = teamList.add(member);
return teamList.size();
}
public static int size(boolean valid) {
return teamList.size();
}
}
teamList is static, hence shared by all instances of TeamMember. Remove the static keyword.
The objective is to create an account registration method for an ATM object. But I keep breaking on the if statement used to enter the loop. I assume my "wording" is off, but I'm drawing a blank on how to fix it. Any suggestions? The problem itself is at if(acc[i].getAcc()==0)where .getAcc is a getter in a class.
package atmassignment;
import java.util.Scanner;
public class AtmAssignment {
static Scanner in = new Scanner(System.in);
static int cou = 1;
static Account[] acc = new Account[10];
public static void main(String[] args) {
menu();
}
public static void menu(){
char opt;
System.out.println("Thanks for accessing ATManager.");
System.out.println("Please select a menu option to proceed.");
System.out.println("1-Register a new account, 2-Access an account, 0-Exit ATManager");
opt = in.next().charAt(0);
switch (opt) {
case '1':
newAccount();
break;
case '2':
selAccount();
break;
case '0':
System.out.println("Goodbye.");
break;
default:
System.out.println("Invalid Entry.");
break;
}
}
public static void newAccount(){
System.out.println("Account registration");
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i] = new Account(cou, bal, cus);
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
}
}
This allocates an array of object references:
static Account[] acc = new Account[10];
However it doesn't actually allocate any objects, so you are probably getting a null pointer exception when you try to access the first element. In your init code, do something like this:
for(int i = 0; i < 10; i++)
acc[i] = new Account();
You call acc[i].getAcc()==0 before actually constructing your objects. Maybe modify the for loop so that you create your objects and then gather input and update your objects later on with setter methods? This of course requires that you have some sort of default constructor for your Account class.
acc[j through maxLength] = new Account(); //where j spans the entire length of the array
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i].setContact(###);
acc[i].setBalance(###); //ETC
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
Probably you didn't populate your Account[] array. Here I only can see you declare your array like -
static Account[] acc = new Account[10];
So after that when you are trying to get you array element using for loop than you can't access them. You are getting the error at if(acc[i].getAcc()==0) this line. So I suggest remove the if check since you are populating your Account later in this line - acc[i] = new Account(cou, bal, cus);
Hope it will help.
Thanks a lot.