do-while loop not terminate when answer no - java

package homework4;
import java.util.Scanner;
public class Prog4 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
CreditCardNumber[] cred1;
CreditCardNumber cred2 = getInput();
Display("The complete number from your input:", cred2);
cred1 = getInputArray();
DisplayArray(cred1);
TryAnother(cred1);
}
public static CreditCardNumber getInput() {
String ID;
String accNum;
CreditCardNumber tempCred;
System.out.printf("Please enter issuer ID:");
ID = scanner.next();
System.out.printf("Please enter account number:");
accNum = scanner.next();
tempCred = new CreditCardNumber(ID, accNum);
return tempCred;
}
public static void Display(String ch, CreditCardNumber cred2) {
System.out.println(ch);
System.out.println(cred2.toString().replaceAll(".{4}", "$0 "));
}
public static CreditCardNumber[] getInputArray() {
CreditCardNumber[] tempArray;
String tempID;
int size;
System.out.printf("Please enter size of the aray:");
size = scanner.nextInt();
if(size < 1) {
size = 1;
}
tempArray = new CreditCardNumber[size];
System.out.printf("Please enter issuer ID:");
tempID = scanner.next();
for(int i = 0; i < tempArray.length; i++) {
tempArray[i] = new CreditCardNumber();
tempArray[i].CreateCred(tempID);
}
return tempArray;
}
public static void DisplayArray(CreditCardNumber[] cred1) {
for(int i = 0; i< cred1.length; i++) {
Display("Credit Card # " + i+":" + '\n', cred1[i]);
}
System.out.println();
}
public static boolean TryAnother(CreditCardNumber[] cred1) {
String s;
System.out.printf("Get more credit card numbers? (n for no):");
s = scanner.next();
if(s.charAt(0) != 'N' || s.charAt(0) != 'n') {
do {
TryAnother(cred1);
cred1 = getInputArray();
DisplayArray(cred1);
} while(s.charAt(0) != 'N' || s.charAt(0) != 'n');
}
return false;
}
}
Hi, I have a problem in my do-while loop in TryAnother method, I'm trying to get the code to repeat for some reason when I enter no the process does not terminate when the condition of the do while loop said it should terminate also it repeat the line that tell user to enter 'yes' or 'no'.
something like:
Please enter issuer ID:321321
Please enter account number:654654654
The complete number from your input:
3213 2165 4654 6549
Please enter size of the aray:7
Please enter issuer ID:789789
Credit Card # 0:
7897 8985 6852 9257
Credit Card # 1:
7897 8917 0678 9958
Credit Card # 2:
7897 8900 5781 0934
Credit Card # 3:
7897 8949 2244 6098
Credit Card # 4:
7897 8941 3828 4895
Credit Card # 5:
7897 8965 9233 5006
Credit Card # 6:
7897 8981 8442 5880
Get more credit card numbers? (n for no):n
Get more credit card numbers? (n for no):n
Get more credit card numbers? (n for no):no
Get more credit card numbers? (n for no):
As you can see when I enter no. it keeps repeating the same sentence. What I want is for it to repeat from enter the array size sentence, How can I do this?

Change this:
}while(s.charAt(0) != 'N' || s.charAt(0) != 'n');
to:
}while(s.charAt(0) != 'N' && s.charAt(0) != 'n');

Related

How to show only the grades

