I am attempting to validate user input. I have tried some if statements and attempted Boolean. I cant get anything to give the output or rather the validation I am wanting
Users are asked to choose between "red" or "blue" I want them to be required to type either "red" or "blue". I know this could be solved easier through buttons but I am trying to use string input. the code below give an example of where i am.
custColorMsg = "Which color do you want your shirt to be red or blue?";
customerColor = getstringInput(custColorMsg);
String color = null
if( customerColor.equalsIgnoreCase("yes")) {
color = true}
if( customerColor.equalsIgnoreCase("no")) {
color = true}
else if(!customerColor.equalsIgnoreCase("yes" || "no") {
color = false}
I know this last portion is wrong I am just unsure how to go about fixing it. Customers will have three chances to input a valid response then the program will terminate, this portion i can handle. If i can just figure out how to accept "yes" or "no" and refuse anything else.
In terms of the design of this program, I would recommend adding a for loop, that goes from 0 to 2 (this will iterate 3 times). Within the loop, the program can determine what the user's input is. I would also recommend looking at my syntax for the for loop below, I use ifs, else ifs and elses to evaluate the data set more efficiently.
The implementation of the program could be:
for(int i = 0; i < 3; i++)
{
customerColor = getstringInput(custColorMsg);
String color = null
if( customerColor.equalsIgnoreCase("yes")) {
color = true;
break;
}
else if( customerColor.equalsIgnoreCase("no")) {
color = true;
break;
}
else{
color = false;
}
custColorMsg = "Invalid Input, Please Input Again";
}
This will give the user 3 times to input the data, and if they input it correctly, it will stop asking, however, if they do not, it will ask again until they run out of attempts.
There's a few things wrong with your approach.
The semantics of your variable names are a bit off. Which makes the code difficult to read. For example, the variable color which you have defined here as a String, but consistently use as a Boolean is a bit confusing. I'm guessing you mean to define it as a Boolean type and intend to use it as the breaking condition from your loop - it would be more meaningful to name the it as isValidColor or something along those lines.
The following line doesn't do what you think it does:
customerColor.equalsIgnoreCase("yes" || "no")
The method equalsIgnoreCase() takes in a String and not a Boolean like this line of your code will have for an argument. Since the || will resolve to a Boolean value of true or false. Furthermore, those are bad operand types for that operator and the code won't compile.
For your control structure you can use a while loop which will exit when you have reached the max amount of tries or entered a valid response.
Here's a working Console version of what you are trying to accomplish:
String custColorMsg = "Which color do you want your shirt to be red or blue?";
String customerColor;
Boolean validInput = false;
Scanner in = new Scanner(System.in);
int tries = 0;
while (tries < 3 && !validInput)
{
System.out.println(custColorMsg);
customerColor = in.nextLine();
if( customerColor.equalsIgnoreCase("red")) {
validInput = true;
}
else if( customerColor.equalsIgnoreCase("blue")) {
validInput = true;
}
tries++;
}
Related
My code is supposed to keep looping until a valid input is given, ie: if a letter is given it will loop, but if a valid number is given, the code should store it into cSec. Is there anyway to do this?
byte cSec;
boolean contCSec = true;
while(contCSec == true) {
System.out.println("Enter course section: ");
cSec = sc.nextByte();
if(cSec>0)
contCCode = false;
}
cSec can't be used outside the loop.
A rather less verbose form of what you wrote might be:
byte cSec;
do {
System.out.println("Enter course section: ");
cSec = sc.nextByte();
} while (cSec <= 0);
where 'cSec <= 0' denotes an invalid value, per your original, though I imagine there's more to validation than that.
This does not match your title (initialize within loop) since to me that's exactly what you don't want to do.
I think this is clearer than your original since it involved no flag values, and the do...while loop shows up the 'ask then decide to loop' nature a little better.
Adding more validation:
byte cSec;
do {
System.out.println("Enter course section: ");
try {
cSec = sc.nextByte();
}
catch (InputMismatchException ex) {
System.out.println("A number is required");
cSec = -1;
}
} while (cSec <= 0);
In addition to another-dave's wonderful answer, you can suppress the compiler warning by initializing cSec outside of the loop.
byte cSec = 0;
boolean contCSec = true;
while(contCSec == true) {
System.out.println("Enter course section: ");
cSec = sc.nextByte();
if(cSec>0)
contCSec = false;
}
The reason that you get the warning without the first declaration is because, as strange as it sounds, the compiler does not analyze the contents of your boolean in while(contCSec == true). It sees that there is a while loop, and it sees that there will be a boolean resulting from (contCSec == true), but as far as the compiler is concerned, any boolean going into your while condition could be true, or could be false. This means that you could enter the while loop, or you could... not.
As far as the compiler is concerned, anything inside the while loop could happen, or could not happen, and there is no way to know without actually running the code. (If you want to know why this is actually a strict limitation for computers, check out the halting problem.) That means that the compiler has no idea whether cSec = sc.nextByte(); will ever happen or not. Hence, the warning.
Trying to create a simple program that has three options for text input. If the user types one of the three, the program moves on. If the user types something else, the program loops back and asks for the input again until a proper response is given.
Using a drop down list or other method will not work, as this is for an assignment.
System.out.print("Enter one of the following: cheese, water, or burger: ");
userMedium = user_input.nextLine( ); // store user input as a string
mediumConvert = userMedium.toLowerCase();
boolean verifyName;
if (mediumConvert.equals("cheese") || mediumConvert.equals("water") || mediumConvert.equals("burger")){
verifyName = false;
} else {
verifyName = true;
}
while (verifyName = true){
System.out.println("Please input a valid medium (cheese, water, or burger): ");
userMedium = user_input.nextLine( );
mediumConvert = userMedium.toLowerCase();
}
This is what I have set up so far, but this just keeps repeating the loop OVER AND OVER. After this section I want to execute a switch to work off each of the three correct responses.
I've spent the last hour on google and YouTube, but everything I found is using integers. It seems pretty easy to validate user input when it is just a number and an operand. But how do I use three possible strings?!
while (verifyName = true)
↑
You're assigning and not comparing. The expression of the assignment returns the assigned value, so your loop is equivalent to:
while (true)
You should change it to:
while (verifyName)
Basically, you should write while (verifyName == true), but it's redundant since it's like asking "Is it true that verifyName has the value true?". Also it prevents potential bugs, like just inserting one = instead of two..
Noticed two things:
1.) By doing
while(verify = true)
you are actually assigning the value true to verifyName. You need to use
while(verifyName)
2.) Where do you reassign the value of verifyName?
You should be validating and reassigning inside the while block.
Also you should consider cleaner alternative solution, but that can wait for another day.
You will never break out of the whileloop because the variable verifyName is never updated inside the loop. This means that you'll either never execute the loop because the user inserted the input you wanted or you'll end up with an infinite loop.
You need to do your input verification inside the loop as well and be careful with the boolean validation as well.
Something like:
while (verifyName) {
System.out.println("Please input a valid medium (air, water, or steel): ");
userMedium = user_input.nextLine( );
mediumConvert = userMedium.toLowerCase();
if (mediumConvert.equals("cheese") || mediumConvert.equals("water") || mediumConvert.equals("burger")){
verifyName = false;
} else {
verifyName = true;
}
}
I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}
newbie programmer here. I'm using Java to try and create a number guessing game. I want my do while loop to continue looping until the user inputs the correct number OR they run out of guesses. This is what I have and I can't figure out how to use 2 boolean controllers for the life of me.
do
{System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
} while ((userGuess != actualNumber) || (remainingGuesses = guesses; remainingGuesses >= 1; remainingGuesses--));
Any help is appreciated!
I think that you want something closer to this effect:
remainingGuess = guesses;
do {
System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
} while ( userGuess != actualNumber || remainingGuesses-- > 0 )
Line by line:
remainingGuesses = guesses;
assigns guesses to remainingGuesses once, if you were to do it every iteration of your loop, it would never end
userGuess != actualNumber || remainingGuesses-- > 0
Keep iterating while the user has guessed incorrectly OR remainingGuesses is more than 0.
remainingGuesses--
Evaluates to the current value of the variable remainingGuesses, then after the expression decrements it by 1.
Initialize remaining guesses before entering the loop. Only check the condition in the while paranthesis "()"
reaminingGuesses = guesses;
do
{System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
remainingGuess--;
} while ((userGuess != actualNumber) || (remainingGuesses >= 1));
If you want it as a do while I would make a few minor changes, and assuming you have constants defined for things like actualNumber and the total number of allowed guesses:
// break the calls into seperate methods, to make them easier to read in the long term and to
// seperate logical concerns into discrete elements.
do {
// get the user guess
guess = getGuess();
// if shouldStop returns true you would stop, if it returns false you should continue, thus the !..
} while (!shouldStop(guess)) {
// decrement the guesses.
--remainingGuesses;
}
/// define these methods somewhere..,
// get your guess
public int getGuess() {
System.out.println("Enter guess #1");
return keyboard.nextInt();
}
public boolean shouldStop(int guess) {
// condensed if statement syntax in java, very handy for this kind of thing
// do we have enough remaining guess to keep going? If so, compare the guess to the actual number
// otherwise return true (the stop signal
return remainingGuesses > 0 ? guess == actualNumber : true;
}
If you really wanted to follow the whole thing through you could break the guess==actual number into a method as well, but its probably not needed in this case since its a simple equality check.
The methos shouldStop could be defined a number of ways however...
Early on I think it's helpful to write these logical blocks out fully, and condense from there, for example:
public boolean shouldStop(int guess) {
if(remainingGuesses <=0) {
return true;
} else if(guess == actualNumber) {
return true;
} else {
return false;
}
}
I am trying to make a test of whether an inputted word is a palindrome or not (the same spelled forward and backward). From what I can see it should work but Eclipse says "The value of the local variable isPalindrome is not used" , but it is used. The problem is that even if the word is not a palindrome it says it is.
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
String phrase;
char[] phraseLetters;
int endChar;
boolean isPalindrome;
Scanner input = new Scanner(System.in);
System.out.println("Enter a word or phrase.");
phrase = input.nextLine();
input.close();
phrase = phrase.toLowerCase();
phrase = phrase.replaceAll(" ","");
phraseLetters = phrase.toCharArray();
endChar = phraseLetters.length - 1;
for (int i = 0; i < phraseLetters.length; i++) {
if (phraseLetters[i] != phraseLetters[endChar]) {
isPalindrome = false;
} else {
isPalindrome = true;
endChar -= 1;
}
}
if (isPalindrome = true) {
System.out.println("This word or phrase entered is a palindrome.");
} else {
System.out.println("This word or phrase is not a palindrome.");
}
}
}
EDIT: I have tried the if statement being
if (isPalindrome == true)
and
if (isPalindrome)
In both cases Eclipse says "The local variable isPalindrome may not have been initialized," in this if condition.
FINAL EDIT:
I have since moved on, and rewritten this code, however I just went back and fixed my original code if anyone still looks at this.
I initialized isPalindrome at the beginning of the code:
Boolean isPalinddrome = True;
I changed the for-loop condition to:
for (int i = 0; (i < phraseLetters.length) && (isPalindrome); i++)
Finally I changed if (isPalindrome = true) to if (isPalindrome)
if (isPalindrome = true) should be if (isPalindrome == true) (or if (isPalindrome) better! Actually this error is another good reason why not asking if someBoolean == true which is a bad style)
By typing if (isPalindrome = true) you're assigning, again, the value true to the variable isPalindrome. And since you're only assigning value to it, the compiler warns you about unused variable.
It's also good to know this:
At run time, the result of the assignment expression is the value of
the variable after the assignment has occurred. The result of an
assignment expression is not itself a variable.
So, when you do if (isPalindrome = true) then the if condition is always satisfied.
You should assing some boolean value to isPalindrome in the main scope.
For example:
boolean isPalindrome = true
You have a typo.
if (isPalindrome = true)
{
System.out.println("This word or phrase entered is a palindrome.");
}
else
{
System.out.println("This word or phrase is not a palindrome.");
}
Look at the if condition. You used = instead of ==. So, you are setting isPalindrome to true, only the true block is executed, and the compiler sees that isPalindrome never matters.
Now, your class has some logic flaws and some programming traps.
If the first and last characters are not equal, isPalindrome is set to false, and then the program continues. Break out of the loop; don't let isPalindrome be set to true later. Incidentally, your version actually cares only about the first and last characters.
Don't write if (x == true). Just write if (x).
Don't name your boolean isAnything. After all, you may do this in a JavaBean class, and then you'll end up with a method named isIsAnything or getIsAnything. This will annoy your readers.
In the future, don't write all your code in the main(String[]) method. Have the main method use the arguments to construct an instance of the class, and use that instance. This way, you can write unit tests for the class; you can't for main. You can break the code into a few methods. One checks for being a palindrome, while another provides the human-readable output.
It's actually a bad idea to use the no-argument forms of String.toLowerCase() and String.toUpperCase() One day, you might need to write an internationalized application, and you will have to deal with the Turkish locale. You might end up mumbling to yourself, “What the heck is a dotless i?”
Don't use i and j as variable names here. Use names that show the variable's purpose. Something like:
for (int start = 0, end = phraseLetters.length - 1; start < end; start++, end--) {
...
}
After all, when start passes end, you're just repeating yourself.
There are an error and bad practice here.
The bad practice is not to initialize the variabale:
boolean isPalindrome = true;
alththough all primitives in java have a default value (for boolean it's false) it's still always better to intialize the varibale explicitly in order enhance code redability.
The error is in the if clause:
if (isPalindrome = true) {
in this line you assign the value and not checking the variabale , all assigment return the value of the assignment meaning that this expression will always return true. Because of this your code always retrun true.