【问题标题】:Current If statement involving String涉及字符串的当前 If 语句
【发布时间】:2016-10-01 09:04:01
【问题描述】:

基本上我的作业应该占用 2 个单词,计算我所做的两个单词中最小的一个,但现在我需要引用最小的单词本身而不是数字。我认为这需要一个 If 语句,但是当我使用 system.out.println 命令结束程序时,我无法初始化我的字符串,并且控制台变得很挑剔。

Scanner scan = new Scanner(system.In); 
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
Int pass1l = pass1.length();
System.out.println(" input second password "); 
String pass2 = scan.nextLine();
Int pass2l = pass2.length();
Int spassl = Math.min(pass1l,pass2l);
// problematic part here. 
String spass;
If (pass1l > pass2l){ spass = pass2}
else if (pass1l < pass2l) {spass = pass1}
else if (pass1l == pass2l) {spass = null;};

Else if 语句也作为 not 语句出现,第一个是表达式的非法开头。

然后,如果我修复了那些我用 system.out 调用 spass 并且它说它没有初始化。我刚开始学习基本的 Java,我之前使用过处理,但不是用于与字符串相关的 if 语句,只有整数。

【问题讨论】:

    标签: java string if-statement


    【解决方案1】:

    你快到了。变量 spass 需要在您使用没有 final else 的 if 块时进行初始化。要么你给 spass="" 要么改变 final else if 到 else 如下。

        Scanner scan = new Scanner(System.in);
        System.out.println(" Input first password ");
        String pass1 = scan.nextLine();
        System.out.println(" input second password ");
        String pass2 = scan.nextLine();
        // problematic part here.
        String spass;
        if (pass1.length() > pass2.length()) {
            spass = pass2;
        } else if (pass1.length() < pass2.length()) {
            spass = pass1;
        } else {
            spass = null;
        }
        System.out.println("result: " + spass);
    

    【讨论】:

    • 在我看来你不应该为初学者推荐没有括号的代码=/
    【解决方案2】:

    你的问题只是一个格式问题,如果语句是这样的格式:

    if(condition){
        do_something;
    }else if( second_condition ){
        do_something_else;
    }else{
        alternative;
    }
    

    在您的情况下,您似乎不知道在哪里设置分号;

    你必须像这样在 if 块内设置分号:

    String spass;
    If (pass1l > pass2l){ 
        //Here semicolon
        spass = pass2;
    } else if (pass1l < pass2l) {
        //Here semicolon
        spass = pass1;
    }else if (pass1l == pass2l) {
        //Here semicolon
        spass = null;
    }
    //No semicolon at the end of the if-else-statement
    

    【讨论】:

      猜你喜欢
      • 2015-02-11
      • 2015-01-07
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 2012-11-18
      相关资源
      最近更新 更多