How to check entered String in a loop with condition? - java

I want to write a program, which is checks an entered String of the user for a given char limits (10 chars for instance). If entered String is more than 10 chars, then the system should re-prompt again and again the user to enter the valid String (a word of 10 chars) until the user enter a valid string.
I have already some piece of code for it, but its not works yet, because I've no idea how to move process up to start (to the line 1) for re-prompt the user or there is other simple way?
System.out.print("Input: ");
String inputChars = Input.readString();
while (inputChars.length() > 10){
System.out.print("Input: ");
String inputChars = Input.readString(); // here is mistake now
}
System.out.print("Output: ");
System.out.print("The enter has 10 chars");
I just want to check the entered word, if is more than 10 chars, then just skip it and prompt the user again for entering a word which is not more than 10 chars. I'm not yet good in java, so if this question is stupid just explain me how to solve it. Thanks in advance

Look at your loop:
while (inputChars.length() > 10){
System.out.print("Input: ");
String inputChars = Input.readString();
}
The second line of the loop body redeclares the inputChars variable. You can't do that, as it's already in scope. You want to just replace the previous value:
inputChars = Input.readString();
You should also consider restructuring your code to avoid the duplication though:
String inputChars;
do {
System.out.print("Input: ");
inputChars = input.readString();
} while (inputChars.length() > 10);
Note how I've also renamed the Input variable to input to follow normal Java naming conventions. I'd actually probably change both input and inputChars to be more descriptive - in particular, there's no indication of what the input data is meant to mean at the moment.

Just remove the String in beginning:
while (inputChars.length() > 10){
System.out.print("Input: ");
inputChars = Input.readString(); // here is mistake now
}
By having String in beginning, you are attempting the redefine the same name variable again.

Change to:
String inputChars = ""
do {
System.out.print("Input: ");
inputChars = Input.readString();
} while (inputChars.length() > 10)
System.out.print("Output: ");
System.out.print("The enter has 10 chars");
Before, inputChars had already been declared before the loop, so you didn't need to redeclare the variable.
A do-while loop is a better construct here because it makes your intentions more clear and makes your code more clean.

Related

input mismatch exception while using space in between words

I'm working on a project and I already finished it, I have really simple problem which makes me really confused. I'm trying to ask a user to enter a number from a menu and depending on that different things happen, but I get input mismatch exception whenever I type space in between words. I get that error on the last line of the code, please check my code below, Thanks.
System.out.println("Enter: " + "\n1.Enter Name" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
if(userChoice == 1) {
System.out.println("Enter name");
String name = kb.next();
}
if(userChoice == 2) {
System.out.println("Enter anohter name");
String anotherName = kb.next();
}
if(userChoice == 3)
break;
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
The issue is with your usage of Scanner#next(), in combination with wanting to input multiple "words" sepearted by a whitespace for example. (Disclaimer: I understand your question in the way that you want to enter multiple words for the "name" input, this answer takes that as a prerequisite)
See following excerpt from the Scanner#next() Javadoc:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter for the Scanner is a whitespace. So when you request a name from the user, and the user wants to enter "John Doe", only "John" will be read, and "Doe" will be left, most likely causing the error you are seeing.
The workaround I would propose is to use nextLine() to read the whole line while providing each input line by line.
However, be aware of this issue: Scanner is skipping nextLine() after using next() or nextFoo()?
Keeping that in mind, I would modify your code as follows:
String name = "";
String anotherName = "";
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
kb.nextLine(); // consumes the newline character from the input
if(userChoice == 1) {
System.out.println("Enter name");
name = kb.nextLine(); // reads the complete line
// do something with name
} else if (userChoice == 2) {
System.out.println("Enter another name");
anotherName = kb.nextLine(); // reads the complete line
// do something with anotherName
}
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
Sidenotes:
I moved the declaration of your name and anotherName variables, as they don't have to be re-declared everytime.
However you should actually do something with them (e.g. save them in a list, or create some object with them) otherwise they will be lost on the next loop iteration.
You can omit the check for if (userChoice == 3) since this would never happen in combination with the while (userChoice != 3).
Example input:
Enter:
1.Enter Nmame
2.Enter another name
3.Exit
1
Enter name
John Doe
1.Enter Nmame
2.Enter another name
3.Exit
3

Can you have a boolean expression repeat in a while loop?

I have found a way to make my program recognize if something is a palindrome or not, but when it is not, the program will not repeat.
I already have the boolean section of this implemented before my provided code.
Originally was set with if statements, wanted to replace with while but something like while (!yespalin(potentialp)) doesn't work either
Scanner scan = new Scanner(System.in);
String potentialp;
System.out.println("Please enter a potential palindrome: ");
potentialp = scan.nextLine();
while (yespalin(potentialp))
{
System.out.println("That string is a palindrome");
}
while (!yespalin(potentialp))
System.out.println("That string is not a palindrome, please enter another: ");
potentialp = scan.nextLine();
}
I want the program to repeat if not a palindrome
For starters I see you are missing "{" on your second while.
However I do not undetstand exactly why do you need 2 while loops.
If you would read your code line by line, you can understand why that the first loop is the only one who prints the "correct" line.
However if you enter a bad palindrome, it will never enter the first loop, therefore won't print the desired sentence.
You want 1 loop which will end if you put the correct value if im not mistaken
Which would look something like this:
Scanner scan = new Scanner(System.in);
String potentialp;
System.out.println("Please enter a potential palindrome: ");
potentialp = scan.nextLine();
while (!yespalin(potentialp)){
System.out.println("That string is not a palindrome, please enter another: ");
potentialp = scan.nextLine();
}
System.out.println("That string is a palindrome");
Hope it was helpful.

How to repeatedly enter a string until user enters keyword to stop loop in java

I am stuck in this program that is string method, my issue is that I cannot get the loop to stop and the program to print the output that is currently stored after the keyword has been entered. I am not trying to compare strings, I am trying to input multiple strings and add a word, in this case, "not" to the strings until the word "stop" is entered. Once "stop" has been entered. the system will output the entire string stored.
Here is the question for the program:
(StringConcat.java) This program asks the user to repeatedly enter a String. It ,should concatenate those Strings together, but insert spaces and the word “not” between every pair of words the user enters. Stop when the user enters the String “stop”. Display the final String. For instance, the program output might look like:
Please enter some Strings:
"Such"
"eyes"
"you"
"have"
"stop"
"Such not eyes not you not have"
Here is my code so far:
import java.util.*;
public class StringConcat{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String s = new String();
System.out.print("Please enter some Strings: ");
for(int x=0; x<s.length(); x++){
s = sc.nextLine();
s = s + "not ";
if(s == "stop"){
System.out.println(s);
break;
}
else{
continue;
}
}
}
}
Several issues with your code:
(1) Why do you use a for loop and iterate up to s.length() when the length of s (which is 0 at that point) has nothing to do with your problem?
You need a loop which has not predefined number of iterations like a while (true) from which you will exit with a break.
(2) In each iteration you get the user's input and store it in s, so you lose all previous values.
You need a separate variable to store the user's input.
(3) The continue statement is not needed as the last statement in a loop.
(4) Because at each iteration you append " not " at the end, after the loop has finished you must delete that last " not " from s
(5) Don't use == when you compare strings. There is the method equals() for this.
This is my solution:
Scanner sc = new Scanner(System.in);
String s = "";
System.out.print("Please enter some Strings: ");
while (true){
String input = sc.nextLine();
if(input.equalsIgnoreCase("stop"))
break;
s += input + " not ";
}
if (s.length() >= 5)
s = s.substring(0, s.length() - 5);
System.out.println(s);
Use while loop.
Why while loop?
Usually we have to use while loops always when we don't know the number of loops we will do. In this case only when the user inputs "stop".
So you need a String field to hold the user words. Also we can use a number field to track if is the first or the second word, thinkg in append the "not" word.
Then, take a look in this example:
Scanner s = new Scanner(System.in);
String currentAnswer = "";
String userWords = "";
int tracker = 0;
while (!currentAnswer.equals("stop")){
currentAnswer = s.nextLine();
userWords += currentAnswer + " ";
if (tracker % 2 != 0) {
userWords += "not ";
}
tracker++;
}
System.put.println(userWords);
This can be done using for loop too but I really recommend the while loop to this case.
EDIT:
As you saw, I used equals() instead == to compare two Strings because we are wiling to check for its value, not for its object equality.
When we use == operator we are trying to check if two objects target to the same memory adress, but we only want to know if two Strings have the same value.
For this case is valid to know that we can compare it using other ways, such as Objects.equals() or even contentEquals().
Check this discussion to learn more about comparing strings.

