【问题标题】:Print the correct output打印正确的输出
【发布时间】:2014-02-08 22:18:44
【问题描述】:

我写了这个程序,重点是打印出正确的中间词....什么代码让它打印出正确的中间词?

import java.util.Scanner; //The Scanner is in the java.util package.

public class MiddleString {
public static void main(String [] args){
Scanner input = new Scanner(System.in); //Create a Scanner object.

String str1, str2, str3; 

System.out.println("Enter the first word: "); //Prompt user to enter the first word
str1=input.next(); //Sets "str1" = to first word.
System.out.println("Enter a second word: "); // Prompt user to enter the second word
str2=input.next(); //Sets "str2" = to second word.
System.out.println("Enter a third word: "); // Prompt user to enter the third word        
str3=input.next(); //Sets "str3" = to third word.


if((str1.compareTo(str3) < 0) && (str1.compareTo(str2) <0) && (str2.compareTo(str3) <0) )
System.out.println(str2);

else if (( str3.compareTo(str1) <0) && (str1.compareTo(str2) <0) && (str3.compareTo(str2) <0) )
System.out.println(str1);

else if ( (str1.compareTo(str2) <0) && (str3.compareTo(str2) <0) && (str1.compareTo(str3) <0) )
System.out.println(str3);


System.out.println("The middle word is "  ); // Outputs the middle word in alphabetical order.

}
}

【问题讨论】:

  • 那么问题出在哪里?这段代码有什么问题?
  • 中间字没有打印出来
  • 你能发布示例输入和输出吗?一个猜测:你的输入中有一个大写字母吗?

标签: java string output


【解决方案1】:

您可以使用其他名为 outputString 的字符串,而不是从 if 语句中分配值,它可以是 str 1、2 或 3,因此请遵循以下代码

String outputString ="";
if((str1.compareTo(str3) < 0) && (str1.compareTo(str2) <0) && (str2.compareTo(str3) <0) ){
System.out.println(str2);
outputString=str2 ; 
}

else if (( str3.compareTo(str1) <0) && (str1.compareTo(str2) <0) && (str3.compareTo(str2) <0) ){
System.out.println(str1);
outputString=str1 ; 
}
else if ( (str1.compareTo(str2) <0) && (str3.compareTo(str2) <0) && (str1.compareTo(str3) <0) ){
System.out.println(str3);
outputString=str3 ; 
}


System.out.println("The middle word is " +outputString ); 

【讨论】:

    【解决方案2】:

    您可以创建一个数组String[],对其进行排序,然后打印中间值:

     String[] strings = { str1, str2, str3 };
     Arrays.sort(strings);
    
     System.out.println(strings[1]);
    

    【讨论】:

    • 我们还没有在课堂上学习过数组,这就是为什么我不能使用数组
    • erm.... @Christian 给了你代码,这是一个很好的例子。数组是编程的一个非常基本的组件,因此学习它们是明智的。
    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2021-01-11
    • 2017-08-07
    • 1970-01-01
    相关资源
    最近更新 更多