I'm almost done with this project for my intro to java programming class. It's a credit card validation program. I know I'm super close to being done. All I need to do is to ask the user if he would like to enter another card number after the first one.
Normally the program says please enter your card number
user inputs card number
program determines if visa, mastercard etc... then determines if valid.
Simple enough.but I need to alter it to say
"please enter a card number"
user inputs card number
"would you like to input another card number?"
user inputs yes or no
If it's yes then the method reruns and gets another number then proceeds to do so until the user says no.
After the user says no, the program determines if the cards are visa, mastercards, etc... and if they are valid.
My code is posted below. I am pretty sure I need a while loop but I'm not quite sure how to set it up. The code below is just the getcardnumber method.
TLDR;
How do i get this to repeat until the user stops inputting card numbers?
public static String getCardNumber() {
String cardNumber;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the credit card number: ");
cardNumber = keyboard.nextLine();
//remove spaces from cardNumber
cardNumber = cardNumber.replace(" ", "");
while (!isAllDigits(cardNumber)) {
System.out.println("The credit card number must contain only the"
+ " digits 0-9; please re-enter: ");
cardNumber = keyboard.nextLine();
//remove spaces from cardNumber
cardNumber = cardNumber.replace(" ", "");
}
//a number containing only digits has been entered
return cardNumber;
}
You can do something like this:
public static void main(String[] args){
boolean b = false;
do {
System.out.println("Number 2: ");
Item2 item2 = new Item2();
System.out.println("Please enter the credit card number: ");
Scanner keyboard = new Scanner(System.in);
System.out.println(checkNumber(keyboard.nextLine(), keyboard));
System.out.println("Would you like to input another card number? 1=Yes; 2=No");
int decision = Input.nextInt();
if (decision == 1){
b = false;
}else if (decision == 2){
b = true;
}
}while(b == false);
}
public static String checkNumber(String cardNumber, Scanner keyboard) {
//remove spaces from cardNumber
cardNumber = cardNumber.replace(" ", "");
while (!isAllDigits(cardNumber)) {
System.out.println("The credit card number must contain only the"
+ " digits 0-9; please re-enter: ");
cardNumber = keyboard.nextLine();
//remove spaces from cardNumber
cardNumber = cardNumber.replace(" ", "");
}
//a number containing only digits has been entered
return cardNumber;
}
Related
I am new to JAVA and have been using IDE, to cut it short whenever I try to check if bag contains a string thats the same as the given input JAVA counts it as FALSE, even if the if statements such as "is input equal to 1" and "is 1 inside the bag" pass as true. here is an excerpt from my code, I would appreciate any help and advice.
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a=sc.next();
if (a.equals("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
if (ValidAnswers1.contains("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
while (correct_input==0)
{
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
}
the console prints out both the keymashes and then diverts into the while loop. I have checked to make sure the while loop is correct by testing with fixed variables, but when scanner is used it seems to have an error.
I didn't understand, what you really want, i did the test and a yet is working fine. take a look at the class, maybe is some error in the variables or something
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String a;
String ValidAnswers1 = "1";
int correct_input = 0;
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a = sc.next();
if (a.equals("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
if (ValidAnswers1.contains("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
while (correct_input==0) {
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
}
}
Here is the output:
Please enter a string (to exit, enter 'exit'):
a
adpkgnos?fbgojadnofabsndofgna
you entered:a.
Please enter a valid string (to exit, enter 'exit')
1
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
//Create a new Object Scan in the memmory
Scanner scan = new Scanner(System.in);
String input;
String[] validAnswers = new String[]{"1","2","3","exit"};
boolean isCorrect = false;
//The method equalsIgnoreCase means that the text can be in uppercase too;
/*The number between the tags "[]" means the number in the array since arrays
starts with number "0" */
do{
System.out.println("Please enter a string (to exit, enter 'exit'): ");
input = scan.next();
if(input.equalsIgnoreCase(validAnswers[0])){
isCorrect = true;
System.out.println("Number 1");
}else if(input.equalsIgnoreCase(validAnswers[1])){
isCorrect = true;
System.out.println("Number 2");
}else if(input.equalsIgnoreCase(validAnswers[2])){
isCorrect = true;
System.out.println("Number 3");
}else if(input.equalsIgnoreCase(validAnswers[3])){
isCorrect = true;
System.out.println("EXIT!");
//You could use the method System.exit(0) to finish the program;
//If you put "1" in the exit value means that the prgram finished with some error;
//System.exit(0);
}else{
//If the Answers is different from all of the others;
System.out.println("you entered: " + input +".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
}
}while(isCorrect != true);
//I used the method do{}while because it's the only method that will exacute at least once;
}
public static void main(String args[])throws IOException{
validNumbers = new int[200];
Scanner sc1 = new Scanner(new File("validNumbers.txt"));
int i = 0;
while(sc1.hasNextInt()) {
validNumbers[i++] = sc1.nextInt();
}
// Creating loop for what the user enters
boolean newValidator = true;
Scanner scanner = new Scanner(System.in);
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
// If found, the calculations will get displayed
if(validator(num)) {
System.out.print("The calculated value to this account is: " + calculator(num));
newValidator = false;
System.out.println("\n" + "Would you like to enter another account number? (y/n)");
String ans = "";
ans = scanner.nextLine();
// Needed the false, if not the code would keep asking to "Enter account number: "
if (ans.equals("y")) {
System.out.print("Enter the account number: ");
String num2 = scanner.nextLine();
System.out.print("The calculated value to this account is: " + calculator(num2));
} else if(ans.equals("n")) {
newValidator = false;
System.out.println("** Program Exit **");
}
}
// Wanted to add a loop for the user to decide if they want to continue iff wrong account is inputed
else {
System.out.println("Not valid account number" + "\n\n" + "Would you like to try again? (y/n)");
String ans = "";
ans = scanner.nextLine();
if(ans.equals("y")) {
newValidator = true;
}
// How the program terminates if the user does not wish to continue
else if(ans.equals("n")) {
newValidator = false;
System.out.println("Not valid input, the program is now terminated!");
}
}
}
}
}
(Using Java) The code is doing the following:
1.) When the user enters a correct number it sees the number(in the file) and adds the digits
2.) When it is not in the file, it knows the number is not there and tells the user to try again and if the user doesn't want to, it ends the program.
***** (Using Java) What the code is not doing:
1.) After they entered the right code, the program is to ask the user if they want to enter another account(with the adding of an account if so). Then this is where I have the problem, the loop is ending after this second go and I need it to keep asking if they want to enter another account number unit the user wants to exit.*****
There's no need to have a nested question asking for another account number, the while loop itself will ask the user again when it repeats.
Simply ask the user if they want to enter another and then exit the loop if the don't. The while loop drops out when "newValidator" is set to false:
boolean newValidator = true;
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
if(validator(num)) {
System.out.println("The calculated value to this account is: " + calculator(num));
}
else {
System.out.println("Not valid account number!");
}
System.out.println("\n\nWould you like to enter another account number? (y/n)");
String ans = scanner.nextLine();
if (ans.equals("n") || ans.equals("N")) {
newValidator = false;
}
}
System.out.println("** Program Exit **");
Firstly I'm a new person here. I need to ask one question.
Scanner klavye = new Scanner(System.in);
System.out.println("DDD-DD-DDDD enter bank number digit: ");
String hesapNo = klavye.nextLine();
if(hesapNo.length() != 11) {
System.out.println("You need to enter number with 11 digit");
}
else {
if(hesapNo.charAt(3) == '-' && hesapNo.charAt(6) == '-') {
System.out.println(hesapNo + " is valid");
}
else {
System.out.println(hesapNo + " is not valid");
}
}
I want to take only digit number but If I write below like this:
ABC-DC-SMND
"The count is valid"
how can I solve this problem?
Thanks for all of your interest.
You can do it with regular expressions and a loop to prompt the user until a valid input.
Scanner klavye = new Scanner(System.in);
System.out.println("DDD-DD-DDDD enter bank number digit: ");
String hesapNo;
final String regexPattern = "\\d{3}-\\d{2}-\\d{4}";
do {
hesapNo = klavye.nextLine();
System.out.println("You need to enter a number with 11 digit with pattern: DDD-DD-DDDD");
}
while(!hesapNo.matches(regexPattern));
System.out.println(hesapNo + " is valid");
That can be done with a simple regex using String.matches:
Scanner klavye = new Scanner(System.in);
System.out.println("DDD-DD-DDDD enter bank number digit: ");
String hesapNo = klavye.nextLine();
if(hesapNo.matches("\\d{3}-\\d{2}-\\d{4}")){ // <-- this regex matches your pattern DDD-DD-DDDD
System.out.println(hesapNo + " is valid");
}else{
System.out.println("You need to enter number with 11 digit");
}
EDIT
If you want to keep asking for input until a valid one is entered then you can do this:
Scanner klavye = new Scanner(System.in);
String hesapNo;
boolean validInput;
System.out.println("DDD-DD-DDDD enter bank number digit: ");
do {
hesapNo = klavye.nextLine();
validInput = hesapNo.matches("\\d{3}-\\d{2}-\\d{4}");
if (!validInput) { // if invalid input then warn the user
System.out.println("Your bank number must be in DDD-DD-DDDD format");
}
} while (!validInput); // loop until a valid input is provided
System.out.println(hesapNo + " is valid");
The following code below asks the user to enter a number. Then it prompts the user to enter more numbers. When they exit the program they display the highest number entered. How could I convert this code to ask for the gender of a person then age. So the output of the program would state the highest girl age is ____ and the highest boy age is _______? Right now its gender neutral and just complies the highest age.
import javax.swing.JOptionPane;
public class largestNumb{
public static void main(String[] args) {
int highestNumber;
boolean firstNumberEntered = false;
int firstNumber;
do {
String firstNumberInput = JOptionPane.showInputDialog("Enter the first number: ");
try {
firstNumber = Integer.parseInt(firstNumberInput);
firstNumberEntered = true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid number! Please try again.");
firstNumber = 0;
firstNumberInput = JOptionPane.showInputDialog("Enter the first number: ");
}
} while (!firstNumberEntered);
highestNumber = firstNumber;
String numberInput = JOptionPane.showInputDialog("Enter another number, or Q to quit");
while (!numberInput.equalsIgnoreCase("Q")) {
int number;
try {
number = Integer.parseInt(numberInput);
if (number > highestNumber) {
highestNumber = number;
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid number!");
}
numberInput = JOptionPane.showInputDialog("Enter another number, or Q to quit");
}
JOptionPane.showMessageDialog(null, "The highest number was: " + highestNumber);
}
}
You can ask for the gender in another showInputDialog method.
Change the showInputDialog from an int to a collection of values, it can be an array with a length of 2 to store the highest age for the gender, it can be a map where the key is the gender, the limit is the sky
You will need to work in your validations:
If you are asking ages, shouldn't that be stated when you are asking the data?
What will happen if the user inputs a negative number?
Would you accept an age of 1345 years?
What if it the text is empty, a character different to 'q'?
I would suggest either placing another showInputDialog message within each loop or creating an if statement to specify the gender.
You need to maintain two different variables which will keep track of the highest age for each girl and boy respectively. You do not need to add any additional in this case. Add code to ask the user to enter gender (validate the data) and ask for age. Based on gender do the separate calculation.
while(...)
{
//Ask for gender and validate
//Ask for age and validate
switch(gender)
{
case 'M':
//maleHigestAge calculation here
break;
case 'F':
//femaleHigestAge calculation here
break;
}
}
//display maleHigestAge and femaleHigestAge with formated string
package cst150zzhw4_worst;
import java.util.Scanner;
public class CST150zzHW4_worst {
public static void main(String[] args) {
//Initialize Variables
double length; // length of room
double width; // Width of room
double price_per_sqyd; // Total carpet needed price
double price_for_padding; // Price for padding
double price_for_installation; // Price for installation
String input; // User's input to stop or reset program
double final_price; // The actual final price
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
//User Input
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
final_price = (price_for_padding + price_for_installation + price_per_sqyd)*((width*length)/9);
keyboard.nextLine(); //Skip the newline
System.out.println("The possible total price to install the carpet will be $" + final_price + "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
}
}
}
How would I make it so when the user says yes the program stop and if the user says no then the program just repeats? I don't know why I'm having so much trouble. I've searched for well over 4 hours. I am only supposed to use a while loop, I think.
You have to assign repeat in your while-loop so it becomes false if the user says yes:
repeat = !input.equalsIgnoreCase("yes");
You just need to set repeat to true or false based on user input. So in the end, compare input with yes or no. Something like this would work for you :
if ("yes".equals(input))
repeat = true; // This would continue the loop
else
repeat = false; // This would break the infinite while loop
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
-----------------------
-------------------------
System.out.println("Do you want to continue:");
repeat = keyboard.nextBoolean();
}
you also if you want your code to be more systematic , go and search about the interrupt , specially thread interrupt , these answers above is correct , find the more organic code and implement it
You can use a break statement to exit a while loop.
while (...) {
input = ...;
if (input.equals("Y")) {
break;
}
}