Ending while loop with string not working - java

I have a problem with trying to end this while loop. When it runs, typing "exit" for the name part doesn't seem to register and the code continues as if "exit" was a name typed in. What I intended to happen is for "exit" to be typed in so that the loop can end. Any help? Here is the code for the class:
import java.util.*;
import java.io.*;
public class BankTest {
public static void main(String args[]) {
List<BankAccount> bank = new ArrayList<BankAccount>();
Scanner scan = new Scanner(System.in);
//enter into list the accounts and end with exit typed in
String name = "";
while (name.contains("exit")==false) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
//find highest account amount
double largestMon = bank.get(0).getBalance();
String largestPer = bank.get(0).getName();
for (int i=0;i<bank.size();i++) {
double compare = bank.get(i).getBalance();
if (compare>largestMon) {
largestMon = compare;
largestPer = bank.get(i).getName();
}
}
System.out.println(largestPer+" has the largest account with $");
}
}
I've already tried switching between != and equals() compare the strings.

Change while (name.contains("exit")==false) to while(true)
and add line if (name.equals('exit')) break; after name = scan.nextLine();

First of all you could change
name.contains("exit")==falseinto !name.contains("exit")
A better solution would be to use a while true loop and break if the name variable is equal to "exit"
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
Notice that in cases like this you shouldn't use .contains() or .equals but rather .equalsIgnoreCase()

This should work
while(true){
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}

Modify your while loop as follows:
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}

Related

i need help in storing multiple user input into an array with maximum limitation and being able to call it later in the code

Im still learning java and i want to understand more about array. Im still in school and we were asked to create an asean phonebook which can store, edit, delete, and view/search the information that are inputted. Im still doing the storing of information block of code and im struggling how to save multiple input in an array that is limited only to 100 contacts and can be searched later in the code. Can someone help me with my task and make me understand??
import java.util.Scanner;
public class Phonebook
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int i = 0;
String studentNumber, surName, firstName, occuPation, countryCode, areaCode, numBer;
char genDer;
do
{
Menu();
System.out.println(" ");
System.out.print("Go to: ");
String choice = input.next();
if (choice.equals("1") || choice.equals("2") || choice.equals("3") || choice.equals("4") || choice.equals("5"))
{
i++;
switch(choice)
{
case "1":System.out.println("Enter student number: ");
studentNumber = input.next();
System.out.println("Enter surname: ");
surName = input.next();
System.out.println("Enter first name: ");
firstName = input.next();
System.out.println("Enter occupation: ");
occuPation = input.next();
System.out.println("Enter gender (M for male, F for female): ");
genDer = input.next();
System.out.println("Enter counter code: ");
countryCode = input.next();
System.out.println("Enter area code: ");
areaCode = input.next();
System.out.println("Enter number: ");
numBer = input.next();
break;
case "2":System.out.println("2");break;
case "3":System.out.println("3");break;
case "4":System.out.println("4");break;
case "5":System.out.println("5");break;
}
}
else
{
System.out.println("Invalid keyword, Please try again");
}
}
while (i < 1);
}
static void Menu()
{
System.out.println("[1] Store to ASEAN phonebook");
System.out.println("[2] Edit entry in ASEAN phonebook");
System.out.println("[3] Delete entry from ASEAN phonebook");
System.out.println("[4] View\\search ASEAN phonebook");
System.out.println("[5] Exit");
}
}

Formatting, Big Decimal, interest to percent please

Can someone please explain the usage not just answer I really would like to learn how to do this. This is my 2nd month using Java and please explain formatting usage in Java. Thank you so much. I really appreciate it. Feel free to ask any other question in regards C++ or python. I am in need of help in formatting, big decimal usage and how to set
import java.util.*;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.math.*;
public class Main{
public static void main(String[] args)
{
Scanner myCalculation = new Scanner(System.in);
System.out.print("Welcome to the Interest Calculator \n\n");
String option = "y";
while (option.equalsIgnoreCase("y"))
{
System.out.print("Enter Loan Amount: ");
//double loanAmount = 520000;
double loanAmount = myCalculation.nextDouble();
//Get Interest rate from user
System.out.print("Enter Interest Rate: ");
// double interRate = .05375;
double interRate = myCalculation.nextDouble();
double interest = loanAmount * interRate;
System.out.printf("%.3f", interest);
System.out.println();
//prompt user to continue? if he enter y then it will Continue
//else it will stop
//System.out.println("Continue? (y:n): ");
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
//do whatever
System.out.println("Would you like to continue? (yes or no)");
String s = scan.nextLine();
if(s.equals("no")) {
stop = true;
}
}
}
}
}
Scanner in = new Scanner(System.in);
System.out.print("enter double");
double d = in.nextDouble(); //doubles
System.out.print("enter int");
int i = in.nextInt(); //ints
System.out.print("enter text");
String text = in.next(); //gets a string up to the first space
in.nextLine();
System.out.print("enter text w/ spaces");
String line = in.nextLine(); //gets a string up to the first space
System.out.println(d);
System.out.println(i);
System.out.println(text);
System.out.println(line);
in.close();
System.out.println(new DecimalFormat("#.###").format(4.567346344634));

