如何解决无法从 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;
替换为一个空的 ;
,否则您的函数将在找到一对连续的两个正确放置的字母后立即停止。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。