2014-02-08 2 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

중간 단어가 인쇄되지 않습니다 – user3288334

+0

샘플 입력 및 출력을 게시 할 수 있습니까? 그리고 추측 : 입력에 대문자가 있습니까? – hichris123

답변

0

당신은 중간 값 정렬을 배열 String[]를 작성하고 인쇄 할 수 있습니다 :

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

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

우리는 아직 배운 배열을 havnt하지만 우리 클래스에서는 왜 배열을 사용할 수 없습니까? – user3288334

+0

erm .... @Christian은 코드를 주었고 좋은 예입니다. 배열은 프로그래밍의 꽤 기본적인 구성 요소이므로 배울 것이 현명합니다. –

1

당신이 outputString라는 이름의 다른 문자열을 사용하여 이상이 str에 할 수있는 if 문에서 값을 할당 할 수 있습니다 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); 
관련 문제