Scanner doesnt read input in else statement

Im trying to ask the user for two numbers. I want to check if those inputs are in fact numbers but the code I have so far does not let me enter a second value if the first input is a string.
So the scanner does not read anything the else statement.
How could I make it work?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
You just need to add console.nextLine(); after your else statement, because the Scanner.hasNextInt method does not move cursor past your previous input (if it is a string).

While-loop equals to not working properly (java bank account)

So my task is to write a bank-account program that asks wether you want to deposit or withdraw money, it asks for how much and at last if I want to continue or not, and if not it will show my current account balance. Example:
Deposit or withdraw (0-deposit, 1-withdraw):
How much?
Do you want to continue?
Balance: XX.XX
The program should be looped and break when the answer is "Y" on "Do you want to quit?".
package Account;
import java.util.Scanner;
public class bankVisit {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
bankAccount account = new bankAccount();
String respond = "N";
System.out.print("Deposit or withdraw (0-deposit, 1-withdraw): ");
int choice = scan.nextInt();
while (respond.equals("N")) {
if (choice == 0) {
System.out.print("Amount: ");
double total = scan.nextDouble();
account.credit(total);
System.out.print("Do you want to quit? ");
respond = scan.next();
} else if (choice == 1) {
System.out.print("Amount: ");
double total = scan.nextDouble();
account.withdraw(total);
System.out.print("Do you want to quit? ");
respond = scan.next();
}
System.out.print("Deposit or withdraw (0-deposit, 1-withdraw): ");
choice = scan.nextInt();
}
System.out.println("Balance: " + account.getBalance());
scan.close();
}
}
I get it to loop, but I dont get how I should make the loop to quit, and post my balance, it keeps looping even though "respond" not equals "N".. Any ideas? Im very new to Java so anything will do.

Reading and writing to txt files

I'm writing a code that reads in file Banking.txt and asks for userID & pin, then prompting the user to make a withdrawal, deposit, or check balance. The balance will be written to Records.txt. The program terminates after the user enters the pin, & i can't figure out how to make it continue. Please help
public static void main(String[] args) throws FileNotFoundException {
File fil1 = new File("Banking.txt");
File fil2 = new File("Records.txt");
Scanner sc1 = new Scanner(fil1);
Scanner s1 = new Scanner(fil2);
String fname;
String mname;
String lname;
String uid = null;
int pin = 0;
double balance = 0;
java.io.PrintWriter output = new java.io.PrintWriter(fil2);
while (sc1.hasNext()) {
fname = sc1.next();
mname = sc1.next();
lname = sc1.next();
uid = sc1.next();
pin = sc1.nextInt();
balance = sc1.nextDouble();
BankRecord person = new BankRecord(fname,mname,lname,uid,pin,balance);
System.out.print(pin);
}
Scanner input = new Scanner(System.in);
System.out.print("Please enter a user ID: ");
String entereduid = input.nextLine();
if(entereduid.equals(uid)){
System.out.print("Please enter a Pin #: ");
String enteredpin = input.nextLine();
if(enteredpin.equals(pin)){
Scanner input2 = new Scanner(System.in);
System.out.print("press 1 to check balance, 2 for a deposit, or 3 for a withdrawal: ");
int ans = input.nextInt();
if(ans == 1){
System.out.print(balance);
output.println("The balance is now "+balance+"$.");
}
else if(ans == 2){
System.out.print("Your current balance is: " + balance+". Please enter an amount to deposit: ");
double dep = input.nextDouble();
balance = balance + dep;
System.out.print("You deposited "+dep+"$. Your new balance is: " + balance+"$.");
output.println("The balance is now "+balance+"$.");
}
else if(ans == 3){
System.out.print("Yor current balance is: "+balance+". Please enter an amount to withdrawl: ");
double wit = input.nextDouble();
balance = balance - wit;
System.out.print("You withdrew "+wit+"$. Your new balance is: "+balance+"$.");
output.println("The balance is now "+balance+"$.");
}}}}}
You're reading the pin from input as a String, but you read it from the file as an Integer; so Integer pin != String pin. Your pin is never recognized as correct so your program skips to the end.
Try new Scanner(System.in).nextInt() to read input as Integer.
So I'd change this line:
String enteredpin = input.nextLine();
to this:
Integer enteredpin = input.nextInt();
If I understand correctly, you want to write the "person" object (i.e. an instance of BankRecord) to a file? As I don't know what methods there are in that class, I'll assume there is a suitable toString() override. I'll also assume that you're trying to write to your home directory.
Path dir = Paths.get(URI.create("file:///"+System.getProperty("user.home")+System.getProperty("file.separator")+"BankRecords.txt"));
try (BufferedWriter bfr = Files.newBufferedWriter (dir, Charset.forName("UTF-8"))) {
String contents = person.toString();
bfr.write(contents, 0, contents.length());
}
catch (IOException ioe) {
System.err.println(ioe.getMessage());
}

Categories

Resources