user3288334
user3288334

Reputation: 7

Print the correct output

i wrote this program and the point is to print out the correct middle word....whats the code to make it print out the correct middle word?

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.

}
}

Upvotes: 0

Views: 91

Answers (2)

Karim Massi
Karim Massi

Reputation: 77

you can use other String named outputString and than assign the value from the if statement it can be str 1, 2 or 3 so follow the code bellow

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

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34176

You could create an array String[], sort it, and print the middle value:

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

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

Upvotes: 0

Related Questions