簡體   English   中英

無法從 java 中的 boolean 方法獲得回報

[英]can't get a return from a boolean method in java

試圖檢查單詞的字母是否按字母順序排序。但我沒有從該方法中得到任何回報。

import java.util.Scanner;

public class A284 {
    //Write a Java program to check
    // if each letter of a given word (Abecadrian word) is less than the one before it.

    public static boolean abecidarianWord(String word){
        int index=word.length()-1;
        for(int i=0;i<index;i++){
            if (word.charAt(i)<=word.charAt(i+1)){
                return true;
            }else return false;
        }
        return true;
    }
    public static void main(String[] args) {
        String entry;
        System.out.println("input a word: ");
        Scanner s1=new Scanner(System.in);
        entry=s1.next();
        abecidarianWord(entry);

    }
}

你這里有兩個問題。

首先,您沒有使用從abecidarianWord返回的值,您只是調用它並忽略結果,因此您無法知道該方法將返回什么。 因此,您應該將返回值分配給一個變量並對其進行處理。 例如,在你的main結束時,一個幼稚的實現會執行以下操作:

boolean isOrdered = abecidarianWord(entry);
if (isOrdered) {
    System.out.println("String is ordered");
} else {
    System.out.println("String is not ordered");
}

其次,在abecidarianWord中,您在循環的第一次迭代后立即返回,這只會告訴您您的條件是否對前兩個字符成立。

相反,您可能希望在找到遵守條件的對時立即返回false ,如果在沒有“意外”的情況下到達循環末尾,則返回true ,例如:

public static boolean abecidarianWord(String word) {
    for (int i=0; i < word.length -1; i++) {
        if (word.charAt(i) > word.charAt(i+1)) {
            return false;
        }
    }
    return true;
}

您已成功返回value

 import java.util.Scanner;

public class A284 {

public static boolean abecidarianWord(String word){
    //you are getting length of "word" here
    int index=word.length()-1;
    for(int i=0;i<index;i++){
        if (word.charAt(i)<=word.charAt(i+1)){
            //If condition are correct return true.
            return true;
        }else{
            //If condition are incorrect return false
            return false;
        }
    }
    return true;
}
public static void main(String[] args) {
    String entry;
    //Printing a text
    System.out.println("input a word: ");
    //getting values from user
    Scanner s1=new Scanner(System.in);
    entry=s1.next();
    //calling a class
    abecidarianWord(entry);
    //You have get the value. But, you are actually trying to say that why it's not printing in output. When you return something you have to put them in another function to print-out
    System.out.println(abecidarianWord(entry));
    //If you don't wanna do it than you have to write SOUT instead of return. Than you can output the way you wrote
}
}

您在第一次比較時返回 true,因此您的循環只運行一次。 相反,在 for 循環中更改 if 條件,如下所示。

if (word.charAt(i)>word.charAt(i+1)){
                return false;
}

@Istiak 是完全正確的。

但只是為了優化你的代碼來做我認為你最想要的,我只想說 if 語句 -> if (word.charAt(i)<=word.charAt(i+1))每兩個迭代單詞中的字符,如果只有兩個字母按順序排列,您不想返回 true,理想情況下替換return true; 只有一個空的; 否則您的 function 將在找到一對連續正確放置的字母后立即停止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM