Exercise:
(Longest common prefix) Write a program that prompts the user to enter two strings and displays the largest common prefix of the two strings.
Here are some sample runs:
Enter the first string: Welcome to C++
Enter the second string: Welcome to programming
The common prefix is Welcome to
Second run:
Enter the first string: Atlanta
Enter the second string: Macon
Atlanta and Macon have no common prefix
my answer:
package chapter5;
import java.util.*;
public class Exer5_51 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first string: ");
String firstString = input.nextLine();
System.out.println("Enter the second string");
String secondString = input.nextLine();
input.close();
int length = Math.min(firstString.length(), secondString.length());
String commonPrefix = "";
for (int n = 0; n < length; n++) {
if (firstString.charAt(n) == firstString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
else {
break;
}
}
if (commonPrefix.length() != 0) {
System.out.printf("The common prefix is %s", commonPrefix);
}
else {
System.out.printf("%s and %s have no common prefix", firstString, secondString);
}
}
}
Is there anything wrong with my code?
Why I can't get the right result?.
if (firstString.charAt(n) == firstString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
Should be:
if (firstString.charAt(n) == secondString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
You were comparing the first String to itself before.
You are comparing the firstString to itself in the if statement.
if (firstString.charAt(n) == firstString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
Related
I'm a beginner in Java and got this school problem:
The authority of XYZ gated residential colony wants its residents' name datum Should be stored in the following format - residents' name his/her father's name. Write a program to concat the father's name to the residents' name. The name should be validated,on validation the name should contain only alphabets and space is allowed. If the name is not valid display the message "Invalid name". If valid string then convert it to uppercase and print it
Sample Input 1:
Inmate's name:Aron
Inmate's father's name:Terby
Sample Output 1:
ARON TERBY
Error: It prints out "Invalid Input" whenever I enter a two-letter Inmate's name like- Aron Kumar otherwise for a single word string input code works alright.
This was the code I wrote:
Scanner sc=new Scanner(System.in);
System.out.println("Inmate's name:"); //if I enter 2 word string,output-"Invalid name1"//
String name=sc.nextLine();
System.out.println("Inmate's father's name:");
String fname=sc.nextLine();
String s3=name.toUpperCase();
String s4=fname.toUpperCase();
char[] a1= s3.toCharArray();
char[] a2= s4.toCharArray();
for(int i=0;i<a1.length;i++)
{
if(a1[i]>='A' && a1[i]<='Z')
count=1;
else {
System.out.print("Invalid name1");
count=0;
break; }
}
if(count==1)
{
for(int i=0;i<a2.length;i++)
{
if(a2[i]>='A' && a2[i]<='Z')
count=2;
else {
System.out.print("Invalid name");
break; }
}
}
if(count==2) {
System.out.print(s3+" "+s4);
}
}
}
The problem is that you are not checking for a space character. Check it as follows:
if (a1[i] >= 'A' && a1[i] <= 'Z' || a1[i] == ' ')
Another problem with your code is changing the value of count to 1 and 2 in each iteration whereas it should be changed when the loop terminates. Given below is the corrected code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int count = 0, i;
Scanner sc = new Scanner(System.in);
System.out.println("Inmate's name:");
String name = sc.nextLine();
System.out.println("Inmate's father's name:");
String fname = sc.nextLine();
String s3 = name.toUpperCase();
String s4 = fname.toUpperCase();
char[] a1 = s3.toCharArray();
char[] a2 = s4.toCharArray();
for (i = 0; i < a1.length; i++) {
if (!(a1[i] >= 'A' && a1[i] <= 'Z' || a1[i] == ' ')) {
System.out.print("Invalid name1");
count = 0;
break;
}
}
// If 'i' reached a1.length, it means no invalid character was found
if (i == a1.length) {
count = 1;
}
if (count == 1) {
for (i = 0; i < a2.length; i++) {
if (!(a2[i] >= 'A' && a2[i] <= 'Z' || a2[i] == ' ')) {
System.out.print("Invalid name");
break;
}
}
// If 'i' reached a2.length, it means no invalid character was found
if (i == a2.length) {
count = 2;
}
}
if (count == 2) {
System.out.print(s3 + " " + s4);
}
}
}
Additional note:
You can make your code much shorter by using regex as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Inmate's name: ");
String name = sc.nextLine();
System.out.print("Inmate's father's name: ");
String fname = sc.nextLine();
if (name.matches("[A-Za-z\\s]+") && fname.matches(("[A-Za-z\\s]+"))) {
System.out.println(name.toUpperCase() + " " + fname.toUpperCase());
} else if (!name.matches("[A-Za-z\\s]+")) {
System.out.println("Inmate's name is invalid");
} else if (!fname.matches(("[A-Za-z\\s]+"))) {
System.out.println("Inmate's father's name is invalid");
}
}
}
The explanation of the regex, [A-Za-z\\s]+:
A-Za-z is for alphabets.
\\s is for space.
The + at the end of [A-Za-z\\s]+ means more than one occurrences are allowed.
A sample run:
Inmate's name: Ram Kumar
Inmate's father's name: Raj Kumar
RAM KUMAR RAJ KUMAR
Another sample run:
Inmate's name: Ram5 Kumar
Inmate's father's name: Raj Kumar
Inmate's name is invalid
Another sample run:
Inmate's name: Ram Kumar
Inmate's father's name: Raj5 Kumar
Inmate's father's name is invalid
When you compare char values in Java, you're relying on the ASCII value of that char. The ASCII value of A is 65, whereas the ASCII value of Z is 90.
Your current code is simply evaluating each char in the character array to make sure it's in the range of 65 to 90, inclusive. The ASCII value of the space char, however, is 32, falling well outside of that range.
Rewrite your code to accept capital letters or spaces (as dictated by the problem description) like so:
if((a1[i]>='A' && a1[i]<='Z') || (a1[i] == 32))
It happens because here
if(a1[i]>='A' && a1[i]<='Z') count=1;
You asking "if char in array is between A and Z, then count = 1"
But in case with name "Aron Kumar" You have a space symbol between two words and this space symbol is not between A and Z, so count don't equals 1 and output is "Invalid Input".
You have to check char array for space too.
You can take the answer of MarsAtomic as a good example.
import java.util.Scanner;
import java.util.regex.*;
public class Authority{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Inmate's name:");
String Inmate = s.nextLine();
System.out.println("Inmate's father's name:");
String father = s.nextLine();
if(!Pattern.matches("^[a-zA-Z\\s]+",Inmate))
{
System.out.println("Invalid name");
}
else if(!Pattern.matches("^[a-zA-Z\\s]+",father))
{
System.out.println("Invalid name");
}
else
{
String k = Inmate +" "+ father;
System.out.println(k.toUpperCase());
}
}
}
Im stuck on this, I need a code that use 2 nested loops for this assignment (there are other solutions, but I need to demonstrate my understanding of nested loops). But I just dont get it. The outer loop repeats the entire algorithm and the inner loop iterates half-way (or less) through the string. I am not sure on what I need to put inside the for loops. This is what I have so far. Any Assistance would be pleasured.
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String x = 0;
String y = input.length-1;
for (String i = 0; i < line.length-1; i ++){
for (String j = 0; j < line.length-1; j ++){
if (input.charAt(x) == input.charAt(y))
{
x++;
y--;
}
}
}
}
Example Output:
Enter a string: 1331
1331 is a palindrome.
Enter a string: racecar
racecar is a palindrome.
Enter a string: blue
blue is NOT a palindrome.
Enter a string:
Empty line read - Goodbye!
Your algorithm is flawed, your nested loop should be to prompt for input - not to check if the input is a palindrome (that requires one loop itself). Also, x and y appear to be used as int(s) - but you've declared them as String (and you don't actually need them). First, a palindrome check should compare characters offset from the index at the beginning and end of an input up to half way (since the offsets then cross). Next, an infinite loop is easy to read, and easy to terminate given empty input. Something like,
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string: ");
System.out.flush();
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
boolean isPalindrome = true;
for (int i = 0; i * 2 < line.length(); i++) {
if (line.charAt(i) != line.charAt(line.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.printf("%s is a palindrome.%n", line);
} else {
System.out.printf("%s is NOT a palindrome.%n", line);
}
}
System.out.println("Empty line read - Goodbye!");
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String reversedText ="";
for(int i=line.length()-1/* takes index into account */;i>=0;i++) {
reversedText+=line.split("")[i]; //adds the character to reversedText
}
if(reversedText ==line){
//is a palidrome
}
}
Your code had lot of errors. I have corrected them and used a while loop to check if its a palindrome or not. Please refer below code,
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
String line;
boolean isPalindrome = true;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
int x = 0;
int y = line.length() - 1;
while (y > x) {
if (line.charAt(x++) != line.charAt(y--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(line + " is a palindrome");
} else {
System.out.println(line + "is NOT a palindrome");
}
System.out.println();
}
}
}
It's hard to explain but I'm trying to create a program that only capitalizes the letter of every word that ends with a period, question mark, or exclamation point. I have managed to receive a result when inputting any of the marks but only when it is entered the second time. In other words I have to hit enter twice to get a result and I'm not sure why. I am still working on it on my own but I'm stuck at this problem.
import java.util.*;
public class SentenceCapitalizer
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
String wrong = keyboard.nextLine();
String[] check = {".!?"};
String upper_case_line="";
Scanner lineScan = new Scanner(line);
for (String sent : check)
{
if (sent.startsWith(wrong))
{
System.out.println("cant use .?!");
}
else
{
/* if (line.startsWith(" "))//if starts with space
System.out.println("good");
else
System.out.println("bad");
*/
//if (int i = 0; i < line.length; i++)
//{char c = line.chartAt(i);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) +
word.substring(1) + " ";
}
System.out.println(upper_case_line.trim());
}
}
}
}
Solution
Hey just a quick solution for your question. Converts the string to character array and then checks the character array for '.!?' if it finds the value then it will make the next letter a capital!
public class SentenceCapitalizer {
public static void main(String[] args) {
//Scanner, Variable to hold ouput
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
//Char array, boolean to check for capital
char [] lineChars = line.toCharArray();
boolean needCapital = false;
//String to hold output
String output = "";
//Check for period in line
for (int i = 0; i < lineChars.length; i++) {
//Make sure first char is upper case
if (i == 0) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
}
//Check for uppercase if char is not space
if (needCapital && Character.isLetter(lineChars[i])) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
needCapital = false;
}
if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') {
needCapital = true;
}
//Add character to string
output += lineChars[i];
}
//Output string
System.out.println (output);
}
}
I am trying to write a program that checks if a string is a palindrome and so far I know I am on the right path but when I enter my code it keeps on running for ever. I don't know what the problem is and would like help finding out the solution. In my program I want the user to enter word or words in the method Printpalindrome and then the program should know if the string is a palindrome or not.
Here is my code:
...
Scanner console = new Scanner (System.in);
String str = console.next();
Printpalindrome(console, str);
}
public static void Printpalindrome(Scanner console, String str) {
Scanner in = new Scanner(System.in);
String original, reverse = "";
str = in.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- ) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse))
System.out.println("Entered string is a palindrome.");
}
}
Because of this line:
n = in.nextLine();
your program is waiting for a second input, but you already got one before entering the function.
Remove this line and it works.
Here's your program, cleaned (and tested) :
public static void main(String[] args){
Scanner console = new Scanner (System.in);
String n = console.next();
Printpalindrome(n);
}
public static void Printpalindrome(String n){
String reverse = "";
for ( int i = n.length() - 1; i >= 0; i-- ) {
reverse = reverse + n.charAt(i);
System.out.println("re:"+reverse);
}
if (n.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is NOT a palindrome.");
}
Of course, this isn't the best algorithm, but you already know there are many QA on SO with faster solutions (hint: don't build a string, just compare chars).
Remove
Scanner in = new Scanner(System.in);
and
n = in.nextLine();
from Printpalindrome function
and it should work.
This can be implemented in a far more efficient manner:
boolean isPalindrom(String s){
if (s == null /* || s.length == 0 ?*/) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
The argument for PrintPalindrom is ignored. You read another value with `in.nextLine()'. Which is the reason for your issues.
Ur code with some correction:-
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
I tried your code and what i observed was that :
first of all you are making a string to enter on the line 2 of your code:
String n=console.next();
next the the program again goes to waiting when this line gets executed:
n = in.nextLine();
actually this particular line is also expecting an input so that is why the program halt at this point of time.
If you enter your String to be checked for palindrome at this point of time you would get the desired result .
But I would rather prefer you to delete the line
n = in.nextLine();
because, with this, you would have to enter two words which are ambiguous.
I have the following code:
import java.util.Scanner;
public class chara{
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
return;
}
else
{
}
System.out.println("now input a letter to be replaced");
String letter = input.next();
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
}
}
the code needs to do three things take a string and a letter and :
replace the key letter in the string with "-"
remove the key letter of the string
count the amount of times the key letter appears.
At present I have two problems. I don't know how to count the amount of times the letter
appears because technically it is a string and not a char and i do not know how to count
strings. Second, I need to make it so that if the strings are not of the desired length it
simply asks again instead of exiting the program. I have tried to use the getString() method but for some reason it always says that the method is undefined.
For issue #1:
Near the top of the main method:
int count = 0;
After user3 is assigned:
count += (user3.length() - user.length());
With full credit to user1324109 for their solution to issue #1, here is how you can solve your issue #2:
import java.util.Scanner;
public class StringReader {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user1 = "", user2 = "", user3 = "";
int count = 0;
while(user1.equals("") || user1.length() < 7) {
System.out.println("Input a string");
user1 = input.nextLine();
}
if(!user1.equals("")) {
System.out.println("now input a letter to be replaced");
String letter = input.next();
user2 = user1.replace(letter, "-");
user3 = user1.replace(letter, "");
System.out.println(user2);
System.out.println(user3);
count += (user1.length() - user3.length());
System.out.println("letter was found to be present "+count+" times");
}
}
}
To help with issue #3:
int count = 0;
for(char c : user.toCharArray() ){
if ( c == letter.charAt(0)) count++;
}
System.out.println("Number of occurences: "+count);