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;
}
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 **");
I recently started java programming
but I have a problem
i want to write a program. I have a password, I ask the user of the program to enter the password
I want: if the person entered a string, I tell him that please don't enter string
and if the password was right and the type of the password that he entered(int) was right, I tell him OK.
in the test of the program, my problem is that when I entered a wrong password and expect that the program tell me that the pass is wrong, the program just tell me nothing !!
here is my code :
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass)
{
System.out.println("ok");
}
else if (password.hasNextInt())
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
You are using hasNextInt() From Java docs.
Returns true if the next token in this scanner's input can be
interpreted as an int value
So you are asking twice for the input.
Example
Input:
1234 (first Input)
1234 (Then hasNextInt() is asking for input again)
OutPut :
wrong pass
So I made this simple snippet for you can use
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
int pass = 123;
try {
int myInput = password.nextInt();
if (myInput == pass) {
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (java.util.InputMismatchException e) {
System.out.println("wrong type");
}
The problem is that Scanner methods like nextInt() consume input that's then no longer available to later Scanner calls.
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass) // line A
{
System.out.println("ok");
}
else if (password.hasNextInt()) // line B
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
So in case of entering a wrong password, e.g. 4321, what happens?
Line A checks password.hasNextInt() as the first half of your condition. The Scanner doesn't know that right now and waits for your console input. You enter 4321, and now the Scanner can check whether that's a valid number (and it does so without consuming the 4321, so that it's still available). It is, so the program continues to the next part of the condition (side remark: were it abc, that first part would be false, and Java would already know that the combined password.hasNextInt() && password.nextInt()==pass condition would be false, without a need to go into the second half, thus not consuming the entry).
Line A now checks the second half password.nextInt()==pass. This calls nextInt(), returning the integer 4321 and consuming the input. Comparing this against your number 123 gives false, so the condition doesn't match. That's what you want so far.
Now in line B you want to check for the case of a number not being 123. But your condition password.hasNextInt() no longer sees the 4321 we entered, as that has been consumed in line A. So it waits for the next input. That's the problem, you're still calling hasNextInt() after consuming the input with nextInt().
You can change your program like this:
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt()) {
if (password.nextInt()==pass) {
System.out.println("ok");
} else {
System.out.println("wrong pass");
}
} else {
pass.next(); // consume the invalid entry
System.out.println("wrong type");
}
[ I reformatted the code snippet in a more Java-typical style, doesn't change the functionality of course, but looks more familiar to me. ]
Of course, Gatusko's exception-based approach works as well, and personally I'd do it his way, but maybe you don't feel comfortable with exceptions right now, so I stayed as close to your approach as possible.
You can use the following piece of code.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt())
{
if(password.nextInt()==pass) {
System.out.println("ok");
}
else {
System.out.println("Wrong password");
}
}
else
{
System.out.println("wrong type");
}
}
What about a while?
int MAX_TRIES = 3
int currentTries = 0;
while (password.hasNextInt() && currentTries < MAX_TRIES) {
if (password.nextInt()==pass) {
// OK!
} else {
// Wrong!
}
currentTries++;
}
if (currentTries == MAX_TRIES) {
// You tried too much
} else {
// Password was a string
}
Try this code, if the input is not an integer then it will throw NumberFormatException, which is caught and displayed.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
String enteredPassword ="";
if(password.hasNext() && (enteredPassword = password.next()) !=null){
try{
if(Integer.parseInt(enteredPassword) == pass){
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (NumberFormatException nfe){
System.out.println("wrong type");
}
}
}
//Payment Process
System.out.println("Order payment");
System.out.println("-------------");
System.out.println("");
System.out.printf("$%.2f remains to be paid. Enter coin or note: ", totalPrice);
double payment;
payment = scan.nextInt();
while (payment <= totalPrice) {
System.out.printf("$%.2f remains to be paid. Enter coin or note:", totalPrice - payment);
payment += scan.nextInt();
So I'm creating a project for Uni where I ask a user to buy coffee from my program. This is a snippet of the code under the payment process section. The two main questions I have are:
1. How do I make it so that the program only works when the input that is put in starts with a $ (eg. 10 would be invalid but $10.00 is valid)
2. How do I make it so that the user can only input $100.00, $50.00, $20.00, $10.00, $5.00, $2.00, $1.00, $0.50, $0.20, $0.10 and $0.05.
I wrote a small program, first is a String, so it can check whether the text is start with $. Since your program is using number, so the String will be converted to double by remove the $ after this.
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
final String payment = input.next();
if(payment.startsWith("$") && payment.matches(".*\\.\\d\\d"))
{
double paymentConverted = Double.parseDouble(payment.substring(1));
// write ur others logic here
}
else
{
System.out.println("Invalid text !");
}
}
startWith() used to check the first value, matches(".*\\.\\d\\d") check if string ends with two digits after a dot.
Between, you have some error on your code
double payment;
payment = scan.nextInt();
should be nextDouble() if not mistaken.
answer for question 1:
this checks if your input starts with a Dollar-sign($), you could move the code to a function and check it that way
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isValid = false;
String input;
do {
System.out.printf("input: ");
input = sc.next();
//check if the input is valid
if((input != null) && (input.length() > 0)) {
if('$' == input.charAt(0)) {
isValid = true;
break;
}
}
System.err.printf("Your input was invalid! input:%s%n", input);
} while(!isValid);
sc.close();
System.out.printf("Your input was correct! input:%s%n", input);
}
rather crude but simple answer for question 1 & 2:
make a Set which contains all valid inputs and check if the input is contained in that very Set.
public static void main(String[] args) {
Set<String> validInputs = new HashSet<>();
validInputs.addAll(Arrays.asList("$100.00", "$50.00", "$20.00", "$10.00", "$5.00", "$2.00", "$1.00", "$0.50", "$0.20", "$0.10", "$0.05"));
Scanner sc = new Scanner(System.in);
boolean isValid = false;
String input;
do {
System.out.printf("input: ");
input = sc.next();
// check if the input is valid
if(validInputs.contains(input)) {
isValid = true;
break;
}
System.err.printf("Your input was invalid! input:%s%n", input);
} while(!isValid);
sc.close();
System.out.printf("Your input was correct! input:%s%n", input);
}
Use nextLine() instead of nextInt() to read input, because the addition of $ makes the input a String.
When you have a short list of pre-set values that are acceptable input, the simplest way to validate input is to read the line from the user and simply compare this to a list of acceptable values that you already know.
// Create a list of allowed values
List<String> allowedValues = new ArrayList<>(Arrays.asList("$100.00", "$50.00", "$20.00"));
// read user input
String input = scan.nextLine();
// use the built-in contains() function on the List object
if (!allowedValues.contains(input)) {
System.out.println("Your input is not valid.");
}
System.out.println("Your input is valid.");
Need some help with my code. I'm trying to modify written code to ask a user for "yes" or "no" in order for the loop to continue. I'm supposed to use a prime read and a while loop to display an error message if the user inputs anything other than "yes" or "no".
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declare local variables
String endProgram = "no";
boolean inputValid;
while (endProgram.equals("no")) {
resetVariables();
number = getNumber();
totalScores = getScores(totalScores, number, score, counter);
averageScores = getAverage(totalScores, number, averageScores);
printAverage(averageScores);
do {
System.out.println("Do you want to end the program? Please enter yes or no: ");
input.next();
if (input.hasNext("yes") || input.hasNext("no")) {
endProgram = input.next();
} else {
System.out.println("That is an invalid input!");
}
}
while (!(input.hasNext("yes")) || !(input.hasNext("no")));
}
}
The hasNext method call doesn't take any parameters. Have a look at the docs.
Therefore you should get the value of the input first:
String response = input.next();
And then test the response:
!response.equalsIgnoreCase('yes') || !response.equalsIgnoreCase('no')
You could put this test into a method as you are checking the same thing multiple times.
It may be easier to see the logic of your program by changing endProgram to a boolean. Perhaps even rename it to running;
boolean running = true;
...
while (running) {
...
String response;
boolean validResponse = false;
while (!validResponse) {
System.out.println("Do you want to end the program? Please enter yes or no: ");
response = input.next();
running = isContinueResponse(response);
validResponse = isValidResponse(response);
if (!validResponse) System.out.println("That is an invalid input!");
}
}
boolean loop = false;
double numberOfStudents;
System.out.print("Enter a number: ");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
while (loop) {
System.out.println("Enter a number");
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
I'm trying to get the program to say "Enter a number" until the user has entered an actual number (no white spaces or letters or signs). When the user has entered a number, it sets numberOfStudents equal to that number and breaks out of the loop.
But if you hit enter twice, it doesn't iterate. It only displays "Enter a number" once.
What is wrong with the loop logic? Why isn't it looping until valid input is taken?
For the actual answer to your question of "Why doesn't 'Enter a number' display more than once?" see Tom's comment (update: Tom's answer).
I've rewritten your loop in a way which preserves your code, but also makes it a little easier to handle format exceptions (though at the risk of silently swallowing an exception -- should be acceptable for this use case).
Can be up to you to use this design, here is an SO post on why empty catch blocks can be a bad practice.
public static void main(String args[])
{
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(loop){
System.out.print("Enter a number: ");
String input = scnr.nextLine();
try{
numberOfStudents = Double.parseDouble(input);
loop = false;
}catch(NumberFormatException e){
}
}
System.out.println("You're outside the loop!");
}
Output:
Enter a number:
Enter a number:
Enter a number:
Enter a number: 50
You're outside the loop!
First of all: Since you're reading from System.in a call to the input stream will block until the user entered a valid token.
So let's check first scan using your scnr variable:
scnr.nextLine()
nextLine() reads everything til the next line delimiter. So if you just press return, then it will successfully read it and will perform the next stuff.
The next call is:
scnr.hasNextDouble()
This call expects a "real" token and ignores white spaces, except as a delimiter between tokens. So if you just press return again it doesn't actually read that input. So it still waits for more (for the first token). That is why it stucks in your loop and you won't get another "Enter a number" output.
You can fix that by either enter a real token, like a number, or by changing the loop like trobbins said.
I hope you now understand your program flow a bit more :).
While trobbins code basically solves your problem, it's bad practice to use exceptions for flow control.
I used a small regexp to check if the value is a number. But this example is not complete, it will still crash it the user enters for example two decimal points. So you would need to create a proper number check or just use integers where the check is much easier.
Someone in the comments pointed out that people may want to enter scientific notation like 5e10, so this would also be another case to check for. If this is just some code you need as a proof of concept or something quick and dirty, you can go with the exception handling method but in production code you should avoid using exceptions this way.
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(true) {
System.out.print("Enter a number: ");
String input = scnr.nextLine().trim();
if(input.matches("^[0-9\\.]{1,}$")) {
System.out.println("Loop has stopped");
numberOfStudents = Double.parseDouble(input);
break;
}
}
System.out.println("You're outside the loop!");
The following code should help you:
double numberOfStudents = 0;
Scanner scnr = new Scanner(System.in);
boolean readValue = false; //Check if the valid input is received
boolean shouldAskForNumber = true; //Need to ask for number again? Case for Enter
do {
if (shouldAskForNumber) {
System.out.print("Enter a number:");
shouldAskForNumber = false;
}
if (scnr.hasNextDouble()) {
numberOfStudents = scnr.nextDouble();
readValue = true;
} else {
String token = scnr.next();
if (!"".equals(token.trim())) { //Check for Enter or space
shouldAskForNumber = true;
}
}
} while (!readValue);
System.out.printf("Value read is %.0f\n", numberOfStudents);
System.out.println("You're outside the loop!");
Update
Understood the following statement in question different way:
But if you hit enter twice, it doesn't loop back. It only displays
"Enter a number" once.
The code is set to print "Enter a number" only once if the user hits RETURN/ENTER or enters space character. You may remove the special check and use the code if needed.
import java.util.Scanner;
public class Testing {
public static boolean checkInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
public static void main(String[] args) {
boolean loop = false;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
String input = "";
while (!(checkInt(input))) {
System.out.println("Enter a number");
input = scnr.nextLine();
}
numberOfStudents = Integer.parseInt(input);
System.out.println("Number of students: " + numberOfStudents );
}
}
//this code is working fine, if you want you check it out.
//In your code your taking another input if the first is an int/double; if the first input is not a number then you have mentioned to take input again..
Use a debugger to see what the code is actually doing. Here's a guide on debugging in Eclipse. After you have finished debugging your code, you will probably know what the problem is.
Below code will help you
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scnr.nextLine();
while(!scnr.hasNextDouble()){
System.out.print("Enter a number: ");
try{
numberOfStudents = Double.parseDouble(input);
break;
}catch(NumberFormatException e){
}
input = scnr.nextLine();
}
System.out.println("You're outside the loop!");
The following code is working,
boolean loop = true;
double numberOfStudents;
Scanner scnr=new Scanner(System.in);
while(loop) {
System.out.println("Enter a number");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
The output is,
run:
Enter a number
hj
po
Enter a number
lhf
Enter a number
o
Enter a number
p
Enter a number
a
Enter a number
34
Loop has stopped
You're outside the loop!
You have to scan the next line if you want to get more values form the scanner again. The code should be like:
while (loop) {
System.out.println("Enter a number");
if(!(scnr.nextLine().trim().isEmpty())){
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
}