简体   繁体   中英

How to check entered String in a loop with condition?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM