Scanner cant read/incorrectly reading my input - java

I am writing a code whereby I have to input people's name and money value. However I have used a scanner but it does not read the name that I input into the console. Whatever name I put, the code will tell me that no such name is found. I have tried for many hours trying to resolve this, assistance would be appreciated! (there are 6 total cases but I only posted the first one since its the only one I'm having problems with)
The code is as such:
import java.util.Scanner;
public class Client {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
Change[] changeArray = new Change [10];
int numNames = 0;
System.out.println("Please enter at least 10 records to test the program");
String name = "";
int change = 0;
int flag = 0;
int[] totalNumberOfCoinsOf = {0,0,0,0,0};
for (int i = 0;i < changeArray.length;i++)
{
System.out.println("Enter name: ");
name = reader.nextLine();
do {
System.out.println("Enter coin value for the person");
change = Integer.parseInt(reader.nextLine());
if (change % 5 ==0) {
break;
}else if (change % 5 <2.5) {//round down to nearest 5 if change is less than 2.5
change = change - change %5;
break;
}
else if (change %5>=2.5)
{
change = Math.round(change * 100)/100; //round up to nearest 5 if change is more than 2.5
}
}while (true);
changeArray[i] = new Change(name, change);
numNames++;
do {System.out.println("Do you have another person to enter? (Y/N) ");
String choice = reader.nextLine();
if (i!=changeArray.length - 1) {
if(choice.toUpperCase().equals("Y")) {
break;
}else if (choice.toUpperCase().equals("N")) {
flag = 1;
break;
}
}
}while(true);
if (flag==1) {
break;
}
}
do {
System.out.println("\n[1] Search by name ");
System.out.println("\n[2] Search largest coin");
System.out.println("\n[3] Search smallest coin");
System.out.println("\n[4] Total coins");
System.out.println("\n[5] Sum of coins");
System.out.println("\n[6] Exit the program");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(reader.nextLine());
switch (choice) {
case 1:
System.out.print("Enter name to search: ");
name = reader.nextLine();
flag = 0;
for (int i = 0;i < numNames; i++) {
if (name.equals(changeArray[i].getName())) {
System.out.println("Customer: ");
System.out.println(changeArray[i].getName() + " " + changeArray[i].getCoinChangeAmount());
int[] coins = changeArray[i].getChange();
System.out.println("Change: ");
if(coins[0]!=0) {
System.out.println("Dollar coins: "+coins[0]);
}
if(coins[1]!=0) {
System.out.println("50 cents: "+coins[1]);
}
if(coins[2]!=0) {
System.out.println("25 cents: "+coins[2]);
}
if(coins[3]!=0) {
System.out.println("10 cents: "+coins[3]);
}
if(coins[4]!=0) {
System.out.println("5 cents: "+coins[4]);
}
flag++;
}
}
if (flag==0) {
System.out.println("Name: "+name);
System.out.println("Not found! ");
}
break;
//Change class
import java.util.Scanner;
public class Change {
private String name;
private int coinChangeAmount;
public Change() {
this.name = "no name";
this.coinChangeAmount = 0;
}
public Change(String name, int coinChangeAmount) {
this.name = "name";
this.coinChangeAmount = coinChangeAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoinChangeAmount() {
return coinChangeAmount;
}

Related

Is it possible to create a text file and then on the same run or runtime of the code also read and write in these files? Java

I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.
The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.
Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?
import java.util.Scanner;
import java.io.*;
public class FileManagement {
static String pathnameFile = "src\\Log";
static File directory = new File(pathnameFile);
static String[] allFiles = directory.list();
public static void createFolder() {
File logFile = new File(pathnameFile);
if (!logFile.exists()) {
logFile.mkdir();
}
}
public static void writeFiles() throws IOException {
FileWriter writer;
for (int i = 0; i < allFiles.length; i++) {
writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
writer.close();
}
}
//original method
/*public static void readFiles() {
Scanner reader;
for (int i = 0; i < allFiles.length; i++) {
reader = new Scanner(pathnameFile + allFiles[i]);
}
}*/
//My solution
public static void readFiles() throws IOException{
if(directory.exists() == false || allFiles == null) {
return;
}
Scanner reader;
File currentFile;
String[] data = new String[4];
for(int i = 0; i < allFiles.length; i++) {
currentFile = new File(pathnameFile + "\\" +allFiles[i]);
reader = new Scanner(currentFile);
int count = 0;
while(reader.hasNextLine()) {
if(!reader.hasNext()) {
break;
}
reader.next();
data[count] = reader.next();
count++;
}
reader.close();
String accountName = data[0];
String PIN = data[1];
int balance = Integer.parseInt(data[2]);
eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
}
}
}
import java.util.Scanner;
import java.io.*;
public class App {
public static eBanking currentAccount;
public static void mainMenu() throws Exception{
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("""
--------------------------------------------------------
1. Log in
2. Register
0. Exit.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
System.out.println("Please enter your account name and PIN below.");
System.out.print("Account name: ");
String accountName = input.next();
System.out.print("PIN: ");
String PIN = input.next();
System.out.println();
for (int i = 0; i < eBanking.accounts.length; i++) {
if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
eBanking.accounts[i].welcome();
currentAccount = eBanking.accounts[i];
break;
}
}
menu();
}
case 2 -> {
System.out.println("Please enter the account name, PIN and inital balance of your new account.");
System.out.print("Account name:");
String accountNameRegister = input.next();
System.out.print("PIN: ");
String registerPIN = input.next();
System.out.print("Initial balance: ");
int initialBalance = input.nextInt();
currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
menu();
}
default -> {
FileManagement.writeFiles();
System.exit(0);
}
}
}
}
public static void menu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("""
--------------------------------------------------------
1. Show your balance.
2. Withdraw money.
3. Deposit money.
4. Change your PIN.
5. Transfer money to another person.
0. Back.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
currentAccount.showBalance();
}
case 2 -> {
System.out.println("Please enter the amount you want to withdraw: ");
int withdrawAmount = input.nextInt();
currentAccount.withdraw(withdrawAmount);
}
case 3 -> {
System.out.println("Please enter the amount you want to deposit: ");
int depositAmount = input.nextInt();
currentAccount.deposit(depositAmount);
}
case 4 -> {
currentAccount.changePIN();
}
case 5 -> {
System.out.println("Please enter the amount you want to send: ");
int amount = input.nextInt();
System.out.println("Please enter the account number you want to send the money to: ");
String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)
System.out.println("The amount of money is completed");
currentAccount.transfer(amount, transferAccount);
}
case 0 -> {
return;
}
default -> {
System.out.println("Please enter a number from the menu list!");
}
}
}
}
public static void main(String[] args) throws Exception {
FileManagement.createFolder();
FileManagement.readFiles();
mainMenu();
}
}
import java.util.Scanner;
import java.io.*;
public class eBanking extends BankAccount {
// Variable declaration
Scanner input = new Scanner(System.in);
private String accountName;
private String accountID;
public static eBanking[] accounts = new eBanking[100];
// Methods
public String getAccountName() {
return accountName;
}
public void welcome() {
System.out.println("---------------------------------------------------------------------------------------");
System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
}
public void transfer(int x, String str) {
boolean foundID = false;
withdraw(x);
if (initialBalance == 0) {
System.out.println("Transaction failed!");
} else if (initialBalance < x) {
for(int i = 0; i < numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += initialBalance;
System.out.println("Transaction completed!");
foundID = true;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += initialBalance;
return;
}
} else {
for(int i = 0; i <= numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += x;
System.out.println("Transaction completed!");
foundID=true;
return;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += x;
return;
}
}
}
// Constructors
public eBanking(String name){
int firstDigit = (int)(Math.random() * 10);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);
int forthDigit = (int)(Math.random() * 10);
accountID = this.toString();
PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha
balance = 0; //dhe nuk duhet ta perseris per the gjitha
accountName = name;
accounts[numberOfAccount] = this;
numberOfAccount++;
System.out.println("---------------------------------------------------------------------------------------");
System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
}
public eBanking(String name, String pin, int x){
if (checkPIN(pin) == false) {
System.out.println("Incorrect PIN format!");
return;
}
accountID = this.toString();
accountName = name;
balance = x;
PIN = pin;
accounts[numberOfAccount] = this;
numberOfAccount++;
welcome();
}
}
import java.util.Scanner;
public abstract class BankAccount {
// Variable declaration
protected String PIN;
protected int balance;
public static int numberOfAccount = 0;
protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();
//Methods
//Balance
public int getBalance() {
return balance;
}
public void showBalance() {
System.out.println("The total balance of the account is " + balance);
}
public void withdraw(int x) {
initialBalance = balance;
if (balance == 0) {
System.out.println("The deduction has failed due to lack of balance!");
return;
}
if (balance < x) {
balance = 0;
System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
} else {
balance -= x;
System.out.println("The deduction of " + x + " from your balance is completed!");
}
}
public void deposit(int x) {
balance += x;
System.out.println("You have made a deposit of " + x + " and your current balance is " + balance);
}
//PIN
public String getPIN() {
return PIN;
}
public void changePIN() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your previous PIN: ");
String tryPIN = input.nextLine();
if (tryPIN.equals(PIN)) {
System.out.print("Please enter your new PIN: ");
String newPIN = input.nextLine();
if (checkPIN(newPIN) == false) {
System.out.println("The PIN is not in the correct format!");
} else {
System.out.println("The PIN has been changed");
PIN = newPIN;
}
} else {
System.out.println("The PIN does not match!");
}
}
protected static boolean checkPIN(String str) {
boolean isValid;
if(str.length() != 4) {
isValid = false;
} else {
try {
int x = Integer.parseInt(str);
isValid = true;
} catch (NumberFormatException e) {
isValid = false;
}
}
return isValid;
}
//Kjo metode duhet per testim
public void getDetails() {
System.out.println(balance + " and PIN " + PIN);
}
}
I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.
I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.
I have provided all the current code on my program and the fix I implemented on FileManagment class

