用户输入upperCase和lowerCase - Java

时间:2017-11-18 04:19:17

标签: java

我试图在Uppercase或LowerCase中输入A或B来继续通过if语句。我无法弄清楚如何做到这一点。目前,它只接受了UpperCase A或B.看了一下论坛和课堂笔记,没有提出任何建议。任何帮助都会得到满足! 我尝试使用toUpperCase(),但不认为我把它放在正确的位置。它一直给我一个错误

import java.util.Scanner;

public class printNumber{
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please select an option between A or B: ");
        char user = input.next().charAt(0);

        System.out.println("You have selected " +user+ " : ");    
        if (user == 'A'){
            for(int n=1; n<=100; n++){
                if((n%2)==0)
                    System.out.println(n);
            }
        }
        else if (user =='B'){
            for (int x =1; x<=100; x=x+2){
                System.out.println(x);
            }
        }
        else
            System.out.println("Error, please try again!");
    }
}

4 个答案:

答案 0 :(得分:3)

您可以使用

char user = input.next().toUpperCase().charAt(0);

答案 1 :(得分:2)

import java.util.Scanner;

public class printNumber{
  public static void main (String[] args){
        Scanner input = new Scanner(System.in);

        System.out.println("Please select an option between A or B: ");
    String opt=input.nextLine();

    System.out.println("You have selected " +user+ " : ");

    if (opt.equalsIgnoreCase("A")){

    for(int n=1; n<=100; n++){
      if((n%2)==0)
        System.out.println(n);
     }
    }
    else if (opt.equalsIgnoreCase("B")){
    for (int x =1; x<=100; x=x+2){
      System.out.println(x);
     }
    }
    else
      System.out.println("Error, please try again!");
  }
}

或者你可以简单地使用

  import java.util.Scanner;

    public class printNumber{
      public static void main (String[] args){
            Scanner input = new Scanner(System.in);

            System.out.println("Please select an option between A or B: ");
        String opt=input.next();

        System.out.println("You have selected " +user+ " : ");

        if (opt == "A" || opt == "a"){

        for(int n=1; n<=100; n++){
          if((n%2)==0)
            System.out.println(n);
         }
        }
        else if (opt == "B" || opt == "b"){
        for (int x =1; x<=100; x=x+2){
          System.out.println(x);
         }
        }
        else
          System.out.println("Error, please try again!");
      }
    }

答案 2 :(得分:1)

试试这个

if (user == 'A' || user == 'a')

同样的'B'

答案 3 :(得分:1)

您正在调用next()类的Scanner方法,该方法返回String,因此您可以使用character方法将其转换为equalsIgnoreCase()而不是"a".equalsIgnoreCase("A")用于验证的输入字符串。但是,如果用户输入的字符串长度大于1,请始终检查输入字符串的长度并显示错误消息。

"a".equalsIgnoreCase("a")和{{1}}将永远为真。