Write a Java program that prompts the user to enter 3 string

Write a Java program that prompts the user to enter 3 strings, and displays the largest common prefix of the three strings. If there is a common prefix display the percentage the common prefix is of the longest string. For example if the largest string is 20 letters and the common prefix is 5 letters then the common prefix is 25% of the longest string. Do not include spaces in that determination. Display a message if there are no common prefixes

Solution

//Java program


import java.util.Scanner;

public class Programming {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(\"Enter the first string:\");
String s1 = input.nextLine();
System.out.print(\"Enter the second string:\");
String s2 = input.nextLine();
System.out.print(\"Enter the third string:\");
String s3 = input.nextLine();

int l = s2.length();
int p = 0;
float percent;

if ( s1.length() > s2.length() && s1.length() > s3.length() )
l = s1.length();
else if ( s2.length() > s1.length() && s2.length() > s3.length() )
l = s2.length();
else if ( s3.length() > s1.length() && s3.length() > s2.length() )
l = s3.length();

for (int i = 0; i <= l; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
break;
}
if (s1.charAt(i) != s3.charAt(i)) {
break;
}
p++;
}

if (p == 0) {
System.out.println(s1 + \" and \" + s2 + \" and \" + s3 + have no common prefix\");
System.exit(0);
}

percent = (p/l) * 100;
System.out.println(\"The common prefix is \" + s1.substring(0, p));
System.out.println(\"the common prefix is\" + percent + \"the longest string.\" have no common prefix\");

}
}

p.s Do check syntax before proceeding.

Thanks,

Happy Chegging

Write a Java program that prompts the user to enter 3 strings, and displays the largest common prefix of the three strings. If there is a common prefix display

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site