打印正确的输出

时间:2014-02-08 22:18:44

标签: java string output

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

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.

}
}

2 个答案:

答案 0 :(得分: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 ); 

答案 1 :(得分:0)

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

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

 System.out.println(strings[1]);