May someone help me check how to create a list?

guys, am doing java programing and try to make a list, but i cannnot let it work as i expected, please help me find out where is wrong.
i have create the code on BlueJ and try to make main and method in different part, but when i try to add a variable in list, it seems added but wont present correctly, and remove method will call error and shut down the whole program
one is :
import java.util.ArrayList;
public class Plane
{
//Create 3 types of variables.
private String name;
private int safelength;
private short station;
private String passengername;
private static int seat;
private static int age;
private ArrayList<Passenger> Passengers;
public Plane(String psgname, int psgseat, int psgage)
{
psgname = passengername;
psgseat = seat;
psgage = age;
Passengers = new ArrayList<Passenger>();
}
public Plane(String planename, int maxlength, short astation)
{
name = planename;
safelength = maxlength;
station = astation;
}
public void addPassenger(Passenger Passenger)
{
Passengers.add(Passenger);
}
public void addPassenger(String passengernames, int pseat, int page)
{
Passengers.add(new Passenger(passengername, seat, page));
}
public Passenger findPassenger(String find)
{
for(Passenger ps : Passengers)
{
if(ps.getpname().contains(find))
{
return ps;
}
}
return null;
}
public int numberofPassenger()
{
return Passengers.size();
}
public void removePassenger(int number)
{
if (number >= 0 && number <numberofPassenger())
{
Passengers.remove(number);
}
}
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
public void setname(String n)
{
name = n;
}
public String getname()
{
return name;
}
public void setsafelength(int s)
{
safelength = s;
}
public int getsafelength()
{
return safelength;
}
public void setstation(short a)
{
station = a;
}
public short getstation()
{
return station;
}
public String toString()
{
String text = "System checked, " + getname() + ", you can prepare yourself at station " + getstation() + " with the maxlength of " + getsafelength() + " metres.";
return text;
}
}
another one is :
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private static String pname;
private static int seat;
private static int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(pname, seat, age);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public static void setpname(String pn)
{
pname = pn;
}
public static String getpname()
{
return pname;
}
}
Problem 1.
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
Here you are printing the value of instance variable,not the passenger's name.To print it, do
System.out.println(Passengers.get(index).getpname());
but this will return null,because your pname is static and you have never initialized its value.For this,change all yor static varibales to non-static.
Problem 2.
Passenger padd = new Passenger(pname, seat, age);
you are storing passenger's name seat age in x y zvariables respectively,butduring the creation of Passenger ,you are using pname seat age variables, which are null.So here do
Passenger padd = new Passenger(x, y, z);
At last,change every static variable and methods to non-static.
Final Solution will look like this,
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private String pname;
private int seat;
private int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(x, y, z);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public void setpname(String pn)
{
pname = pn;
}
public String getpname()
{
return pname;
}
}