Easy fix for while loop not executing properly second time?

I'm fairly new at java and have a current assignment to take a given word, put the first word at the end, rebuild the word from reverse, and see if it's the same word as the original, such as: grammar, potato, uneven, dresser, banana etc. So far I have this:
Scanner input = new Scanner(System.in);
String original, reverse = "";
String exit = "quit";
int index;
System.out.println("Please enter a word (enter quit to exit the program): ");
original = input.next();
while (!original.equalsIgnoreCase(exit))
{
String endingChar = original.substring(0, 1);
String addingPhrase = original.substring(1);
reverse += endingChar;
for (index = addingPhrase.length() - 1; index >= 0; --index)
{
char ch = addingPhrase.charAt(index);
reverse += ch;
}
if (original.equals(reverse))
{
System.out.println("Success! The word you entered does have the gramatic property.");
}
else
{
System.out.println("The word you entered does not have the gramatic property."
+ " Please try again with another word (enter quit to exit the program): ");
}
original = input.next();
}
input.close();
When I run it and enter the word "banana," it properly recognizes that it is indeed the same backwards when the b is moved to the end, and does the same with the other words listed above, but when I enter a second word on the loop, it never recognizes it properly, and always responds with the print statement from the else block:
Please enter a word (enter quit to exit the program):
banana
Success! The word you entered does have the gramatic property.
banana
The word you entered does not have the gramatic property. Please try again
with another word (enter quit to exit the program):
I'm guessing it's something to do with either the way I made my for loop, or the way I asked for input at the end of the while loop, but like I said I'm fairly new and awful at debugging. Any help would be much appreciated, thanks a lot in advance.
You are changing string reverse in every iteration, but you are not clearing it. So before the end of the loop or at the beginning clear the string for example like so: reverse = "", and then it should be fine.
Just add reverse = ""; in the end of the while loop in order to set the variable reverse to its original state, i.e. empty string

How to prevent Java scanner from inputing spaces

I'm trying to prevent the user from inputting spaces or no values.
but nothing works. Even with no entered values program goes further without printing my error. What am I doing wrong?
my code example
Scanner nameScan = new Scanner(System.in);
System.out.print("Input your name: ");
String newcomer = nameScan.nextLine();
player.setName(newcomer);
String userName = player.getName();
userName = userName.trim();
if (userName.length()==0) {
System.out.println(" ");
System.out.println("You have to set up a player name first... ");
System.out.println(" ");
}
else {...
As #11thdimension said, you have to validate the input.
You can do something like:
if (newcomer.isEmpty()) {
System.out.println("Please write something");
}
Or you can do a while loop and keep asking for a correct input.
Your code
if(username.length() == 0)
will not check whether the username contains space because space is counted towards the length of the String.
To check for empty String input(which may contain space(s)), you can do:
if("".equals(username.replaceAll("\\s+",""))) //or
if("".equals(username.trim()) //or
if(username.isEmpty())
Further more, you would want to use a do-while loop for validation instead of using an if-statement.

Categories

Resources