I am brushing up on my Java skills by trying to solve the below assignment problem I found on the internet:
Write a Java method that accepts two strings as parameters and returns a string that contains all unique two-character strings whose first character comes from the first string and second character comes from the second string. All two-character strings in your returned string should be separated by a space. Use ordinary string concatenation in your solution. Look at the examples below for a "hint" on how to proceed and look at the String API for methods you can use to simplify your solution.
Example
First string = ABCD
Second string = EFGH
Returned string > AE AF AG AH BE BF BG BH CE CF CG CH DE DF DG DH
How can I improve this code?
package com.assignments.java;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* This is an Assignment Program for Java
*
* @author SaiUpadhyayula
*
*/
public class JavaAssignmentOne {
public static void main(String[] args) throws IOException {
BufferedReader bReader = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter First String");
String firstString = bReader.readLine();
System.out.println("Enter Second String");
String secondString = bReader.readLine();
String returnedString = constructCharSequence(firstString, secondString);
System.out.println("Returned String : " + returnedString.trim());
}
public static String constructCharSequence(String firstString,
String secondString) throws IOException {
String biggerString = firstString;
String smallerString = secondString;
String returnedString = "";
// Determine the smaller and bigger Strings from
// the given two input strings
if (firstString.length() <= secondString.length()) {
biggerString = firstString;
smallerString = secondString;
} else {
biggerString = secondString;
smallerString = firstString;
}
// Construct the given required character sequence
// by iterating over the two input strings
for (int i = 0; i < biggerString.length(); i++) {
for (int j = 0; j < smallerString.length(); j++) {
// As we require unique two-character string
// check whether the string sequence already exists
// in the returnedString
if (!returnedString.contains("" + biggerString.charAt(i)
+ smallerString.charAt(j) + "")) {
returnedString = returnedString + biggerString.charAt(i)
+ smallerString.charAt(j) + " ";
}
}
}
return returnedString;
}
}