I made the invalid grades into " " but it seems in output it's showing space like this https://i.stack.imgur.com/3kHZW.png how to show only the valid grades? the invalid grades is making blank space in output
This is the question https://i.stack.imgur.com/uxLhG.png
This is the needed output https://i.stack.imgur.com/HNZpZ.png
This is my Program
String [][] student = new String[100][3];
int stu = 0, totalp=0, totalf=0;
for(int h=0; h<100; h++) {
System.out.print("Enter Name: ");
student[h][0] = sc.nextLine();
System.out.print("Enter Grade: ");
student[h][1] = sc.nextLine();
int grade = Integer.parseInt(student[h][1]);
if(grade >100 || grade <50) {
student[h][0] = "";
student[h][1] = "";
student[h][2] = "";
System.out.println("Invalid Grade");
}
else if(grade >=75) {
student[h][2] = ("Passed");
totalp++;
}
else if(grade <=74) {
student[h][2] = ("Failed");
totalf++;
}
System.out.print("Add new record (Y/N)?: ");
char choice = sc.nextLine().charAt(0);
System.out.println("");
if(choice == 'y' || choice =='Y') {
stu++;
continue;
}
else if(choice == 'n' ||choice =='N') {
break;
}
}
System.out.println("\nGRADE SUMMARY REPORT");
System.out.println("\nName\tGrades\tRemarks");
for(int i =0; i<stu+1; i++) {
for(int h =0; h<student[i].length; h++) {
System.out.print(student[i][h] + "\t");
}
System.out.println();
}
System.out.println("\nTotal Passed: " + totalp);
System.out.println("Total Failed: "+ totalf);
If a grade entered by the user is invalid, just don't add it to student array. Then it won't get printed at all. You should also handle the case where the user does not enter a number when asked to enter a grade.
When asking the user if she wants to add a new record, you only need to check whether she entered a Y. Anything else can be considered a no.
The below code uses method printf to format the report. Also, in order to format the report, I keep track of the longest name entered by the user.
import java.util.Scanner;
public class Students {
private static final int MAX_ROWS = 100;
private static final int NAME = 0;
private static final int GRADE = 1;
private static final int REMARK = 2;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String[][] student = new String[MAX_ROWS][3];
int totalp = 0, totalf = 0, longest = 0;
int h = 0;
while (h < MAX_ROWS) {
System.out.print("Enter Name: ");
String name = sc.nextLine();
int len = name.length();
if (len > longest) {
longest = len;
}
System.out.print("Enter Grade: ");
String grade = sc.nextLine();
try {
int mark = Integer.parseInt(grade);
if (mark >= 50 && mark <= 100) {
student[h][NAME] = name;
student[h][GRADE] = grade;
if (mark >= 75) {
student[h][REMARK] = "Passed";
totalp++;
}
else {
student[h][REMARK] = "Failed";
totalf++;
}
h++;
if (h == MAX_ROWS) {
System.out.println("Maximum students entered.");
}
else {
System.out.print("Add new record (Y/N)?: ");
String choice = sc.nextLine();
if (!"Y".equalsIgnoreCase(choice)) {
break;
}
}
}
else {
throw new NumberFormatException();
}
}
catch (NumberFormatException xNumberFormat) {
System.out.println("Invalid. Grade is a number between 50 and 100.");
}
System.out.println();
}
System.out.println("\nGRADE SUMMARY REPORT\n");
if (longest < 4) {
longest = 4;;
}
System.out.printf("%-" + longest + "s", "Name");
System.out.println(" Grade Remarks");
String format = "%-" + longest + "s %4s %s%n";
for (int i = 0; i < h; i++) {
System.out.printf(format, student[i][NAME], student[i][GRADE], student[i][REMARK]);
}
System.out.println();
System.out.println("Total passed: " + totalp);
System.out.println("Total failed: " + totalf);
}
}
Here is output from a sample run of the above code:
Enter Name: Superman
Enter Grade: 99
Add new record (Y/N)?: y
Enter Name: Batman
Enter Grade: 23
Invalid. Grade is a number between 50 and 100.
Enter Name: Iron Man
Enter Grade: 74
Add new record (Y/N)?: n
GRADE SUMMARY REPORT
Name Grade Remarks
Superman 99 Passed
Iron Man 74 Failed
Total passed: 1
Total failed: 1
You may also want to refer to the Exceptions lesson in Oracle's Java tutorials.
right now you are still printing the invalid grades in a line. what you want is to check and make sure the grade is valid before printing it. Since you made all the invalid grade an empty string, you can simply check for that like so
if(!student[i][h].isEmpty()){
System.out.print(student[i][h] + "\t");
}

Why is my do-while loop not working?

