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.
Related
First of all, this is my assignment question, and I was totally struggling for 2 weeks. If I want to calculate the ticket price, but the first three ticket price is 50, and the subsequence ticket is 45, but I tried do while loop, while loop and for loop, it will start over the program and start with the price 50, so how do I change the price to 45 when the program loop for 4 times?
public void setPrk(){
int[] ticket_add= new int[9999];
ticket_amount= ticket_add.length;
Ticket ticket= new Ticket();
Scanner s= new Scanner(System.in);
ticket.setTicketAmt();
for(int i=0;i<ticket_amount;i++){
System.out.print("Enter your choice (T/W/A): ");
prk=s.next().toLowerCase().charAt(0);
while(!(prk=='t'||prk=='T'||prk=='w'||prk=='W'||prk=='a'||prk=='A')){
System.out.println("Invalid option, try again");
System.out.print("Enter your choice: ");
prk=s.next().toLowerCase().charAt(0);
}
switch(prk){
case't':
ticket.setAge();
Ticket.ThemePark();
break;
case'w':
ticket.setAge();
Ticket.WaterPark();
break;
case'a':
ticket.setAge();
Ticket.AllPark();
break;
default:
break;
}
System.out.println("Your ticket fee will be "+(sum+(sum*0.06)));
}
}
public char getPrk(){
return prk;
}
public void setTicketAmt(){
Scanner s=new Scanner(System.in);
System.out.print("Enter your ticket amount: ");
while(!s.hasNextInt()){
System.out.println("This is not an integer, try again");
System.out.print("Enter your ticket amount: ");
s.next();
}
ticket_amount=s.nextInt();
while(ticket_amount<=0||ticket_amount>9999){
System.out.println("Invalid ticket amount, try again");
System.out.print("Enter your ticket amount: ");
while(!s.hasNextInt()){
System.out.println("This is not an integer, try again");
System.out.print("Enter your ticket amount: ");
s.next();
}
ticket_amount=s.nextInt();
}
}
public static int getTicketAmt(){
return ticket_amount;
}
public static void ThemePark(){
double[] ticket= new double[2];
double ticketSize[]={0};
if(age<17){
if(ticket_amount<=3){
ticket[0]=50;
ticketSize[0]=ticket[0];
}
if(ticket_amount>3){
for(int i=0;i<=3;i++){
ticket[0]=50;
ticketSize[0]=ticket[0];
}
for(int i=0;i>3&&i<ticket_amount;i++){
ticket[1]=45;
ticketSize[0]=ticket[1];
}
}
for(int k=0;k<ticketSize.length;k++){
sum+=ticketSize[k];
}
}
}
The question is vastly unclear.
I assumed you tried to put in most relevant parts. However, some important variables are missing (e.g., age), and unrelated parts (e.g., the switch(pkg)) could be removed from your question.
On the other hand, if that is all of the source code, it is best to state what are you trying to do in which functions.
Anyway, I presume you are trying to work on the price in the ThemePark function, and here's my solution to it:
public double ThemePark(int age, int ticket_amount) {
// I used a double variable to store the total value, but the `static` attribute
// is removed for demonstrating a whole function.
double ticketSum = 0;
if (age < 17) {
for (int i = 0; i < ticket_amount; i++) {
// The above fucntion of `for(int i=0; i>3&&i<ticket_amount:i++)` is genuinely
// incorrect, as i would never increment to i>3 in such case, it should be set
// as `i=4`. However, in such case it cannot registered the ticket_amount=4. As
// a result, it should also be set as `<=ticket_amount`.
if (i <= 3) {
ticketSum += 50;
} else {
ticketSum += 45;
}
}
}
return ticketSum;
}
Please state in the question if there's more specifications, and I hope this answer helps.
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.
I'm making a database where you can enter in animals and the supplements that they need. I have to use a multidimensional array. The problem I'm running into is that when a user goes into entering data into the multidimensional array, I get an out of bounds error. I'm confused because I used the same methodology for the user to input the type of animal and the number of supplements needed, but when it gets to actually entering the supplement, I introduced and array hold to keep the supplements for each animal organized. For a more visual reference, my logic wanted to be like this:
Names
Animal Type 1 Supplement 1
The Animal types go down the first column while the supplements fill in a horizontal fashion on each animal. I'll post my code but specifically I've run into issues with the array out of bounds. I suspect it has to do with how I initialized the multi array, but I'm unsure at this point. Any help would be greatly appreciated!
//Nicholas Stafford
//February 1, 2016
//This program will allow user input of up to any number of animals and dietary information and then allow the user to display that information when searching the database
import java.util.Scanner;
import java.util.Arrays;
public class inventory {
public static void main(String[] args)
{
//Initial variables
int choiceent;
int numAnimals = 0;
int numDiet = 0;
int ArrayHold = 0;
boolean isNum;
boolean isNum2;
boolean quit = false;
//Scanners needed for input
Scanner choice = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
//Initial value needed to enter animals into database
System.out.println("Enter the number of animals you wish to enter:");
do
{
if(input1.hasNextInt()) {
numAnimals = input1.nextInt();
isNum = true;
}
else {
System.out.println("Please enter an integer value!");
isNum = false;
input1.next();
}
}
while(!(isNum));
System.out.println("You are entering " +numAnimals+ " animals.");
//Multidimensional array
String [][] ZooBase = new String [100][100];
//Array for data types
int numDietA[] = new int [numAnimals];
do{
System.out.println("1. Enter the names of each animal");
System.out.println("2. Enter the dietary information");
System.out.println("3. Search the array for information");
System.out.println("4. Close the program");
choiceent = choice.nextInt();
switch(choiceent)
{
case 1:
//Data validation for name
for(int i = 0; i < numAnimals; i++)
{
System.out.println("Enter the type of animal for animal " +i+ "");
while(!input2.hasNext("[a-zA-Z]+"))
{
System.out.println("Enter a type of animal!");
ZooBase[i+1][0] = input2.nextLine();
}
ZooBase[i+1][0] = input2.nextLine();
}
//Display Names
System.out.println("Names");
for(int j = 0; j < numAnimals; j++){
System.out.println(ZooBase[j+1][0]);
}
break;
case 2:
for(int j = 0; j < numAnimals; j++)
{
System.out.println("How many supplements does the " +ZooBase[j+1][0]+ " need?");
do
{
if(input3.hasNextInt()) {
numDietA[j] = input3.nextInt();
isNum2 = true;
}
else {
System.out.println("Please enter an integer value!");
isNum2 = false;
input3.next();
}
}while(!(isNum2));
}
for(int k = 0; k < numAnimals; k++)
{
ArrayHold = k+1;
for(int m = 0; m < numDietA[m]; m++ )
{
System.out.println("Enter item " +m+ " for the " +ZooBase[m+1][0]+ "");
while(!input4.hasNext("[a-zA-Z]+"))
{
System.out.println("Enter a supplement (No integers)!");
ZooBase[ArrayHold][m+2] = input4.nextLine();
}
ZooBase[ArrayHold][m+2] = input4.nextLine();
}
}
break;
case 3:
break;
case 4:
quit = true;
break;
default:
System.out.println("Invalid option!");
break;
}
}while(choiceent != 4);
}
}
Once an array is initialized, its size can't be changed. To make sure this does not happen, use ArrayList<>, which does not have fixed bounds. You can find the syntax + all details here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Hope that helps!
ps. you can also initialize just 1 scanner input and use it throughout
I am trying to call my add method to add a score to my array
I've got this so far, but I keep getting an error saying myQuiz was never initialized.
......................................................................................
import java.util.Scanner;
public class Assignment7 {
public static void main (String[] args) {
//new scanner
Scanner in = new Scanner (System.in);
String choice;
char command;
// print the menu
int count = 0;
int counter = 0;
printMenu();
int array[] = new int[0];
//do while loop testing using user input
do{
// ask a user to choose a command
System.out.println("\nPlease enter a command or type ?");
choice = in.next().toLowerCase();
command = choice.charAt(0);
//start switch statement for user input cases
switch (command)
{
switch (command)
{
case 'n': //ask and read the size of the input array and name
System.out.print("\n\t n [Create a new Quiz]: ");
System.out.print("\n\t [Input the size of quizzes]: ");
int num=in.nextInt(); // read the integer
array = new int[num];
System.out.print("\n\t [Input the name of the student]: ");
String name = in.next(); //read name
Quiz myQuiz = new Quiz(num, name);
break;
case 'a': // ask and add score to array
System.out.print("\n\t a [Add a score]: ");
array[count] = in.nextInt();
myQuiz.add(array[count]);
counter++;
break;
/*
case 'a': // ask and add score to array
System.out.print("\n\t a [Add a score]: ");
array[count] = in.nextInt();
myQuiz.add(array[count]); //HELP
counter++;
break;
And my Quiz.java with add method
public class Quiz {
private int count;
private int[] scores;
private String name;
public Quiz(int a,String name){
scores = new int [a];
for (int i = 0; i<scores.length; i++){
scores[i] = -1;
}
this.count = 0;
this.name = "";
}
public void add(int b){
for(int i : scores){
if(scores[i] == count){
System.out.println("Array is full. The value " + b + " cannot be added.");
}
else {
scores[count] = b;
count++;
}
Watch your scopes more carefully: You define myQuiz in one branch of your switch-case statement, but you access it in another branch, too. What happens, if case 'a' is accessed? The myQuiz variable is unknown there!
case 'n': //ask and read the size of the input array and name
System.out.print("\n\t n [Create a new Quiz]: ");
System.out.print("\n\t [Input the size of quizzes]: ");
int num=in.nextInt(); // read the integer
array = new int[num];
System.out.print("\n\t [Input the name of the student]: ");
String name = in.next(); //read name
Quiz myQuiz = new Quiz(num, name);
break;
case 'a': // ask and add score to array
System.out.print("\n\t a [Add a score]: ");
array[count] = in.nextInt();
myQuiz.add(array[count]);
counter++;
break;
You have to define myQuiz outside of your switch-case statement, before it, to be more specific.
You create an empty array :
int array[] = new int[0];
and try to assign numbers to it :
array[count] = in.nextInt();
It can't work.
You must give it a positive length.
I am working on this airline program. The program should ask the user how many seats on the plane are sold and then I have this for loop to allow a user to enter a name and a meal choice for each person on the plane.
I have tried reading through some different questions about infinite for loops on stackoverflow, but I can't seem to figure out exactly what is going wrong with my code. I feel like there must be something about for loops that I am not understanding because I thought that it would only go through until your i < someNumber is no longer true.
So when I run this program, say I enter 2 seats I would expect it to go through the loop just twice, but It just keeps going. asking for a name and then a meal.
import java.util.Scanner;
public class Flyers
{
String name;
String mealType;
int economySeats;
int businessSeats;
int firstClassSeats;
int count;
public Flyers()
{
}
public String toString()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
return "Name: " + name + ", Meal " + mealType;
}
public void addEconomyFlyers()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of economy seats sold: ");
economySeats = in.nextInt();
for(count = 0; count < economySeats; count++)
{
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
Flyers newFlyer = new Flyers();
String seat = newFlyer.toString();
}
}
Here is my main class if that is helpful.
import java.util.Scanner;
public class Aviation
{
public Aviation()
{
}
public static void main(String[] args)
{
int option;
FlightCost newFlight = new FlightCost();
FlightProfit flight = new FlightProfit();
Flyers newFlyers = new Flyers();
Scanner in = new Scanner(System.in);
System.out.print("Enter new flight location: ");
String location = in.next();
do{
String menu = "\n Please select an option to perform"
+ "\n1 (1) Get flight costs."
+ "\n2 (2) Get flight profits."
+ "\n3 (3) Enter names/meals."
+ "\n4 (4) Exit.";
System.out.println(menu);
option = in.nextInt();
}while (option < 0 || option > 4);
switch(option)
{
case 1:
newFlight.getCost(location);
break;
case 2:
flight.addEconomySeats();
flight.addBusinessSeats();
flight.addFirstClassSeats();
flight.getProfit(location);
break;
case 3:
newFlyers.addEconomyFlyers();
break;
case 4:
System.out.println("Exit");
break;
default:
System.out.println("Error: must select menu option.");
}
}
}
remove below code from toString()
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
You are already reading these from the for loop.
Also, your do-while loop is all wrong. The condition doesn't make sense. It should be option > 0 && option <4
As Pat said:
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
this code in the toString() is obsolete
however the do while does make sense, to me at least, as i see it you want the menu printed out each time the user gives an invalid int, however you are still letting 0 get through although that is not a valid choice, the do while should be:
while (option <= 0 || option > 4);
or
while (option < 1 || option > 4);
Another quirk in your code:
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
Flyers newFlyer = new Flyers();
String seat = newFlyer.toString();
you create a new instance of the class you have just modified and call toString() on, even though you have not populated that class with data, so the toString method as it would be after the edit pat suggested will return "Name: Meal "
As i see your code is a work in progress, try adding more System.out.print on various variables for debugging purpose or use a debugger, though i know using debugger when learning can be difficult, it sure was for me. Also remember that every time you create a new instance ex:
Flyers newFlyer = new Flyers();
it has only the data that is either set by default or set in your constructor ex:
public Flyers()
{
}
I hope what i wrote was helpful, have a nice day and keep at it.