I have a problem with some code. When I try to break my loop using "quit" it wont stop. If I begin with typing quit, it breaks as intended but the second time the loop runs and I type quit it's not breaking. What is the problem?
public static void interactionLoop() {
input = new Scanner(System.in);
String ssn = null;
String message = null;
int accountNr;
double amount;
while(true) {
for(Customers aCustomer : Customers.getCustomerList()) {
System.out.println(aCustomer.getName() + ", " + aCustomer.getSsn());
}
System.out.println("Choose a customer by using SSN.");
System.out.print(">> ");
ssn = input.nextLine();
if(ssn.equals("quit")) {
break;
}
Customers theChosenCustomer = Customers.getCustomerBasedOnSSN(ssn);
ArrayList<Accounts> accList = theChosenCustomer.getAccountList();
for(Accounts anAccount : accList) {
if(anAccount instanceof Savings) {
System.out.print("(Savings, " + anAccount.getAccountNr() + ")" + "\n");
}
if(anAccount instanceof Loans) {
System.out.print("(Loans, " + anAccount.getAccountNr() + ")" + "\n");
}
}
System.out.print("Enter the account that you want to work with using the account number:\n>> ");
accountNr = input.nextInt();
Accounts chosenAccount = theChosenCustomer.getSpecificAccount(accountNr);
System.out.println("Account balance: "+chosenAccount.getBalance());
for(Transaction t : chosenAccount.getTransaction()) {
System.out.println(t.getDateAndTime().getTime() +", " + t.getComment() +": " + t.getAmount());
}
System.out.println("\n");
System.out.print("Please enter the amount of money you wish you withdraw or deposit: ");
while(input.hasNext()) {
amount = input.nextDouble();
input.nextLine();
if(chosenAccount.isValid(amount)){
System.out.print("Please enter a comment: ");
message = input.nextLine();
Calendar transdatetime = Calendar.getInstance();
chosenAccount.makeTransaction(new Transaction(transdatetime,message,amount));
System.out.println("");
interactionLoop();
}
}
}
accountNr = input.nextInt();
From 2nd time onwards Scanner scans Integer from the Std InpuStream but then the newline remains which is taken by
ssn = input.nextLine();
due to which your program does not quit. Same goes for double. Better use
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
then use reader.readLine() and parse it into your desired data type. Eg. Integer.parseInt(reader.readLine())
Related
Here is my updated code. Again, the instructions are as follows: "Enter a first name, last name, student id, and avg, then have those 4 things displayed in a new csv file, with each of the 4 inputs separated by a comma in each record." This code works well, is there anything I can do better? Also, is "in.close()" necessary in this case since I am not reading a file, but rather user input?
public class Homework07 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
String newRecord = (firstName + ", " + lastName + ", " + studentId + ", " + currentAvg);
outFile.println(newRecord);
}
in.close();
outFile.close();
}
}
your code capture the enter key entered by user to I added an empty in.nextLine(); to escape it, and secondly I added outFile.flush(); to flush the stream to the file.
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
outFile.write(firstName + "," + lastName + "," + studentId + "," + currentAvg);
outFile.flush();
}
in.close();
outFile.close();
Your call to the Scanner#nextDouble() method does not consume the ENTER key hit (the newline character) therefore you need to do it yourself by placing this line: in.nextLine(); directly under this line:
double currentAvg = in.nextDouble();
Ironically, you need to apply a newline character when you write to your file for every record you want to save, like this:
String record = new StringBuilder(firstName).append(", ").append(lastName)
.append(", ").append(studentId).append(", ")
.append(currentAvg).append(System.lineSeparator())
.toString();
outFile.write(record);
Read all lines from console and store in A collection. in this context how to use scanner's methods. The number of lines user may enter is unknown.
try this:
Scanner reader = new Scanner(System.in);
List<String> a = new ArrayList<>();
while (reader.hasNextLine()) {
String s = reader.nextLine();
if (s.equals("!q")) {
break;
}
a.add(s);
}
you can try this:
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
and output will be like:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
So this code asks for a name and a number 1-20, but if you put in a number over 20 or below 1 the program still runs and I know I need a conditional statement right around figuring out the amount for "ano" to stop and re-ask the statement and re-run the segment but I don't know how to implement it into the code.
// library - for interactive input
import java.util.Scanner;
//---------------------------------
// program name header
public class feb24a
{
//--------FUNCTION CODING ---------------
// FUNCTION HEADER
public static void seeit(String msg, String aname, int ano)
{
// statement to accomplish the task of this function
System.out.print("\n The message is " + msg + "\t" + "Name is:" + aname + "\t" + "number is: " + ano);
// return statement without a variable name because it is a void
return;
}
//------------------- MAIN MODULE CODING TO CALL FUNCTIONS ----------------
// Main module header
public static void main (String[] args)
{
String msg, aname;
int ano, again, a, b;
msg = "Hello";
a = 1;
b = 20;
//Loop control variable
again = 2;
while(again == 2)
{
System.out.print("\n enter NAME: ");
Scanner username = new Scanner(System.in);
aname = username.nextLine();
System.out.print("\n enter number 1-20: ");
Scanner userno = new Scanner(System.in);
ano = userno.nextInt();
seeit(msg, aname, ano);
//ask user if they want to do it again, 2 for yes any other for no
System.out.print("\n do you want to do this again? 2 for yes ");
Scanner useragain = new Scanner(System.in);
again = useragain.nextInt();
} //terminate the while loop
}
}
Replace your while loop with this:
Scanner scanner = new Scanner(System.in);
while (again == 2) {
ano = 0;
System.out.print("\n enter NAME: ");
aname = scanner.nextLine();
while (ano < 1 || ano > 20) {
System.out.print("\n enter number 1-20: ");
ano = scanner.nextInt();
}
seeit(msg, aname, ano);
System.out.print("\n do you want to do this again? 2 for yes ");
again = scanner.nextInt();
}
Try to surround your ano = userno.nextInt() in a while loop. (i.e., while(ano < 1 || ano > 20)) and put a prompt inside that while loop. That way, it will keep reading a new number until it finally no longer fulfills the while loop and will break out.
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());
}
Sorry if my question seems a little vague.
Basically what I am trying to do is error check using string comparison on a constructor object, which is stored in an array. I think I have the right idea: (Count is a static int that iterates whenever an employee is added in another method)
public static void updateTitle(Employee searchArray[]) {
String searchID;
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee ID for manipulation: ");
searchID = input.nextLine();
for (int i = 0; i < count; i++) {
String arrayID = searchArray[i].getEmployeeNumber();
if (searchID.equals(arrayID) == true) {
System.out.println("Employee: " + searchID + " found!");
System.out.println("Employee " + searchID
+ "'s current title is: "
+ searchArray[i].getEmployeeTitle());
System.out.println(" ");
System.out
.println("Would you like to change this employees title? (Y/N)");
System.out.println(" ");
String answer = input.nextLine().toUpperCase();
if (answer.equals("Y")) {
System.out.println("Enter new title: ");
String newTitle = input.nextLine();
searchArray[i].setEmployeeTitle(newTitle);
searchArray[i].updateTitle(newTitle);
}
if (answer.equals("N")) {
break;
}
} else if (searchID.equals(arrayID) == false) {
System.out.println("Please enter a valid ID!");
}
}
}
This successfully error checks, however because it is iterating through the array, it will display an error message before a validation message if the array element is > 0 and is found in the array. Is there any way to analyse every element of the array and produce the error message if and only if the ID is not found in any elements?
you definitely should read a book how to program in Java.
All code below should be rewritten, but I leave it for understanding the error.
public static void updateTitle(Employee searchArray[]) {
String searchID;
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee ID for manipulation: ");
searchID = input.nextLine();
Employee found = null;
for (int i = 0; i < searchArray.length; i++) {
String arrayID = searchArray[i].getEmployeeNumber();
if (searchID.equals(arrayID)) {
found = searchArray[i];
break;
}
}
if (found != null) {
System.out.println("Employee: " + searchID + " found!");
System.out.println("Employee " + searchID + "'s current title is: " + found.getEmployeeTitle());
System.out.println(" ");
System.out.println("Would you like to change this employees title? (Y/N)");
System.out.println(" ");
String answer = input.nextLine();
if (answer.equalsIgnoreCase("Y")) {
System.out.println("Enter new title: ");
String newTitle = input.nextLine();
found.setEmployeeTitle(newTitle);
found.updateTitle(newTitle);
}
} else {
System.out.println("Please enter a valid ID!");
}
}