When I compile, that try to enter (y) to play again my do - while is not working, it takes me out of the loop.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
int guessNumber = 0;
do
{
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Change the code as below: (You just need to update the variables inside the loop)
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = 0;
int guessNumber = 0;
do
{
// new lines to be added
theNumber = (int)(Math.random() * 100 + 1);
guessNumber = 0;
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
Here is the execution of code on Jshell:
The reason the program is not working is because the do-while loop does one iteration before it gets to the "while" part. In your case, the program successfully finishes the loop after a user correctly guesses the number. Your program breaks because after that you are requiring the user to enter 'y' to continue endlessly without letting them guess a number. If they guess a number, the program terminates.

java - withdraw from bank account using a method

Building a basic bank account with Java using methods. I am creating a new method to withdraw from the bank account. This is the code that I came up with right now, but on netbeans it shows that there are errors.
I created a new method called withDrawal. This code below is for the withdrawing from account and to not let the balance in the account go below zero!
private static void withDrawal()
{
int accountIndex = findAccount();
int verifyPin = checkPin (!=0);
if(accountIndex != -1)
if(verifyPin !=-2)
{
accounts[accountIndex].withDrawal();
accounts[verifyPin].checkPin();
int withDra = input.nextInt();
}
else
{
System.out.println("Account does not exist!");
System.out.printf("Enter amount you want to withdraw: ");
}
}
Java file
package grossmontbank;
import java.util.Scanner;
public class GrossmontBank
{
//class variables (global - accessible throughout this class)
//scanner object to be used throughout
private static Scanner input = new Scanner(System.in);
//array of blank accounts
private static final int MAX_ACCOUNTS = 50;
private static Account[] accounts = new Account[MAX_ACCOUNTS];
//total accounts created
private static int totalAccounts = 0;
//main class mimics a bank teller
public static void main(String[] args)
{
char choice;
//loop until 'Q' is entered
do
{
choice = getChoice(); //getChoice() will only return with a C, B, W, D or Q
if(choice != 'Q')
{
switch(choice)
{
case 'C': createAccount();
break;
case 'B': checkBalance();
break;
case 'W':
break;
case 'D':
break;
}
}
}while(choice != 'Q');
closeBank(); //outputs all account holders and 'closes' the bank
}
/*method checkBalance calls method findAccount()
* if account exists, calls Account method checkBalance()
*/
private static void checkBalance()
{
int accountIndex = findAccount();
//findAccount() returns index of account if found, -1 if not found
if(accountIndex != -1)
{
accounts[accountIndex].checkBalance();
}
else
{
System.out.println("Account does not exist");
}
}
/*method checkIfExists determines if account holder already exists
* returns true if account holder exists, false otherwise
*/
private static boolean checkIfExists(String firstName, String lastName)
{
//loops through account array to see if account name already exists
for(int i = 0; i < totalAccounts;i++)
{
//compares the names, ignoring upper/lower
if(accounts[i].getFirstName().equalsIgnoreCase(firstName)
&& accounts[i].getLastName().equalsIgnoreCase(lastName))
{
System.out.println("Account holder already exists. Please verify and re-enter. ");
return true;
}
}
return false;
}
/*method closeBank prints out closing statement
* prints out list of all account holders
*/
private static void closeBank()
{
System.out.println("Closing the follow accounts:");
for(int i = 0; i < totalAccounts;i++)
{
//printing an account object invokes the Account class method toString()
//prints first and last name only
System.out.printf(" %s%n",accounts[i]);
}
System.out.println("Grossmont Bank is officially closed.");
}
/*method createAccount creates a single bank account
* checks to ensure account holder does not already exist
* returns Account object
*/
private static void createAccount()
{
String first, last, initial;
boolean exists = false;
//only create a new account if MAX_ACCOUNTS has not been reached
if(totalAccounts < MAX_ACCOUNTS )
{
//loop until a new account name has been entered
do
{
System.out.print("Enter your first name: ");
first = input.next();
System.out.print("Enter your last name: ");
last = input.next();
exists = checkIfExists(first,last);
}while(exists == true);
System.out.print("Will you be making an initial deposit? Enter Yes or No: ");
initial = input.next();
//if no initial deposit, call 2 parameter constructor, otherwise call 3 param one
if(initial.equals("No"))
{
accounts[totalAccounts] = new Account(first,last);
}
else
{
System.out.print("Enter initial deposit amount: ");
accounts[totalAccounts] = new Account(first,last, input.nextDouble());
}
//increment totalAccounts created (used throughout program)
totalAccounts++;
}
else
{
System.out.println("Maximum number of accounts has been reached. ");
}
}
/*method findAccount asks for first and last name
* searchs for account holder in array
* if exists, returns array index of this account
* if doesn't exist, returns '-1'
* called from checkBalance()
*/
private static int findAccount()
{
String first, last;
System.out.print("Enter first name: ");
first = input.next();
System.out.print("Enter last name: ");
last = input.next();
//loops through account array
for(int i = 0; i < totalAccounts;i++)
{
//compares the names, ignoring upper/lower
if(accounts[i].getFirstName().equalsIgnoreCase(first)
&& accounts[i].getLastName().equalsIgnoreCase(last))
{
return i; //returns the index of the account
}
}
return -1; //if account not found
}
/* method getChoice() outputs options
* inputs choice from user and validates
* returns choice char
*/
private static char getChoice()
{
char choice;
//output menu options
System.out.println();
System.out.println("Welcome to Grossmont Bank. Choose from the following options: ");
System.out.println(" C - create new account");
System.out.println(" B - check your balance");
System.out.println(" D - deposit");
System.out.println(" W - withdrawal");
System.out.println(" Q - quit");
//loop until a valid input is entered
do
{
System.out.print("Enter choice: ");
choice = input.next().charAt(0);
//if choice is one of the options, return it. Otherwise keep looping
if(choice == 'C' || choice == 'B' || choice == 'D' || choice == 'W' || choice == 'Q')
return choice;
else
{
System.out.println("Invalid choice. Ensure a capital letter. Please re-enter.");
choice = '?';
}
}while(choice == '?');
return choice; //will never get here, but required to have a return statement to compile
}
private static void withDrawal()
{
int accountIndex = findAccount();
int verifyPin = checkPin (!=0);
if(accountIndex != -1)
if(verifyPin !=-2)
{
accounts[accountIndex].withDrawal();
accounts[verifyPin].checkPin();
int withDra = input.nextInt();
}
else
{
System.out.println("Account does not exist!");
System.out.printf("Enter amount you want to withdraw: ");
}
}
}

New Java developer - Simple Q

I have just recently started coding and am quite the beginner. I'm trying to make a program that simply asks the user to enter a "password", and depending on whether the password is correct; increment a counter. And, once the counter reaches 10, print out a message.
Basically what I'm trying to make is like a "clip-card", like one of those you can get at a coffee shop (you get every 10th coffee free).
So, this is what I have now. I just need to know how to make the program continue after inputting a password, and keep track of the inputs.
Ohhh and... If this is unclear, please say so and I will try to clarify.
This is what I have to far...
import java.util.Scanner;
public class Coffee {
public static void main(String [] args){
int count = 0;
String pass = "hey";
System.out.println("Enter password: ");
Scanner key = new Scanner(System.in);
String moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
}
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
}
if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
When would your program end? The way you describe it, it could just go on forever.
If that is the case, you just enclose it in a while loop :
public static void main(String [] args) {
Scanner key;
String moves;
int count = 0;
String pass = "hey";
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
}
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
}
if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
But you really should have an breaking condition.
You need loop(while,do-while,or for loop) to do this kind of repeated stuff .
Sample code may help
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
int count = 0;
String pass = "hey";
System.out.println("Enter password: ");
Scanner key = new Scanner(System.in);
String moves = key.nextLine();
boolean flag = true;
while (flag) {
if (moves.compareTo(pass) == 0) {
count++;
System.out
.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
}
if (count == 10 && count != 0) {
System.out.println("You've got a free coffe!");
count=0;
}
if (moves.compareTo(pass) != 0) {
System.out.println("Wrong password! Try again.\n");
}
System.out.println("Do you want to continue ..(y/n)");
String choice = key.nextLine();
if (choice.equals("n")) {
flag = false;
} else {
flag = true;
}
}
}
}
I will give you a while and do-while loop to chose from
While loop
Scanner key;
String moves;
int count = 0;
String pass = "hey";
boolean condition=true;
while(condition) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
condition=false;
}
}
else if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
Do-While loop
Scanner key;
String moves;
int count = 0;
String pass = "hey";
boolean condition=true;
do{
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
condition=false;
}
}
else if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}while(condition);

