2014-02-08 142 views
0

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

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. 

} 
} 
+0

那么问题是什么?什么不适用于这个代码? – hichris123

+0

中间单词isnt打印出来 – user3288334

+0

您可以发布样本输入和输出吗?还有一个猜测:你有输入大写字母吗? – hichris123

回答

0

您可以创建一个数组String[],排序,并打印中间值:

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

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

我们还在我们班学习过数组,这就是为什么我不能使用数组 – user3288334

+0

erm .... @Christian给了你代码,它是一个很好的例子。数组是编程的一个非常基本的组件,所以学习它们会是明智的。 –

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);