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");
Related
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 **");
Hello everyone i'm doing my homework and i want to understand, how to fulfill properly third section in code - 3.View operation history. (List of all operations performed by user, use array for storing this information in format: “[operation index]. [operation name] - [user input]”. Also i have an issue -
Application should work and accept user input until he wants to exit from program.
Scanner in = new Scanner(System.in);
System.out.println("Please select operation");
System.out.println("1.Encode");
System.out.println("2.Decode");
System.out.println("3.View operation history");
System.out.println("4.Exit program");
Integer userInput = Integer.valueOf(in.nextLine());
if (userInput.equals(1)) {
System.out.println("You chosen encoding operation");
System.out.println("Please choose codec name - caesar or morse");
String userInputEncode = in.nextLine().toLowerCase();
if (userInputEncode.equals("caesar")) {
System.out.println("Enter text to encode");
String userInputEncode2 = in.nextLine().toLowerCase();
System.out.println("Encoded text: " + caesarEncoder.encode(userInputEncode2));
} else if (userInputEncode.equals("morse")) {
System.out.println("Enter text to encode");
String userInputEncode3 = in.nextLine().toLowerCase();
System.out.println("Encoded text: " + morseEncoder.encode(userInputEncode3));
} else
System.out.println("You entered wrong codec name, try one more time");
} else if (userInput.equals(2)) {
System.out.println("You chosen decoding operation");
System.out.println("Please choose codec name - caesar or morse");
String userInputDecode = in.nextLine().toLowerCase();
if (userInputDecode.equals("caesar")) {
System.out.println("Enter text to decode");
String userInputDecode2 = in.nextLine().toLowerCase();
System.out.println("Decoded text: " + caesarDecoder.decode(userInputDecode2));
} else if (userInputDecode.equals("morse")) {
System.out.println("Enter text to Decode");
String userInputDecode3 = in.nextLine().toLowerCase();
System.out.println("Decoded text: " + morseDecoder.decode(userInputDecode3));
}
else
System.out.println("You entered wrong codec name, try one more time");
}
else if (userInput.equals(3)) {
}
else if (userInput.equals(4)) {
in.close();
System.out.println("Program was closed by user");
You probably need a loop that checks if the user has typed the number 4.
Then you can create a List before the loop where you will store all the history of what the user has typed during the execution of the program.
And then in the case of the number 3 is selected, you can use that list to take the historical data and then print all the data that you need
Below a simple and fast example (not the best way):
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
Scanner in = new Scanner(System.in);
List<String> operationHistory=new ArrayList<String>();
Integer userInput = null;
do{
System.out.println("Please select operation");
System.out.println("1. aaa");
System.out.println("2. bbb");
System.out.println("3. print selection history");
System.out.println("4. exit");
userInput = Integer.valueOf(in.nextLine());
if (userInput.equals(1)) {
System.out.println("Please type something");
String userInputEncode = in.nextLine().toLowerCase();
operationHistory.add("1. aaa - " + userInputEncode);
}else if (userInput.equals(2)) {.
System.out.println("Please type something");
String userInputEncode = in.nextLine().toLowerCase();
operationHistory.add("2. bbb - " + userInputEncode);
}else if (userInput.equals(3)) {
System.out.println("Operation History:");
for(String operationitem:operationHistory){
System.out.println(operationitem);
}
System.out.println("-------------");
}
}while(!userInput.equals(4));
in.close();
System.out.println("Program was closed by user");
This is just an example similar to your code, you can use it to understand how your problem can be solved and how the loops and the lists works
You then probably want to manage some unexpected input
first off, the secret word is printed out as dashes, then the user puts in what letter they want to guess. if they guess the letter correctly then it will update the dashes. so if the word is java, it will show as ---- and if the user types a, then it will update and show -a-a . my program does that but it also adds extra dashes at the end and i don't know how to make it not print those extra dashes. and that brings me to another problem i am having, the user is asked at what indexes they want to guess the letter. so if the user types the letter a and at index 1, then the updated word will show -a--, but my program updates all instances of where the a is at, so it shows -a-a. here is my code:
import java.util.Scanner;
public class HangMan2 {
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int guessRemaining = 20;
int rounds = 1;
int roundScore;
String wordString = "";
String word = RandomWord.newWord();
int length = word.length();
for(int i = 0; i < length; i++)
{
wordString += "-";
}
System.out.println("The word is: " +wordString);
System.out.println("The secret word is: " +word);
System.out.println("Enter the number of spaces allowed");
int spacesAllowed = keyboard.nextInt();
keyboard.nextLine();
if(spacesAllowed > length)
{
System.out.println("Invalid input. Try again.");
System.out.println("Enter the number of spaces allowed");
spacesAllowed = keyboard.nextInt();
}
while(guessRemaining > 0) {
System.out.println("Please enter the letter you want to guess: ");
String letterGuess = keyboard.next();
char letterCharacter = letterGuess.charAt(0);
System.out.println("Please enter the number of spaces you want to check (seperated by spaces): ");
String spacesChecked = keyboard.next();
boolean guessCheck;
// check if the letter is in the string
guessCheck = (word.indexOf(letterCharacter)) != -1;
if(guessCheck == true)
{
for (int i = 0; i < word.length(); i++) {
if (letterCharacter == word.charAt(i)) {
wordString = wordString.substring(0, i) + letterGuess + wordString.substring(i);
System.out.println("Your guess is in the word!");
System.out.println("The updated word is: " +wordString);
} //end of if statement
} //end of for loop
}
else
{
System.out.println("Your letter was not found in the spaces you provided");
guessRemaining--;
System.out.println("You have " +guessRemaining+ " guesses remaining.");
}
}
if(guessRemaining != 0)
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
roundScore = (guessRemaining * 10) / spacesAllowed;
} //end of if
else{
System.out.println("Guesses Remaining: 0");
System.out.println("You have failed to guess the word... :(");
}
System.out.println("Would you like to play again? Yes (y) or No (n)");
String playAgain = keyboard.next();
if(!playAgain.equals("y") && !playAgain.equals("n"))
{
System.out.println("Invalid response, please try again... ");
}
if(playAgain.equals("y"))
{
rounds++;
}
else
{
System.exit(0);
}
}
}
wordString = wordString.substring(0, i) + letterGuess + wordString.substring(i);
if ((wordString.substring(0,i) + wordString.substring(i)).equals(wordString))
System.out.println("These are completely identical");
else
System.out.println("You solved it yourself ;)");
hint: it's 58 in your posted code.
Second part: Completely different program structure.
You'll need to track user's two guessed values, one as a character, the other as an int.
You will compare wordString.toCharArray()[indexUserGuessed] to characterUserGuessed and update the result or game state as needed, using similar code from the way you solved the if statement paradox I provided.
Finally, Welcome to Stack Exchange. MOST of us won't do your homework for you.
Oh and I would look up examples of "StringBuilder Java" as you might find it easier to manipulate your String with this class than with String.
I need help finishing this code up, I have all of the logic to it and I understand what my code needs to do, I'm just unsure where to add this piece of code to my program and keep everything else running fine.
If i put the code before the while loop without the while wrapped in the else then it works perfectly fine but it throws an exception out of bounds rather than printing the error message and continue on.
If I put the code before the while loop with the while all wrapped in the else it first prompts and after the upc code is input it then prompts again and works fine, but I don't get why it's not doing anything on the first prompt?
thanks in advance!
updated code** it now has trouble with the upc being larger than 12 and if the user enters a blank line, it doesn't print the goodbye statement or the error message, however it does print the error message if the upc is less than 12?
any suggestions would be appreciated greatly!
public class Project06 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a UPC (enter a blank line to quit): ");
String upc = keyboard.nextLine();
while (upc.length() <= 12 && upc.length()>0) {
int odd= Character.getNumericValue(upc.charAt(0))+Character.getNumericValue(upc.charAt(2))
+Character.getNumericValue(upc.charAt(4))+Character.getNumericValue(upc.charAt(6))
+Character.getNumericValue(upc.charAt(8))+Character.getNumericValue(upc.charAt(10));
int even= Character.getNumericValue(upc.charAt(1))+Character.getNumericValue(upc.charAt(3))
+Character.getNumericValue(upc.charAt(5))+Character.getNumericValue(upc.charAt(7))
+Character.getNumericValue(upc.charAt(9));
int sum= odd*3+even;
int checkDigit= Character.getNumericValue(upc.charAt(11));
if (sum%10 !=0) {
int subtract= 10-(sum%10);
if (subtract==checkDigit) {
System.out.println("Check digit should be: " +subtract);
System.out.println("Check digit is: "+ checkDigit);
System.out.println("UPC is valid");
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
upc= keyboard.nextLine();
}
else {
System.out.println("Check digit should be: " +subtract);
System.out.println("Check digit is: "+ checkDigit);
System.out.println("UPC is not valid");
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
upc= keyboard.nextLine();
}
if (upc.length() < 12 || upc.length() > 12){
if (upc.equals("")) {
System.out.print("Goodbye!");
}
else {
System.out.print("ERROR! UPC MUST have exactly 12 digits ");
System.out.println();
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
upc= keyboard.nextLine();
}
}
}
}
}
}
Look over the following code. I have put the input in a method, so you only have to do it once. The upc=null causes the checksum calculation to be skipped and ask for a new upc. I also added an error message if the sum%10 is not right.
Cliff
import java.util.Scanner;
public class upc
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
String upc = inputLine();
while ( upc == null || upc.length() == 12 )
{
if(upc != null )
{
int odd= Character.getNumericValue(upc.charAt(0))+Character.getNumericValue(upc.charAt(2))
+Character.getNumericValue(upc.charAt(4))+Character.getNumericValue(upc.charAt(6))
+Character.getNumericValue(upc.charAt(8))+Character.getNumericValue(upc.charAt(10));
int even= Character.getNumericValue(upc.charAt(1))+Character.getNumericValue(upc.charAt(3))
+Character.getNumericValue(upc.charAt(5))+Character.getNumericValue(upc.charAt(7))
+Character.getNumericValue(upc.charAt(9));
int sum= odd*3+even;
int checkDigit= Character.getNumericValue(upc.charAt(11));
if (sum%10 !=0) {
int subtract= 10-(sum%10);
if (subtract==checkDigit) {
System.out.println("Check digit should be: " +subtract);
System.out.println("Check digit is: "+ checkDigit);
System.out.println("UPC is valid");
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
} else {
System.out.println("Check digit should be: " +subtract);
System.out.println("Check digit is: "+ checkDigit);
System.out.println("UPC is not valid");
System.out.println();
} // if (subtract==checkDigit)
upc = null;
} else {
System.out.println("Bad sum. (sum%10 !=0) = "+(sum%10)+" != 0!"); // WHAT SHOULD HAPPEN HERE?
}
} else upc = inputLine();
} // while
System.out.println("End while");
} // main
public static String inputLine()
{
System.out.print("Enter a UPC (enter a blank line to quit): ");
String upc = keyboard.nextLine();
upc = upc.trim(); // removes any leading and trailing whitespace
if (upc.equals(""))
{
System.out.print("Goodbye!");
System.exit(0);
}
System.out.println(" UPC: "+upc.length()+", '"+upc+"'");
if (upc.length() < 12 || upc.length() > 12)
{
System.out.print("ERROR! UPC MUST have exactly 12 digits ");
System.out.println();
System.out.println();
System.out.print("Enter a UPC (enter a blank line to quit): ");
} else {
return upc;
}
return null;
}
} // upc
I am trying to create a simple Java program where the user should input his age. If the user entered for example a letter instead of a number, he will get a message.
What I would like to do is that in addition to the message the user should be asked for another input and that input will be checked again to see if it is a number.
Can anyone know how can I achieve that?
System.out.println("2 - Set The Age");
Scanner b = new Scanner(System.in);
if (b.hasNextDouble()) {
double lage = b.nextDouble();
setAge(lage);
addEmployeeMenu();
} else {
System.out.println("You should type only numbers!");
}
You can use a while loop like this
Scanner b = new Scanner(System.in);
double lage;
while (true) {
System.out.println("2 - Set The Age");
if(b.hasNextDouble()){
lage = b.nextDouble();
break;
}else b.nextLine();
}
The point is, get your number and check it inside a while loop, repeat as long as the input is not correct
You can also use NumberFormatException:
while (true) {
System.out.println("Set the age: ");
String input = sc.next();
try {
int x = Integer.parseInt(input);
System.out.println("Your input '" + x + "' is a integer");
break;
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
}
}