【问题标题】:Java Scanner how to input string if functionJava Scanner如何在函数中输入字符串
【发布时间】:2017-02-02 20:57:58
【问题描述】:

我是 Java 编程的新手。

我的问题是我有一个代码(见下文),我想将它们与 if 语句进行比较。 line 9 (string test)11(if(test.equals) 出现错误。我完全不知道。

我用 int 编写了一个代码,它工作得很好,但是那个。

package bucky;

import java.util.Scanner;

class apples {
    public static void main(String args[]) {

        Scanner input = new Scanner(System.in);
        Scanner sc = new Scanner(System.in);
        String test = sc.nextLine();
        if (test.equals("YES")) {
            System.out.println("YES");
        } else {
            System.out.println("TIS IS ELSE");
        }
    }

}

【问题讨论】:

  • 什么错误?请添加堆栈跟踪或错误消息。
  • 欢迎来到 Stack Overflow!请查看我们的SO Question Checklist 以帮助您提出一个好问题,从而得到一个好的答案。

标签: java string if-statement int


【解决方案1】:

你快到了...将 YES 定义为字符串,并且它

 String test = sc.nextLine();   
 String YES = "yes";   
 if (test.equals(YES)) {

或者更好地使用equalsIgnoreCase() 这样你就可以摆脱区分大小写的输入

 if (test.equalsIgnorecase(YES))

【讨论】:

  • 先生方法是if (test.equalsIgnoreCase(YES))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多