344,604 views
16 votes
16 votes
Print the two strings in alphabetical order. Assume the strings are lowercase. End with newline. Sample output: capes rabbits import java.util.Scanner: public class OrderStrings { public static void main (String args) { String firstString: String secondString: firstString = "rabbits" secondString = "capes" /*Your solution goes here */ return: } }import java.util.Scanner;public class OrderStrings { public static void main(String[] args) { String firstString; String secondString; firstString = "rabbit"; secondString= "capes"; //String class in java provide string comparison function, use it, and get //your work done may even use brute force i.e using for loop and compare character by // character which will not good for the programming language which already have vast //predefined number of functions if(firstString.compareTo(secondString) < 0){ System.out.println(firstString + " " + secondString); } else{ System.out.println(secondString + " " + firstString); } return; }}

User Alexander Shishenko
by
3.2k points

1 Answer

17 votes
17 votes

Answer:

Following are the code to the given question:

import java.util.Scanner;//import package

public class OrderStrings // defining a class OrderStrings

{

public static void main(String[] args) //defining a main method

{

Scanner scnr = new Scanner(System.in);//defining a Scanner class object

String firstString;//defining a String variable

String secondString; //defining a String variable

firstString = scnr.next();//input value

secondString = scnr.next();//input value

if (firstString.compareTo(secondString) < 0)//use if to compare sting value

System.out.println(firstString + " " + secondString);//print sting value

else//else block

System.out.println(secondString + " " + firstString);//print sting value

}

}

Output:

rabbits capes

capes rabbits

Explanation:

In this code a class "OrderStrings" is defined inside the class the main method is defined that declares the two string variable that uses the input method to input the string value and after input, it uses the conditional statement. Inside this compareTo method is declared that compare string value and prints the string value.

User Joice
by
2.8k points