内部的字符串比较if else失败

时间:2018-02-11 13:43:21

标签: string if-statement compare

import java.util.Scanner;

public class BeispielBundesländer {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("How many states are there?");
        int states = scan.nextInt();
        String president = "Test Person";

        if (states == 9) {
            System.out.println("Good Job!");
            System.out.println("Now tell me the presidents name!");

            String presidentInput = scan.nextLine();

            if (presidentInput.equals(president)) {
            System.out.println("Well done!");
            } else {
                System.out.println("Fail!"); }
        } else {
            System.out.println("Fail!");
                }
    }
}

第二个中的字符串比较如果'presidentInput.equals(president)'永远不会起作用。我用“String presidentInput = scan.next();”尝试了它,但问题是它只保存第一个字,例如变量presidentInput中的“Test”而不是“Test Person”。所以我尝试nextLine(),但是这甚至不让我写任何东西,只是跳过失败。

1 个答案:

答案 0 :(得分:0)

from math import gcd        
def get_smallest_co_prime(M):
    if gcd(M)>1:
        return gcd(M)





    TypeError: gcd() takes exactly 2 arguments (1 given)

}

  

以上代码可以帮助您。

public class BeispielBundesländer {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("How many states are there?");
    int states = sc.nextInt();
    sc.nextLine();
    String president = "Test Person";
    if (states == 9) {
        System.out.println("Good Job!");
        System.out.println("Now tell me the presidents name!");
        String presidentInput = sc.nextLine();
        System.out.println(presidentInput);
        if (presidentInput.equals(president)) {
            System.out.println("Well done!");
        } else {
            System.out.println("Fail!");
        }
    } else {
        System.out.println("Fail!");
    }
}
  

这将读取行上剩余的数字(在我怀疑的数字之后没有任何内容)

尝试放置scanner.nextLine();如果您打算忽略该行的其余部分,则在每个nextInt()之后。