Java queue only printing out last element within for loop. - java

I'm creating a Java array of queues program to represent patients in a doctor array. It lets me add nodes in data structure but when I try to print it out it blows up on me. Here is the method
static boolean [] openflag = new boolean[6];
static queue [] Clinic = new queue[6];
static String [] Doctor = {"Doctor 1", Doctor 2", "Doctor 3","Doctor
4","Doctor 5","Doctor 6"};
final static String HEADING = "The clinic moniter of Dylan Rychlik";
static int MAX = 6;
public static void Listpaitents()
{
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is notaviable");
}
else{
Paitent[] array = Clinic[queuechoice -1].toArray();
//int size = Clinic[queuechoice -1].getSize();
int limit = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 1; x <= limit; x++) {
out += array[x-1].Print() + "\n";
// System.out.println(array[x-1] + "\n");
}
JOptionPane.showMessageDialog(null,out);
}
}
Here is the toarray() method in queue class.
public static Paitent[] toArray()
{
int x = Length;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = Length; ((Current != null) && (x >= 1));x--)
{
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
}
return Array;
}
And finally, here is the paitent class
public class Paitent {
protected static String name;
protected static String telephone;
protected static int ID;
//Creates a constructor for a paitent object
public void paitent()
{
name = "";
telephone = " ";
ID = 0;
}
//updates the country object
public void update(Paitent thisThing)
{
name = thisThing.name;
telephone = thisThing.telephone;
ID = thisThing.ID;
}
//asks for user input for country objects
public void input(int i)
{
String PatronHeading = "Country Data Entry";
String entername;
int enterID;
String enterphone;
entername = JOptionPane.showInputDialog(null, "Please Enter the name of
paitent #" + i +": ", PatronHeading, JOptionPane.QUESTION_MESSAGE);
enterphone = JOptionPane.showInputDialog(null, "Please Enter the telephone
number for paitent #" + i +": ", PatronHeading,
JOptionPane.QUESTION_MESSAGE);
String PNumberString = JOptionPane.showInputDialog(null, "Please Enter the
ID for paitent #" + i +": ", PatronHeading, JOptionPane.QUESTION_MESSAGE);
enterID = Integer.parseInt(PNumberString);
name = entername;
telephone = enterphone;
ID = enterID;
}
//prints the results
public String Print()
{
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number " +
telephone + " ID " + ID;
return outputString;
}
//gets and sets the PCI in order to sort them
}
Any help? Tried several tactics to fix it and nothing seems to be working. There a lot of code so if you need the full code please let me know!

A problem with your code is that you are using static variables. This means they can only ever have one value
so change
protected static String name;
protected static String telephone;
protected static int ID;
to
protected String name;
protected String telephone;
protected int ID;
edit and clean up your code

Related

How to integrate a loop in my code

I am new to Java. My program first gets inputs from the user about their car, and then it shows the result.
I need to integrate my "Rövarspråk" in to the code, but I am not really sure how.
If the user owns a "Saab" or a "Volvo" the "rövarspråk" loop should change the user's "string name".
If something is unclear, just tell me and I'll try to explain better.
Thanks in advance.
public static void main(String[] args) {
String lookSaab;
String consonantsx;
String input;
String slang;
String add;
// String
int length;
// int
Scanner skriv;
// Scanner
String reg;
String year;
String brand;
String name;
String car;
String when;
String small;
String medium;
String big;
// String
int mod;
int randomNumber;
int quota;
int denominator;
// int
reg = JOptionPane.showInputDialog("Ange registreringsnummer"); // Input plate number of your car
year = JOptionPane.showInputDialog("Ange årsmodell"); // Input model year of the car
mod = Integer.parseInt(year);
brand = JOptionPane.showInputDialog("Ange bilmärke"); //Input car brand
name = JOptionPane.showInputDialog("Ange ägare "
+ "(för - och efternamn)"); //Input owner of the car first name + last name
car = brand + reg;
Date date = new Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE MMM dd");
when = sdf.format(date);
denominator = 1500;
randomNumber = 1500 + (int)(Math.random() * ((40000 - 1500) + 1));
quota = randomNumber / denominator;
small = "Liten service";
medium = "Medium service";
big = "Stor service";
if (randomNumber <= 8000){
JOptionPane.showMessageDialog(null, small, "Typ av service", 1);
} else if ( randomNumber <= 20000){
JOptionPane.showMessageDialog(null, medium, "Typ av service", 1);
} else {
JOptionPane.showMessageDialog(null, big, "Typ av service", 1);
}
String resultat = "Bil: " + car + "\n"
+ "Årsmodell: " + mod + "\n"
+ "Ägare: " + name + "\n"
+ "Mästarställning: " + randomNumber + "\n"
+ "Inlämnad: " + when + "\n"
+ "Klar om: " + quota + " dagar";
JOptionPane.showMessageDialog(null, resultat, "Resulat", 1);
lookSaab = "Saab";
if (brand.equals(lookSaab)){
}
/* Rövarspråket */
consonantsx = "bBcCdDeEfFgGhHjJkKlLmMnNpPqQrRsStTvVwWxXzZ"; //Saves all consonants to string
char consonants[] = consonantsx.toCharArray(); //String to charr
System.out.println("Mata in en mening");
skriv = new Scanner(System.in);
input = skriv.nextLine(); //Saves the input
length = input.length(); //Length inc. space
char array[] = input.toCharArray(); // Input to a char array
slang = "";
System.out.println("På rövarspråk:");
for(int i = 0; i<length; i++) {
for(int x = 0; x<20; x++){
if(array[i] == consonants[x])
{
add = array[i]+"o"+array[i];
slang = slang + add;
break;
}
else{
}
}
}
System.out.println(slang);
}
}
OK so as mentioned a good start would be to put your RoverSpraket translator into its own method:
public String rovarSpraket(String normalString) {
final String consonantsx = "bBcCdDeEfFgGhHjJkKlLmMnNpPqQrRsStTvVwWxXzZ";
char consonants[] = consonantsx.toCharArray(); // String to charr
int length = normalString.length(); // Length inc. space
char array[] = normalString.toCharArray(); // Input to a char array
String slang = "";
System.out.println("På rövarspråk:");
for (int i = 0; i < length; i++) {
for (int x = 0; x < 20; x++) {
if (array[i] == consonants[x]) {
String add = array[i] + "o" + array[i];
slang = slang + add;
break;
} else {
}
}
}
return slang;
}
This method takes a "normal" String as input and returns the Rövarspråk version of it.
Given that it can be used anywhere you want now, like:
/i named my class "Goran" ;)
Goran goran = new Goran(); //instatiate a class object
String hello = "hello world";
System.out.println(goran.rovarSpraket(hello)); //use class object method "roverSpraket"
This will print as the following on the console:
På rövarspråk:
hoheoelollolloldod
Only thing left to do is use this in the remaining code. I guess what you want is that:
if (brand.equals("Saab") || brand.equals("Volvo")){
name = rovarSpraket(name); //translate if brand is Saab or Volvo
}
And a working example for calling the method (one way to do it)
public class Goran {
public static void main(String[] args) {
String brand;
String name;
//i named my class "Goran" ;)
Goran goran = new Goran(); //instatiate a class object
String hello = "hello world";
System.out.println(goran.rovarSpraket(hello)); //use class object method "roverSpraket"
brand = "Saab";
name = "henry";
if (brand.equals("Saab") || brand.equals("Volvo")){
name = goran.rovarSpraket(name); //translate if brand is Saab or Volvo
}
System.out.println("new name is " + name);
}
public String rovarSpraket(String normalString) {
final String consonantsx = "bBcCdDeEfFgGhHjJkKlLmMnNpPqQrRsStTvVwWxXzZ";
char consonants[] = consonantsx.toCharArray(); // String to charr
int length = normalString.length(); // Length inc. space
char array[] = normalString.toCharArray(); // Input to a char array
String slang = "";
System.out.println("På rövarspråk:");
for (int i = 0; i < length; i++) {
for (int x = 0; x < 20; x++) {
if (array[i] == consonants[x]) {
String add = array[i] + "o" + array[i];
slang = slang + add;
break;
} else {
}
}
}
return slang;
}
}
Hope this helps ^^

How Do I Get Customer Input To Display?

I am in an Object-Oriented Programming course in college and I have to use Java to start a program that will eventually incorporate a full on GUI by the end of the course. For the beginning of this project, I have to basically use message boxes to set up how a customer would order a sub to be delivered to their home.
Here's what I have so far:
This is the main class
import javax.swing.*;
//Here is the main class
public class Subs {
public static void main(String[] args) {
// Begin Main Method
char letter;
String input;
String input1, input2, input3, input4, input6, input8;
int input5, input7;
int subL; //length of sub in inches
int cup; //size of drink in ounces
JFrame frame = new JFrame("Message");
JOptionPane.showMessageDialog(frame, "Welcome to Famous Subs! ");
input1 = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");
input2 = JOptionPane.showInputDialog(frame, "Please Enter Your Address: ");
do {
input3 = JOptionPane.showInputDialog(frame, "What kind of sub would "
+ "you like? " +
"\n Turkey Club" +
"\n Philly" +
"\n Meatball" +
"\n Chicken Parm");
input4 = JOptionPane.showInputDialog(frame, "What type of bread? " +
"\n White" +
"\n Wheat" +
"\n Rosemary" +
"\n Italian Herb");
subL = getValidLength();
input6 = JOptionPane.showInputDialog(frame, "What would you like to "
+ "to drink? " +
"\n Water" +
"\n Soda" +
"\n Juice");
cup = getValidCup ();
input8 = JOptionPane.showInputDialog(frame, "Do you wish to continue?\n "+
"'y' or 'Y' for YES\n"+
"'n' or 'N' for NO\n");
Order firstOrder = new Order(input1, input2, input3, input4, input6, subL, cup);
JOptionPane.showMessageDialog(frame, firstOrder.toString());
letter = input1.charAt(0);
}
while (letter == 'Y'|| letter == 'y');
System.exit(0);
}
private static int getValidLength()
{
int s;
String input5;
do{
input5 = JOptionPane.showInputDialog(null, "What size of sub do you wish "
+ "to order? "+
"\n 6 inch"+
"\n 12 inch");
s = Integer.parseInt(input5);
} while (!(s==6 || s==12));
return s;
}
private static int getValidCup()
{
int c;
String input8;
do{
input8 = JOptionPane.showInputDialog(null, "What size drink? " +
"\n Small 12oz." +
"\n Medium 24oz." +
"\n Large 36oz.");
c = Integer.parseInt(input8);
}
while (!(c==12 || c==24 || c==36));
return c;
}
}
This is my subclass
//This is the class for the order
public class Order {
//creating my variables
private String Customer;
private String Address;
private String name;
private String bread;
private String drink;
private int length; //in inches
private int size; //in ounces
private double SubPrice;
private double DrinkPrice;
private double total;
//blank constructor
public Order(){}
//Create a constructor to hold variables
public Order (String Customer, String Address, String name, String bread, String drink, int subL, int cup){
this.Customer = Customer;
this.Address = Address;
this.name = name;
this.bread = bread;
this.drink = drink;
subL = length;
cup = size;
}
//create the getters and setters for the variables
public String getCustomer(){
return Customer;
}
public void setCustomer(String Customer){
this.Customer = Customer;
}
public String getAddress(){
return Address;
}
public void setAddress(String Address){
this.Address = Address;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getBread(){
return bread;
}
public void setBread(String bread){
this.bread = bread;
}
public String getDrink(){
return drink;
}
public void setDrink(String drink){
this.drink = drink;
}
public int getLength(){
return length;
}
public void setLength (int length){
this.length = length;
}
public int getSize(){
return size;
}
public void setSize (int size){
this.size = size;
}
public void setSubPrice (int subL, double SubPrice){
if (subL == 6)
SubPrice = 7.95;
else if (subL == 12)
SubPrice = 12.75;
}
public void setDrinkPrice(int cup, double DrinkPrice){
if (cup == 12)
DrinkPrice = 2.00;
else if (cup == 24)
DrinkPrice = 4.00;
else if (cup == 36);
DrinkPrice = 6.00;
}
public void setTotal(){
total = SubPrice + DrinkPrice;
}
#Override
public String toString(){
String grandOrder = "Greetings " + Customer +
"\nHere is your order: " +
"\n" + name +
"\n" + bread +
"\n" + drink +
"\nThe length of your sub is: " + length +
"\nThe size of your drink is: " + size +
"\nThe Price for your sub is: " + SubPrice +
"\nThe Price for your drink is: " + DrinkPrice +
"\nHere is your total: $" + calculateTotal(DrinkPrice, SubPrice) +
"\nThis will be delivered to: " + Address;
return grandOrder;
}
}
Everything runs just fine except the fact that the last box to show up returns all the string fields as null and the int and double variables as 0 or 0.0.
How do I return the values for what the user inputs on each dialog box? In addition, how do I get he customer's name and address to appear on this final screen? Thanks.
You never initialize fields of your Order. You call constructor without parameters public Order(){}. So you see the default values of the fields.
What you should do:
Be sure that you keep in a variable the value for the name of the client. (input = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");)
Be sure that you keep in variable user's input after "input = JOptionPane.showInputDialog(frame, "What kind of sub would "
+ "you like? " ...".
After get all inputs from the user, create Order object passing user's values
Order firstOrder = new Order(name, bread,drink,int subL, cup);
Change the constructor with parameters like that:
public Order (String name, String bread, String drink, int subL, int cup). You should not pass subPrice and drinkPrice because you Order class already know these values (see setdrinkPrice()). You determine the price of a cup based on the int cup. BTW, can you change the name of the method? Something like setDrinkPrice().
You never call setDrinkPrice() and setsubPrice()(should be setSubPrice(). You can do this when you calculate the total.
Start with these changes and if you have more problems ask .
Okay, a few things are going on here.
Order firstOrder;
firstOrder = new Order();
Can just be written as
Order firstOrder = new Order();
there's no need to do that on two lines. But, more importantly, you've not giving it any parameters, so Java is linking that to the empty constructor (the one that doesn't assign anything.) All of that nice constructor code you have isn't getting called.
To do that, you need to actually do something with those input fields you keep assigning (at the moment you're just ignoring them and writing over them); specifically, you should store them in local variables, and then pass them to the constructor like:
firstOrder = new Order(arg1, arg2, ...)
Also, Order isn't a subclass; it isn't extending anything. (Except Object, but we don't generally call something a subclass just for that.
input = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");
input = JOptionPane.showInputDialog(frame, "Please Enter Your Address: ");
On the first line above, you get the customer's name. then you call the second line, throwing away the customer's name without saving it anywhere.

Looping through an arraylist [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Hi all I'm trying to loop through an array using a password of 4 letters and an ID of 4 int numbers.
Thus far I can create the two 'keys' BUT I can't get them to search for the account on the arraylist I have despite it's creation. I really don't know how to fix this problem since the only way seems to be to just call for an 'If' statement or switch.
Here is where I have the code set up:
int acctID;
int depositingAmount;
//System.out.println("Input your ID and then your password to deposit money.");
String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");
acctID = Integer.parseInt(inputID);
String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");
// int depositAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
{
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword == bankAccounts.get(i).getPassword())//If ID and password work are true then it goes in here.
{
String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
+ "input");//An here is where you would be able to spit out how much money to deposit.
depositingAmount = Integer.parseInt(depositAmount);
bankAccounts.get(i).deposit(depositingAmount);
break;
}
}
Like you can see the loop in theory is suppose to go "Oh okay lets me start going though all of the accounts in the list until I get to yours" and when it finds it "oh hey I found your account, here let me give you the deposit feature". Sorry if I tried to simplify it too much in this paragraph its just that this problem is frustrating me too no end because I know that if I can solve this then the rest of my project is done. I have a withdraw feature also but that's basically the same thing but playing with different methods on the same class.
EDIT: Here are the constructors
public BankAccount() {//ADDED TWO PARAMETERS
//NO ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 999;
//RANDBETWEEN
setAccountBalance(0);
Random passcode = new Random();
//char charcs = (char)(passcode.nextInt(26) + 'a');
//Added string.
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 1000;
setAccountBalance(accountBalance);
//Random passcode = new Random();
//password = (String) (passcode.nextInt(26)) + 'a';
//NEED A VARIABLE TO PASS IN
//4 Digit password
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
An here are the getters..
public int getAccountId() {
return accountId;
}
public String getPassword() {
return password;
}
Also here are the fields I created..
private int accountId;
private double accountBalance;
private static double annualInterestRate = 0.045;
private static java.util.Date dateCreated = new java.util.Date();
private String name;
private String password = "";
Here is where I stand with the If statement
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))
I've seen the other thread that's been posted has a similar question but their answer of just putting .equals() is not enough. Unless i'm stuppose to just take out bankAccounts from the line.
EDIT 2: The entire code.
import java.util.Random;
public class BankAccount {
private int accountId;
private double accountBalance;
private static double annualInterestRate = 0.045;
private static java.util.Date dateCreated = new java.util.Date();
private String name;
private String password = "";
public BankAccount() {//ADDED TWO PARAMETERS
//NO ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 999;
//RANDBETWEEN
setAccountBalance(0);
Random passcode = new Random();
//char charcs = (char)(passcode.nextInt(26) + 'a');
//Added string.
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 1000;
setAccountBalance(accountBalance);
//Random passcode = new Random();
//password = (String) (passcode.nextInt(26)) + 'a';
//NEED A VARIABLE TO PASS IN
//4 Digit password
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public int getAccountId() {
return accountId;
}
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double accountBalance) {
this.accountBalance = accountBalance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public void withdraw(double amountToWithdraw) {
if (amountToWithdraw > accountBalance) {
//putting together withdraw make sure to have a validation to stop ppl from going over.
System.out.println("Sorry you cannot exceed the amount you have in your balance.");
}
else {
accountBalance = accountBalance - amountToWithdraw;
}
}
public void deposit(double amountToDeposit) {
if (amountToDeposit < 0) {
//deposits cannot be negative
System.out.println("You cannot deposit a negative amount of dallars.");
}
else {
accountBalance = accountBalance + amountToDeposit;
}
}
public double getMonthlyInterestRate() {
int MonthsInAYear = 12;//method variable is small BUT just need to get results
double monthlyInterestRate = annualInterestRate / MonthsInAYear;
return monthlyInterestRate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString(){
String bankInfo = " Password: " + getPassword() + " Account ID: " + getAccountId();
return bankInfo;
}
}
public class CurrentAccount extends BankAccount{
private static float overdraftLimit = 100;
CurrentAccount(){
super();
}
public static float getOverdraftLimit() {
return overdraftLimit;
}
// MAKE A SETTER FOR THE OVERDRAFTLIMIT
public void withdraw(double amountToWithdraw){
if (amountToWithdraw <= getAccountBalance()+overdraftLimit) {
setAccountBalance(getAccountBalance() - amountToWithdraw);
}
else {
System.out.println("Error this transaction has been cancelled.");
}
}
}
public class SavingsAccount extends BankAccount{
private static double interest;
public SavingsAccount (){
super();
interest = 0;
}
public void addInterest(){
interest = getAccountBalance() * getMonthlyInterestRate(); //GETTING ZEROS FROM ACCOUNTBALANCE
//CHANGE getAccountBalance with some other initial payment.
super.deposit(interest);
}
public double getInterest() {
return interest;
}
public void setInterest(float interest) {
this.interest = interest;
}
}
public class Bank {
Scanner input = new Scanner(System.in);
Scanner Restart = new Scanner(System.in);
private static ArrayList<BankAccount> bankAccounts; // MADE THIS STATIC
public Bank() {
bankAccounts = new ArrayList<BankAccount>();
}
public void openAccount() {
Object[] possibilities = {"Regular Account", "Savings Account", "Checking Account"};
Object inputValue = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, possibilities, possibilities [0]);
if (inputValue.equals("Regular Account")) {
// Make a regular acct
String inputName = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new BankAccount();
newBankAccount.setName(inputName);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
} else if (inputValue.equals("Savings Account")) {
// Make a savings acct
String inputNameSavings = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new SavingsAccount();
newBankAccount.setName(inputNameSavings);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
} else if (inputValue.equals("Checking Account")) {
// Make a checking acct
String inputNameChecking = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new CurrentAccount();
newBankAccount.setName(inputNameChecking);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
}
}
public static ArrayList<BankAccount> getBankAccounts() {
return bankAccounts;//Moving this into the Open.Account?
}
public void closeAccount() {
System.out.println("Hello give me the name of the" + " "
+ "account you would like to close.");
String userName = input.next();// Gets input for first choice.
// Ask for account id
System.out.println("Please input your account ID");
int userAccountId = input.nextInt();
for (int i = 0; i < bankAccounts.size(); i++) {
if (bankAccounts.get(i).getName().equals(userName)
&& bankAccounts.get(i).getAccountId() == userAccountId) {
bankAccounts.remove(i);
System.out.println("Account removed");
}
}
// anyway, you would set the name probably in the constructor function
// for that particular instantiation of the class
}
public void update() {
// UPDATES MY ACCOUNTS
for (int i = 0; i < bankAccounts.size(); i++) {
if (bankAccounts.get(i) instanceof SavingsAccount) {
((SavingsAccount) bankAccounts.get(i)).addInterest();
} else if (bankAccounts.get(i) instanceof CurrentAccount) {
if (bankAccounts.get(i).getAccountBalance() < 0) {
System.out.println("\nThe Account: " + bankAccounts.get(i).getName() + " has been OverDrafted.\n");
}
}
}
}// ends update
public void withdraw(){
System.out.println("Input your ID and then your password to withdraw money.");
int acctID = input.nextInt();
int withdrawAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++){
//input needed.
if (acctID == bankAccounts.get(i).getAccountId()){
System.out.println("We have found your account. Please input how much money you would like to withdraw.");
withdrawAmount = input.nextInt();
bankAccounts.get(i).withdraw(withdrawAmount);
break;
}
// } while (input != 1);
}
}
public void deposit(){
int acctID;
int depositingAmount;
//System.out.println("Input your ID and then your password to deposit money.");
String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");
acctID = Integer.parseInt(inputID);
String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");
// int depositAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
{
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))//If ID and password work are true then it goes in here.
{
String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
+ "input");//An here is where you would be able to spit out how much money to deposit.
depositingAmount = Integer.parseInt(depositAmount);
bankAccounts.get(i).deposit(depositingAmount);
break;
}
}
}
}
An finally the class i'm running it on...
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class TestBankAccount {
public static void main(String[] args) {
// JOptionPane.showMessageDialog(null, "Hello User.");
Object[] menuPossibilities = {"Create a New Account", "Deposit", "Withdraw", "Display Balance", "Exit"};
Object menuValues = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
while (!menuValues.equals("Exit")){
Bank newBank = new Bank();
// Bank newBank1 = new Bank();
// Bank newBank2 = new Bank(); Do the same thing as below but switch out
// bank1 and bank2 as a substitute.
ArrayList<BankAccount> bankList = newBank.getBankAccounts();
if (menuValues.equals("Create a New Account")){
newBank.openAccount();
}
else if (menuValues.equals("Deposit")){
newBank.deposit();
}
else if (menuValues.equals("Withdraw")){
newBank.withdraw();
}
else if (menuValues.equals("Display Balace")){
newBank.deposit();
}
else if (menuValues.equals("Exit")){
System.out.println("Thank you for using our service.");
}
menuValues = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
}
}
}
Use .equals method to check strings for equality.

can not be assigned to a variable error in eclipse (homework)

I am building on a ordering program for java for a class in school and I am getting quantityInput can not be resolved to a variable error I also get the error
the method showInputDialog(Component, Object, Object) in the type JOptionPane is not applicable for the arguments (String, int, int)
any help in resolving the 2 errors would be much aprecated.
/**
* Course: IT110 - Introduction to Programming
* Filename: KagesKreationsPhase1.java
* Created: 04/09/10 by Dr. Debby Telfer
* Modified: 11/26/13 by Dr. Bary W Pollack
*
* Purpose: Created a simple online ordering system
* for Pizzas-R-Us customers
*/
import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;
/**
* #author bary
*/
public class KagesKreations {
/**
* #param args
*/
public static void main(String[] args) {
// declare variables
String openingMsg, nameInputMsg, customerName, nameOutputMsg, getReturning, getColor, getQuantity,
returnInputMsg, customerReturn, returnOutputMsg, quantityMsg, quantityOutputMsg, totalOutputMsg,
colorChoiceMsg, colorChoice, colorChoiceOutputMsg, greetingOutputMsg, outputMsg, quantityInput, getname;
int number = 0;
double cost = 10.00;
double taxRate = 1.07;
double total;
try {
// display opening message
openingMsg = "*** Welcome to Kage's Kreations Online Ordering System ***\n"
+ " Lets Pick A Kustiom Kreation!";
JOptionPane.showMessageDialog(null, openingMsg);
// get required input using dialogs
customerName = getName();
customerReturn = getReturning();
colorChoice = getColor();
quantityInput = getQuantity();
number = Integer.parseInt(quantityInput);
KagesKreations.totalCost(number, cost, taxRate);
total = totalCost(number, cost, taxRate);
writeOrderFile(customerName, customerReturn, colorChoice,quantityInput, total);
confirmation();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
System.exit(1);
}
} // end main()
public static String getStringInput(String prompt) throws Exception {
String value;
int i = 0;
do {
value = JOptionPane.showInputDialog(prompt);i++;
if (value == null) {
throw new Exception("Cancle was pressed. Closeing the program.");
}
} while (value.equals("") && i < 3);
if (value.equals("")) {
throw new Exception("No input vale was entered after three attempts.");
}
return value;
}
public static int getQuantity(int lowValue, int highValue) throws Exception {
// quantity must be between 1-99
int quantity;
int counter = 0;
int quantityInput;
do {
quantityInput = Integer.parseInt(JOptionPane.showInputDialog("How many bracelets would you like to order? (1-99)", 1, 99));
counter = counter + 1;
} while (quantityInput < lowValue || quantityInput > highValue && counter < 3);
if (quantityInput < lowValue || quantityInput > highValue) {
throw new Exception("Invalid responce please enter a number between 1 and 99");
}
quantity = quantityInput;
return quantity;
}
public static String getColor() throws Exception {
String color;
int counter = 0;
do {
color = JOptionPane.showInputDialog("Please choose Brown or Black for the color of your bracelet");
counter = counter + 1;
} while (!color.equals("Brown") && !color.equals("Black") && counter < 3);
if (!color.equals("Brown") && !color.equals("Black")) {
throw new Exception("Invalid responce please enter Brown or Black.");
}
return color;
}
public static String getReturning() throws Exception {
String returning;
int counter = 0;
do {
returning = JOptionPane.showInputDialog("Are you a returning customer? (Yes or No)");
counter = counter +1;
} while (!returning.equals("Yes") && !returning.equals("No") && counter < 3 );
if (!returning.equals("Yes") && !returning.equals("No")) {
throw new Exception("Invalid responce please enter Yes or No.");
}
return returning;
}
public static String getName() throws Exception {
String name;
int counter = 0;
do {
name = JOptionPane.showInputDialog("Please Enter your name.");
counter = counter + 1;
} while (counter < 3);
return name;
}
public static double totalCost(int number, double cost, double taxRate){
double total = 0;
total = (number * cost) * taxRate;
return total;
}
public static void writeOrderFile(String name, String returning, String color, String quantity, double total) throws Exception {
File order = new File("order.tx");
PrintWriter pw = new PrintWriter(order);
pw.println(name);
pw.println(returning);
pw.println(color);
pw.println(quantity);
pw.println(total);
pw.close();
}
public static void confirmation() throws Exception{
String nameOutputMsg, customerName, returnOutputMsg, customerReturn, colorChoiceOutputMsg, colorChoice, quantityOutputMsg, quantityInput,
totalOutputMsg, total, greetingOutputMsg, outputMsg;
FileReader fr = new FileReader("order.txt");
BufferedReader bf = new BufferedReader(fr);
customerName = bf.readLine();
customerReturn = bf.readLine();
colorChoice = bf.readLine();
quantityInput = bf.readLine();
total = bf.readLine();
fr.close();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
colorChoiceOutputMsg = "You have chosen " + colorChoice + " as the color for your braclet.\n";
quantityOutputMsg = "You have ordered " + quantityInput + " bracelets.\n";
totalOutputMsg = "Your total cost is $" + total + ".\n";
greetingOutputMsg = "Thank you for visiting Kage's Kreations!" + "\n\n"
+ "Your order should ships in 24 to 48 hours.\n";
// create and display output string
outputMsg = nameOutputMsg + returnOutputMsg + colorChoiceOutputMsg + quantityOutputMsg + totalOutputMsg + greetingOutputMsg;
JOptionPane.showMessageDialog(null, outputMsg);
}
} // end class KagesKreationsPhase1
The second prolem is that JOptionPane just does not provide any method that matches the arguments you try to pass in your getQuantity-mehod:
quantityInput = Integer.parseInt(JOptionPane.showInputDialog("How many bracelets would you like to order? (1-99)", 1, 99));
You have to chose one of the existing methods.
You should declare a variable before using it. You can declare the variable inside the getQuantity() or in class level (Please read much about local and class variables). you can declare it as the way you declared quantity and counter variables.
public static int getQuantity(int lowValue, int highValue) throws Exception {
// quantity must be between 1-99
int quantity;
int counter = 0;
int quantityInput = 0;
...
}
In your code I can't find a place where you are using showInputDialog() with String, int, int parameters. Please share the full code your trying.

increment constructor with medhod

Create a class Student which is derived from the class Person from
homework 1. The class has the member variables:
facultyNumber - a
String, which will be initialized to value "426789XX" where the XX is
the serial number of the object created in the program (if the program
has created 3 objects, the value of XX respectively will be - 00, 01
and 02).
notes – an array of 20 int values in the interval [2,6]. The
elements of the array will be initialized with the values 1.
and the methods:
void takeExam(int index, int note) - assign the value note
to the element in position index
void failExam(int index) – assign
the value 2 to the element in position index
public String toString ()
- convert the Student to String
i have some thing like this homework and where i m doing mistake i dont know little help i m completely newbie for java
public class Student extends Person {
Student() {
facultyNumber = String.valueOf(Integer.parseInt(facultyNumber) + 1);
System.out.print(" Faculty Number: ");
System.out.print(facultyNumber);
Scanner in = new Scanner(System.in);
System.out.print(" Enter notes: ");
int notes = in.nextInt();
}
Student(String name, int age, String facultyNumber, int notes) {
super(name, age);
}
String facultyNumber = "42678900";
int[] notes ={1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
void takeExam(int index, int note) {}
void failExam(int index){ Arrays.fill(notes, 2); }
public String toString () {
return "name: " + name + " age: " + age + " Faculty Number: " + facultyNumber +" notes: " + notes ;
}
}
i think i should do some counting for chance faculty no increment but i dont know how to start anybody can help step by step.
Well, a homework question.
public class Student extends Person {
private static final int VALUE_EXAM_FAIL = 2;
private String facultyNumber = "426789XX";
private int[] notes = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
//a new object is instantiated from outside this class,
//therefore they have to tell this constructor the facultyNumber (or you use a static facultyNumber)
public Student(int facultyNumber) {
this.facultyNumber = this.facultyNumber.replace("XX", String.valueOf(facultyNumber)); //think about problems if facultyNumber only has 1 digit.
}
public Student(String name, int age, int facultyNumber, int[] notes) {
super(name, age); //what is this?
this(facultyNumber); //and this?
this.notes = notes;
}
public void takeExam(int index, int note) { notes[index] = note; } //what happens here if index = -1 or 99?
public void failExam(int index) { notes[index] = VALUE_EXAM_FAIL; }
#Override
public String toString () {
return "class: " + this.getClass.getSimpleName()
+ " name: " + this.name
+ " age: " + this.age
+ " Faculty Number: " + this.facultyNumber
+ " notes: " + this.notes ; //this could be nicer!
}
}
Use access modifiers like public/private!
This should help you getting started. Think about: should I read from the console here in this class? If yes, how? If no, why not?
i solve my problem like this its working
import java.util.*;
public class Student extends Person {
private static final int VALUE_EXAM_FAIL = 2;
private String facultyNumber = "426789XX";
private int[] notes = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
static int index = 0;
private int ind;
Student(){
ind = index;
index++;
this.facultyNumber = this.facultyNumber.replace("XX", String.format("%02d", ind));
Scanner in = new Scanner(System.in);
boolean goodinput = false;
int num = 0;
do {
try {
goodinput = true;
System.out.print("Notes [2,6]:");
num = notes[ind] = Integer.parseInt(in.nextLine());
System.out.println(num);
if ((num < 2) || (num > 6)) {
System.out.println("Input not between 2 and 6, try again.");
goodinput = false;
}
} catch (Exception e) {
System.out.println("Input is not an integer, try again.");
goodinput = false;
}
} while (!goodinput);
}
public Student(String name, int age, int facultyNumber, int[] notes) {
super(name, age);
this.facultyNumber = Integer.toString(facultyNumber);
this.notes = notes;
}
public void takeExam(int index, int note) { notes[ind] = note; }
public void failExam(int index) { notes[ind] = VALUE_EXAM_FAIL; }
#Override
public String toString () {
return super.toString() + " Faculty Number: " + this.facultyNumber
+ " notes: " + this.notes[ind]+ " " + ind;
}
}

Categories

Resources