首页 > 解决方案 > 验证方法中的输入

问题描述

我是java新手,目前正在尝试学习它!

我对方法有疑问,下面是我的代码示例。

import java.util.*;

public class test
{
    public static void main(String[] args) 
    {
        char key;
        Scanner info = new Scanner(System.in);
        System.out.print("Enter Keyword: ");
        key = info.next().charAt(0);
        while(key!='W'&&key!='w'&&key!='M'&&key!='m')
        {   
            System.out.println("Invalid Keyword");
            System.out.print("Enter Keyword");
            key = info.next().charAt(0);
        }

        System.out.print("Valid key");
    }

    public static char validKey(char key)
    {
        ///i want the while validation to go here instead of in the main
    }
}
  1. 正如我在代码中所写,有没有办法在 validKey 方法中而不是在 main 方法中验证密钥?
  2. 有没有办法让我不必在while条件中指定'w'和'W'?

对不起,如果我不能很好地解释它,提前谢谢!

标签: javamethods

解决方案


  1. 如果要检查是否key正确,可以执行以下操作:
import java.util.*;

    public class test
    {
        public static void main(String[] args)
        {
            char key;
            Scanner info = new Scanner(System.in);
            System.out.print("Enter Keyword: ");
            key = info.next().charAt(0);

            while(!validKey(key))
            {
                System.out.println("Invalid Keyword");
                System.out.print("Enter Keyword");
                key = info.next().charAt(0);
            }

            System.out.print("Valid key");
        }

        public static boolean validKey(char key)
        {
            if(Character.toLowerCase(key)!='w' && Character.toLowerCase(key)!='m') {
                return true;
            } else {
                return false;
            }
        }
    }
  1. 这取决于。如果案例大小不重要,您可以尝试以下操作:
    while(Character.toLowerCase(key)!='w' && Character.toLowerCase(key)!='m')
    {   
        ...
    }

如果我的回答对您有帮助,请回信;)


推荐阅读