Java switch statment, search of array

//TestEmployeesProgram driver with menu & object array.
import java.util.*;
public class TestEmployeesProgram {
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
final int MAX = 7;
Employee employee[] = new Employee[MAX];
int choice,k;
String name;
boolean notFound;
employee[0] = new Manager("Jerry Bloggs","gfr",5,38.5);
employee[1] = new Manager("Joe Bloggs","gdr",4,32.5);
employee[2] = new Admin("Mary Jennings","nnv",35.3,88.5,34.3);
employee[3] = new Clerk("Brian Jones","bbl",42.4,78.5,23.5,45.3);
employee[4] = new Manager("John Bloggs","gvr",5,33.5);
employee[5] = new Admin("Bridget Jennings","nvv",45.3,98.5,36.3);
employee[6] = new Clerk("Jack Jones","bbb",43.4,78.5,23.5,47.3);
//Initial Read
choice = showMenu();
//Continue Until 4/Exit
while (choice != MAX) {
switch (choice) {
case 1://Manager
System.out.println();
System.out.printf("%s %-16s %-10s %6s","Name","Id","Hours Worked","Pay");
System.out.println("\n==================================================");
for (k = 0; k < MAX; ++k)
{
if (employee[k] instanceof Manager){ //use of string method instance of.
System.out.println(employee[k].toString());
}
}
break;
case 2://Administration
System.out.println();
System.out.printf("%s %-16s %-10s %6s %-19s","Name","Id","Hours Worked","Pay","Admin Quota");
System.out.println("\n==================================================");
for (k = 0; k < MAX; ++k)
{
if (employee[k] instanceof Admin){
System.out.println(employee[k].toString());
}
}
break;
case 3://Clerk
System.out.println();
System.out.printf("%s %-16s %-10s %6s %-19s","Name","Id","Hours Worked","Pay","Admin Quota","Units Sold");
System.out.println("\n==================================================");
for (k = 0; k < MAX; ++k)
{
if (employee[k] instanceof Clerk){
System.out.println(employee[k].toString());
}
}
break;
I was running the program and the name search in case 4 goes directly to default "employee name not found" and doesnt allow user input.I looked through the code but cant find the error,any tips or help?
case 4://Name search
System.out.print("Enter employee name: ");
name = console.nextLine();
k = -1;
notFound = true;
while ((k < MAX-1) && (notFound))
{
++k;
if (name == employee[k].getName()){
System.out.println();
System.out.printf("%s %-16s %-10s %6s %-19s","Name","Id","Hours Worked","Pay","Admin Quota","Units Sold");
System.out.println("\n==================================================");
System.out.println(employee[k].toString());
System.out.println();
notFound = false;
}
}//end of case 4 while.
if (notFound){
System.out.println("Employee name not found\n");
}
break;
case 7://exit
System.out.println("Program exiting...");
System.exit(0);
default:
System.out.println("Invalid menu choice 1..3 of 7 to Exit");
}//end of switch
//sub read
choice = showMenu();
}//end of while
}//end of main
//Menu method for employee selection.
public static int showMenu()
{
int choice;
System.out.println();
System.out.println("Employee Program Menu");
System.out.println("1.Show Manager pay details ");
System.out.println("2.Show Admin pay details ");
System.out.println("3.Show Clerk pay details ");
System.out.println("4.Search by employee name ");
System.out.println("7.Exit");
System.out.print("Enter option: ");
choice = console.nextInt();
return choice;
}
}
There are two errors. The first is here:
System.out.print("Enter option: ");
choice = console.nextInt();
The nextInt method doesn't consume the end-of-line character. Try this instead:
System.out.print("Enter option: ");
String line = console.nextLine();
choice = Integer.parseInt(line);
The second error is that here you should use equals instead of == to compare strings:
if (name == employee[k].getName())
Try this instead:
if (name.equals(employee[k].getName()))
The == operator tests to see if the two strings are the same object (i.e. the strings are at the same location in memory).
if (name == employee[k].getName())
change this to
if (name.equals(employee[k].getName()))
This is a common issue. When you use nextInt() to read an integer value only the integer character is read and the \n is left in the buffer and when you call nextLine() after that, it doesn't prompt for user entry because it already got a '\n'
To avoid this, in the showMenu method do
console.nextLine();
after you get the choice using nextInt().
This last part of showMenu would be:
choice=console.nextInt();
console.nextLine();
return choice;
and you should use .equals() method to compare strings as below.
if (name.equals(employee[k].getName()))
Good luck :)

Categories

Resources