繁体   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