目前,我是一名开始学习java的学生。我不熟悉数组或任何复杂的方法。我的老师希望我们这样做以理解所涉及的逻辑,因此我无法使用内置的排序功能。有时我的代码有效。例如,当我输入" iea"时,它会打印" aei",这是正确的。但是,有时当我输入像" abc"这样的输入时,它只会打印" c"作为中间价值。救命?我是个菜鸟。
import java.util.*;
public class SortThreeLetters {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
char largest = ' ';
char middle = ' ';
char min = ' ';
String word;
System.out.println("Enter three lower case letters: ");
word = sc.nextLine();
char letter1 = word.charAt(0);
char letter2 = word.charAt(1);
char letter3 = word.charAt(2);
if ( letter1 > letter2 && letter1 > letter3 ){
largest = letter1;
if(letter2 > letter3){
middle = letter2;
min=letter3;
}
else if (letter3>letter2){
middle = letter3;
min=letter2;
}
}
else if ( letter2 > letter1 && letter2 > letter3 ){
largest = letter2;
if(letter3>letter1){
letter3=middle;
letter1=min;
}
else if (letter1>letter3){
letter1 = middle;
letter3 = min;
}
}
else if ( letter3 > letter1 && letter3 > letter2 ){
largest = letter3;
if(letter2>letter1){
letter2 = middle;
letter1 = min;
}
else if (letter1>letter2){
letter1 = middle;
letter2 = min;
}
}
System.out.println(min+""+middle+""+largest);
}
}
答案 0 :(得分:0)
if ( letter1 > letter2 && letter1 > letter3 ){
largest = letter1;
if(letter2 > letter3){
middle = letter2;
min=letter3;
}
else if (letter3>letter2){
middle = letter3;
min=letter2;
}
}
else if ( letter2 > letter1 && letter2 > letter3 ){
largest = letter2;
if(letter3>letter1){
middle=letter3;
min=letter1;
}
else if (letter1>letter3){
middle=letter1;
min=letter3;
}
}
else if ( letter3 > letter1 && letter3 > letter2 ){
largest = letter3;
if(letter2>letter1){
middle=letter2;
min=letter1;
}
else if (letter1>letter2){
middle=letter1;
min=letter2;
}
}
答案 1 :(得分:0)
您的作业声明是问题的原因。赋值运算符=
的左侧是受让人,运算符的右侧是分配值。检查
else if ( letter2 > letter1 && letter2 > letter3 )
和
else if ( letter3 > letter1 && letter3 > letter2 )
您需要在largest
运算符的左侧包含变量middle
,min
,=
。