Why is my program not accepting input through the console? (Java)

I know it's a silly silly program. It's just to practice constructors.
public class PetRecord {
private String name = "Bob";
private int age;
private double weight;
public PetRecord(String initialName, int initialAge, double initialWeight) {
name = initialName;
if(initialAge < 0 || weight < 0) {
System.out.println("Error: Age or weight cannot be negative");
System.exit(0);
}
else {
age = initialAge;
weight = initialWeight;
}
}
public PetRecord(String initialName) {
name = initialName;
}
public void output() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
}
public void setAll(String newName, int newAge, double newWeight) {
name = newName;
if ((newAge < 0) || (newWeight < 0)) {
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else {
age = newAge;
weight = newWeight;
}
}
public void review() {
if(age < 8 && weight < 8) {
System.out.println("Your pets weight and age are healthy.");
}
if(age >= 8 && weight >=8) {
System.out.println("Your pets weight and age are unhealthy.");
}
else {
System.out.println("Come to my office for a proper assessment.");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PetRecord d = new PetRecord("Bob");
System.out.println("Please check if our current records are correct.");
d.output();
System.out.println("Are they correct?");
String answer = input.nextLine();
String yes = "Yes";
String no = "No";
if((answer.equals(yes))) {
System.exit(0);
}
if(answer.equals(no)) {
System.out.println("Please enter your pets name.");
String correctName = input.nextLine();
System.out.println("Age?");
int correctAge = input.nextInt();
System.out.println("Weight?");
double correctWeight = input.nextDouble();
d.setAll(correctName, correctAge, correctWeight);
System.out.println("Your updated records say: ");
d.output();
System.out.println("Would you like a health review?");
String answer1 = input.nextLine();
String yes1 = "yes";
String no1 = "no";
if(answer1.equals(yes1)) {
d.review();
}
if(answer1.equals(no1)) {
System.out.println("Thank you for using PetSystem. Goodbye.");
System.exit(0);
}
}
}
}
My program accepts input for String answer, but my program will not accept String answer1. I can't even type anything in the console after the program asks you if you would like a health review.
The issue comes from here
System.out.println("Your updated records say: ");
d.output();
Because you have printed something out in the middle of accepting input, you most likely have an extra newline token you have not dealt with. Prior to asking the "health review" question place the following code.
while (input.hasNextLine()) {
input.nextLine();
}
This will make sure that you clear out any extra tokens before continuing to accept user input.
you can,t type anything in the console after "if you would like a health review." because you code only runs ones you should put it in a loop to make it run more than once

Bank Program error when I try to access an account that does not exist

I have been working on this bank program for my Java class at school for the past week and a half. I thought I finally had it working the way my instructor wanted. However, when I try to access an account that does not exist, the program "blows up" (my instructors words). I need it to let the user know that the account does not exist and redirect them back to the main menu. So, my problem I believe is in my findAcct method in my Bank class. I have tried several fixes but none have worked. Any insight or help would be greatly appreciated! I need to have this done by Monday. I know I said the problem is in one method, but I'll post my whole program for context.
Bank Class
import java.util.Scanner;
public class Bank
{
private int max = 25;
private int count;
bankAcct myAcct[] = new bankAcct[max];
Scanner scannerObject = new Scanner(System.in);
public void openAcct()
{
if (count >= max){
System.out.println("Not accepting new customers at this time.");
}else{
System.out.println("Please enter your name: ");
String lname = scannerObject.next();
myAcct[count] = new bankAcct(count + 1, 25, lname);
count++;
System.out.println("Thank you " + lname + ", your account number is: " + count);
}
}
public int findAcct() // This is the method in question
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
found = i;
}
}
return found;
}
public void seeBal()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].dispBal();
}
}
public void Deposit()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].makeDeposit();
}
}
public void Withdrawal()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].makeWithdrawal();
}
}
}
bankAcct Class
import java.util.Scanner;
public class bankAcct
{
private double Bal;
private int acctNum;
private String name;
Scanner scannerObject = new Scanner(System.in);
public bankAcct(int pAcctNum, double pBal, String pName)
{
Bal = pBal;
acctNum = pAcctNum;
name = pName;
}
public void makeDeposit()
{
System.out.print( "Hello " + name + ", please, enter amount to deposit $");
double lDep = scannerObject.nextDouble();
Bal = Bal + lDep;
System.out.println( " You have deposited $" + lDep);
System.out.println( " Your new balance is $" + Bal);
}
public void makeWithdrawal()
{
System.out.print( "Hello " + name + ", please, enter amount to withdraw $");
double lWDraw = scannerObject.nextDouble();
if (lWDraw <= Bal){
Bal = Bal - lWDraw;
System.out.println( "You have withdrawn $" + lWDraw);
System.out.println( "Your new balance is $" + Bal);
}else{
System.out.println("Insufficient funds!");
}
}
public void dispBal()
{
System.out.println( "Hello " + name + ", your current balance is $" + Bal);
}
public int getAcctNum()
{
return acctNum;
}
public void setName(String pName)
{
name = pName;
}
public String getName()
{
return name;
}
}
bankUser Class
import java.util.Scanner;
public class bankUser
{
public static void main(String[] args)
{
Bank myBank = new Bank();
int Choice;
do
{
dispMenu();
Choice = getChoice();
proChoice(Choice, myBank);
}
while (Choice !=0);
}
public static void dispMenu()
{
System.out.println( "|==================================|");
System.out.println( "| TONY'S FIRST NATIONAL BANK |");
System.out.println( "|***********Menu Options***********|");
System.out.println( "|__________________________________|");
System.out.println( "| Press [1] To Open New Account |");
System.out.println( "| Press [2] To View Balance |");
System.out.println( "| Press [3] To Make Deposit |");
System.out.println( "| Press [4] To Make Withdrawal |");
System.out.println( "| Press [0] to Exit |");
System.out.println( "|__________________________________|");
System.out.println( "| Please Make Selection Now... |");
System.out.println( "|==================================|");
}
static int getChoice()
{
Scanner scannerObject = new Scanner(System.in);
int pChoice, Choice;
pChoice = scannerObject.nextInt();
Choice = pChoice;
return Choice;
}
static void proChoice(int Choice, Bank myBank)
{
switch (Choice)
{
case 1: myBank.openAcct();
break;
case 2: myBank.seeBal();
break;
case 3: myBank.Deposit();
break;
case 4: myBank.Withdrawal();
break;
case 0: System.out.println( "Thank you, come again.");
break;
}
}
}
Again, any help would be greatly appreciated. I am still a padawan when it comes to Java.
*UPDATE: I have tried this code, and it seems to work! However, my instructor told me that we can never have 2 return statements within a method.
public int findAcct()
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
return found = i;
}
}
return -1;
}
UPDATE: Here is what I did to my findAcct method in my Bank Class:
public int findAcct()
{
System.out.println("Greetings, please enter your account number: ");
int acctNum = scannerObject.nextInt();
int found = -1;
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == acctNum){
found = i;
break; //Ends Loop
}
}
return found;
}
My instructor did not mind a break statement, so I added out at the end of my for loop. I also moved my local variable found = -1; down a couple lines. Thank you for all the help! I can't wait to learn more!
If you do not want to have 2 return statements within a method (which you can have, but sometimes it is bad practice when you are beginning coding so professors like to just make that rule) you can use your found variable to store the value that will be returned and return found at the end of the function.
You were on the right track.
Example:
public int findAcct()
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
found = i;
break; //Exit out of the loop
}
}
return found;
}
This code will set found to i if it finds the account and then break out of the loop. After it breaks out of the loop it will return found. Otherwise, found will never be set and return -1 since you initialized it to -1 at the top.
If your instructor has not taught you break statements yet, then you can use a boolean variable foundAccount initialized to false. Then check if foundAccount is false before doing your if statement check. Once you find it, set it to true so you do not keep looking.
Example:
public int findAcct()
{
int found = -1;
boolean foundMatch = false;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(!foundMatch){
if(myAcct[i].getAcctNum() == found){
found = i;
foundMatch = true; //we will no longer search
}
}
}
return found;
}

how to find two's best answers

I am trying to find two's greatest numbers that are entered from the console.
I found the first one, but the solution for the second one is not working. The program is compiling and running. Here is the code.
import java.util.Scanner;
public class FindingSecondHighestScore_4_09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double max = 1;
double score2 = 0;
String firstName = "";
String secondName = null;
System.out.println("Enter number of students: ");
int x = input.nextInt();
while(x > 0)
{
System.out.println("Enter Sudent's name");
String name = input.next();
System.out.println("Enter Student's score");
double score = input.nextDouble();
//find max
if(score > max)
{
max = score;
firstName = name;
}
//find second max
if(max < score2 || score < score2)
{
max = score2;
score = score2;
}
else if(max > score2 && score2 < score)
{
score2 = score;
secondName = name;
}
x--;
}
System.out.println("The student: " + firstName + " has the greatest score: " + max);
System.out.println("Second studemt " + secondName + " with second results: " + score2);
}
}
Here is a bit more elaborate implementation (my waking up excercise of today):
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TopScores {
private static final int TOP_SELECTION_SIZE = 2;
public static class Student {
private final String name;
private double score;
public Student(String name) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Name cannot be empty");
}
this.name = name;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public void setScore(String score) {
try {
this.score = Double.parseDouble(score);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal score: " + score);
}
}
#Override
public String toString() {
return String.format("%s with score %s", name, score);
}
}
public static void main(String[] args) {
List<Student> students = new ArrayList<TopScores.Student>();
System.out.println("Please enter students. Press <RETURN> to stop.");
Scanner input = new Scanner(System.in);
boolean enteringData = true;
while (enteringData) {
try {
System.out.print("Enter student's name: ");
Student student = new Student(input.nextLine());
System.out.print("Enter student's score: ");
student.setScore(input.nextLine());
for (int i = 0; i < students.size(); i++) {
if (student.getScore() > students.get(i).getScore()) {
students.add(i, student);
break;
}
}
if (students.size() == 0) {
students.add(student);
}
} catch (IllegalArgumentException e) {
enteringData = false;
}
}
int studentsToDisplay = Math.min(TOP_SELECTION_SIZE, students.size());
if (studentsToDisplay > 0) {
System.out.println("Top students:");
for (int i = 0; i < studentsToDisplay; i++) {
System.out.println("* " + students.get(i));
}
} else {
System.out.println("No students to display");
}
}
}
I created a separate class Student which holds name and score, validates the input and creates the display format for one student.
To determine the top scores I keep all the entered students sorted in a list by adding each new student in the correct position.
The user doesn't have to enter the number of students beforehand but can terminate data entry by entering an empty line (or an invalid score).
After data entry is finished the desired number of top scoring students is printed.
This approach is more flexible; printing the top 3 or top 10 students is a matter of changing the value of TOP_SELECTION_SIZE.
Most important takeaway: try to think in classes (in this case Student) where possible and delegate sensible responsibilities to each class.
Since this looks like homework, I will just give you a few hints:
When you find a new max, what should happen to score2?
Should you look for a new score2 even if you found a new max?
If we want to address the if structures, consider rearranging to something like this:
if (/* new score beats second score, but not first */) {
// replace second score
} else if (/* new score beats both first and second */) {
// move first score down to second
// assign a new first score
}
Let your thought process to correspond closely to the code, which will clarify what each block should do, thus localizing any logic errors.
I think when score is greater than max then have to shift max into second score and set max with new score....
And
When the score is between max and score2 then have to update score2 only with new score
//find max
if(score > max)
{
score2 = max;
max = score;
secondName = firstName;
firstName = name;
}
//find second max
if(score < max && score > score2)
{
score2 = score;
secondName = name;
}

Categories