Answer to Question #292698 in Java | JSP | JSF for Yash

Question #292698

Write a program that has a method commonPre (String str1, String str2) that


returns the common prefix of two strings. For example, the common prefix of “distance” and


“disinfection” is “dis”. If the two strings have no common prefix, the method displays “No


common prefix”. The user should be prompted to enter two strings in JOptionPane and


display their common prefix, if any. Use JOptionPane for all inputs and outputs.

1
Expert's answer
2022-02-01T05:54:33-0500
import javax.swing.JOptionPane;


public class App {


	/**
	 * The start point of the program
	 * 
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		String str1 = JOptionPane.showInputDialog("Enter the string 1: ");
		String str2 = JOptionPane.showInputDialog("Enter the string 2: ");
		JOptionPane.showMessageDialog(null, commonPre(str1, str2));
	}


	private static String commonPre(String str1, String str2) {
		int minLenght = str1.length();
		if (minLenght > str2.length()) {
			minLenght = str2.length();
		}
		String commonPrefix = "";
		for (int i = 0; i < minLenght; i++) {
			if (str1.charAt(i) == str2.charAt(i)) {
				commonPrefix += str1.charAt(i);
			} else {


				if (commonPrefix.length() > 0) {
					return commonPrefix;
				} else {
					break;
				}
			}
		}
		if (commonPrefix.length() > 0) {
			return commonPrefix;
		}
		return "No common prefix";
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS