虽然循环没有正确执行

时间:2013-11-08 07:23:53

标签: java

我一直在尝试正确执行此代码但似乎缺少某些内容。程序需要输入字符串并检查它是否为空。如果不是,则应检查是否存在除字母之外的任何字符。如果是,它应该抛出错误并再次执行while循环以获取另一个输入。如果一切正常,它应该退出while循环并返回字符串。无法理解缺少的东西。任何形式的帮助都将受到高度赞赏。

import java.util.Scanner;

public class Validator
{
    public static String getString(Scanner sc, String prompt)
{
    char temp;
    String s = "";
    boolean isValid = false;
      while (isValid == false)
    {
    System.out.print(prompt);
    s = "";
    s = sc.next();  // read user entry
    sc.nextLine();  // discard any other data entered on the line

    if (s == null || s.equals(""))
            System.out.println("Please enter a valid input");
    else
    {
        check:
    for (int i =0; i<s.length(); i++)
    {
         temp = s.charAt(i);
        if (!Character.isLetter(temp))
        {
            System.out.println("Invalid input. The name should consist of only alphabets");
            break check;
         }
        }
                }
                 isValid = true;
    }
      return s;
}

}

3 个答案:

答案 0 :(得分:0)

你可以像这样使用休息

    if (!Character.isLetter(temp))
    {
        System.out.println("Invalid input. The name should consist of only alphabets");
        break;
     }

PS - 检查了什么?

答案 1 :(得分:0)

为避免输入无效,您应使用goto check:continue语句。但continue更可取。

if (!Character.isLetter(temp)){
  System.out.println("Invalid input. The name should consist of only alphabets");
  continue;
}

答案 2 :(得分:0)

修改您的代码,如

package com.practice.strings;

import java.util.Scanner;

公共课比较{

/**
 * @param args
 */
public static void main(String[] args) {
    getString();
    System.out.println("exit");
}

public static String getString() {
    Scanner sc = new Scanner(System.in);
    char temp;
    String s = "";
    boolean isValid = false;
    while (isValid == false)
    {
        s = "";
        s = sc.next();  // read user entry
        sc.nextLine();  // discard any other data entered on the line

        if (s == null || s.equals(""))
            System.out.println("Please enter a valid input");
        else
        {
            int i;
            for (i =0; i<s.length(); i++)
            {
                temp = s.charAt(i);
                if (!Character.isLetter(temp))
                {
                    System.out.println("Invalid input. The name should consist of only alphabets");
                    break ;
                }
            }
            if (i == s.length())
                isValid = true;
        }
    }
    return s;
}

}