Show Characters shared between two strings - java

For a Java exercise I'm writing a program where the user enters two strings. The program then checks to see if the two strings share any similar characters and outputs them to the screen.
For example is Terrarium and Terraform are the two strings it should print t e r r a r. However when I run my program it always simply outputs all the characters in the first string. (In this case T e r r a f o r m.)
I suspect I'm creating a logical error based on a limited understanding of loops. But when I search for answers people seem to always use a similar method to my own.
Here is the code for your viewing:
import java.util.Scanner;
public class CountMatches
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(" Please enter a String >> ");
String stringA = keyboard.nextLine();
System.out.println(" Please enter another String >> ");
String stringB = keyboard.nextLine();
for(int counter = 0; counter < stringA.length(); counter++ )
{
char compareA = stringA.charAt(counter);
char compareB = stringB.charAt(counter);
//System.out.println(compareA);
//System.out.println(compareB);
//System.out.println("");
if(compareA != compareB)
{
System.out.println("");
}
else if(compareA == compareB);
{
System.out.println(compareA);
System.out.println("");
}
}
}
}

else if(compareA == compareB);
Get rid of the semicolon on this line and it should work. I would also get rid of the first if statement just keep the second one.

You have two problems with this code.
First,
for(int counter = 0; counter < stringA.length(); counter++ )
If the two string are of different length, you could get an exception by going off the end of the other string. So, do this:
int len = stringA.length();
if (len > stringB.lengh()) len = stringB.length();
Next, the reason you code fails is because you have a ; at the end of your else. Your code should be:
if(compareA != compareB)
{
System.out.println("");
}
else // Don't need the == here
{
System.out.println(compareA);
System.out.println("");
}
Good luck with this.

Related

Why does my program keep looking for inputs?

This code is in Java. It allows me to enter the first input fine, but after the second is inputted it keeps looking for more strings, none of the rest of my code follows. Idealy the code will find if 2 strings are anagrams, but I have not been able to test this due to this annoying problem.
import java.util.*;
public class Anagram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word");
String first = scan.nextLine();
System.out.println("Please enter a second word");
String second = scan.next();
first = first.toLowerCase();
second = second.toLowerCase();
int lengthF = first.length();
int lengthS = first.length();
int x = 0;
int y = 0;
int placeF=0;
int placeS=0;
char g = 97;
int count =0;
if(lengthF != lengthS)
{
System.out.println("The words are not anagrams");
x=1;
}
while(x == y||g<123)
{
x=0;
y=0;
for(int i = 0;i<lengthF;i++)
{
if(first.charAt(i)==g)
{
x++;
}
}
for(int i = 0;i<lengthS;i++)
{
if(second.charAt(i)==g)
{
y++;
}
}
count++;
g++;
}
if(count==23)
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}
I've spotted three bugs in your code, which you can easily find by yourself if you always follow these general rules for programming:
Never use numbers obscurely. Write them in a way that explains where that value comes from: Instead of:
char g=97;
... let it be:
char g='a';
And the same goes for every single "special" number in your program: 97, 123 and 23 (In this way you'll see 23 is wrong).
Indexed loops should be always for, with its initial value, its ongoing condition and its increment operation. Ongoing condition must be the index interval condition, plus optional secondary conditions combined by AND operators.
And the third bug... Well, right now I cannot think of any general rule to avoid it. It must have been a copy-and-paste issue: The variable lengthS is wrongly initialized.
Also, I recommend you not to code the same algorithm more than once: Take it out to an individual function and reuse it. So you can do with the loop that counts the number of occurrences of a certain char within a certain string. You could define it like this:
private static int countOccurrencesOfChar(String s, char c) {...}

String having r & g separated by 5 characters! (Error:String index out of range error)

Given an input string,check whether the string has char 'r' & 'g' separated be exactly 5 characters.
For the following code, the error is String index out of range error.
Can't figure out whats wrong
My code for class having function that checks for pattern:
public class classb {
String s = new String();
public int match(String str){
int counter = 0;
int j;
s=str;
for(j=0;j<(s.length()-6);j++){
if(s.charAt(j)=='r' && s.charAt(j+6)=='g') {
counter=1;
break;
}
if(s.charAt(j)=='g' && s.charAt(j+6)=='r'){
counter=1;
break;
}
while(s.charAt(j)!='r' || s.charAt(j)!='g'){
if(j<(s.length()-6))
j++;
else
break;
}
}
return counter;
}
}
Main class:
import java.util.*;
public class classa
{
public static void main(String[] args)
{
String a = new String();
int count;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
a= sc.nextLine();
classb x = new classb();
count=x.match(a);
if(count==1)
System.out.println("Pattern found ");
else if(count==0)
System.out.println("Pattern not found ");
}
}
You can use a regex for this problem, r.{5}g.
The r says that the pattern starts with r, and the g says that it ends with g. The . means any character, and the {5} means that there are exactly 5 (in this case of any character).
And to implement this, you would just use the method String#matches("r.{5}g").
The root problem in your code is this:
for(j=0;j<s.length();j++){
while(s.charAt(j)!='r' || s.charAt(j)!='g')
j++;
You have a loop for j where you increase J - but inside that loop you increase j again. Below that, you use j+6 in an index and you haven't checked to see if j+6 is too long. So you're repeatedly modifying j and checking 6 characters out without ever checking to see if those are in bounds.
I'd start by stopping your for loop at s.length()-6. If an r or g sequence starts in those last spots it can't complete, so no need to check them - and then your j+6 logic will work and not blow up.

Changing single chars to upper or lower case depending on user input in Java

I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
}
When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.
The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'. If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C". To print the chars in a row, you can simply append each character to a string, and then output that.
The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
if (Character.isUpperCase(letter1)) {
System.out.println(Character.toLowerCase(letter1));
} else {
System.out.println(Character.toUpperCase(letter1));
}
}
The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.
To solve your problem. just remove the for loop. 'coz you already
store each character to the three variables.
You code will look like this now:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.print("Result: " + Character.toLowerCase(letter1));
else {
System.out.print("Result: " + Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.print(Character.toLowerCase(letter2));
else {
System.out.print(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.print(Character.toLowerCase(letter3));
else {
System.out.print(Character.toUpperCase(letter3));
}
}
}
The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.
Replace your for loop with:
System.out.println(letters.toUpperCase());

Trying to write a simple compiler in java (I am using notepad++)

My question is how would I write a simple compiler ,that is like the compilers used in fax machines, that would convert something like aaaavvvvvddddddddddd to 4a5vBd.
Also, I get to "Assume" that any string entered will not contain uppercase letters and no numbers, and that any string will contain less than 61 of any type of character so, I get to assume no one will put in 64 continues a's in my program.
This is as far as I gotten
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n;
char cn;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Hello, please enter a string");
word = scan.nextln();
if(n <= 61)
{
int n = ?;
cn = numChars.charAt(n);
}
}
}
I assume I need to use a loop, but I don't know what I should use to count the repeating letters and then tell how many letters of that type are in a row. Now I am only asking for advice and not so much for code, because I want to do it but, as a beginner my Java "Vocabulary" isn't very big right now.
Any advice/ tips would be greatly appreciated.
Sincerely,
Mr.Trips
Well I am back and it appears my code here likes to only print out 147. No matter what I type in I will always get 147. I have tried to hand trace all my variables, but when I do it I get exactly what I want, and I must have some error in my logic. Any thoughts?
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int s = 0;
char a;
char b;
char c;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Please enter a string");
word = scan.nextLine();
while (n < word.length())
{
a = word.charAt(n);
b = a;
n = n ++;
a = word.charAt(n);
if (a == b)
{
s = (s + 1) ;
}
else if (a != b);
{
c = numChars.charAt(s);
System.out.print(b + c);
s = 0;
c = 0;
break;
}
}
}
}
Thank you again!
Since you don't want code this is logically how to do it. You are right you should loop through the string for each char. Store the last char in a variable and keep a counter variable. Compare current char to last char if it is equal then increment the counter. As soon as it is not equal to the last char then add counter + last char to result string and reset counter variable. Each iteration update last char variable.

Simple JAVA: Password Verifier problem

I have a simple problem that says:
A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string and print out a message as to whether or not the string entered would be considered a valid password.
I need help on completing this code. I have this pseudocode that I can't workout into Java code:
print "enter new password"
input newPassword
digitCounter =0
letterCounter = 0
for I = 0 to newPassword.length() by 1
c = newPassword.charAt(i)
if c is a digit
increment digitCounter
else if c is a letter
increment letterCounter
endif
endFor
if newPassword.length() >= 6 and digitCounter > 0 and letterCounter > 0
print "the password is valid"
else
print " password rejected, must be at least 6 characters long and be a mix of letters and digits "
endif
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
So far all I have is this for the Java code:
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String thePassword;
int len, i, letterCounter = 0, digitCounter = 0;
char c;
Len = thePassword.length();
System.out.print("Enter the password: ");
thePassword = in.nextLine();
for (i = 0,i = len, )
{
c = in.charAt(1);
if ()
}
}
}
Take a look at Character.isDigit() and Character.isLetter() for checking the characters:
If you want to use String.charAt() to get the characters of your string, you could do a for loop like so:
for (int i = 0;i < s.length();i++) {
char c = s.charAt(i);
//Check things about c
}
Although Java 1.5 instroduced a For-Each loop which will loop automatically over arrays like so:
for (char c : s.toCharArray()) {
//Check things about c
}
impot javax.swing.JOptionPane;
class PasswordDemo{
public static void main(String[] agrs){
String pass = "abcdef";
String right = "Success!";
String wrong = "Failed to login";
String input = JOptionPane.showInputDialog("Enter the password to login: ");
do{
JOptionPane.showMessageDialog(null,wrong);
input = JOptionPane.showInputDialog("Enter the password to login: ");
}while(!input.equals(pass));
//when login successfully
JOptionPane.showMessageDialog(null,right);
}
}
I'd check that the Regex \d (any digit), and the Regex [a-z] (any letter) both matches the string. And then check for length.
A couple quick tips:
your pseudo code algorithm is not correct. It will correctly validate that strings must indeed be at least 6 characters in length, but won't invalidate passwords with weird characters in them (e.g. ~%). Based on the problem statement, it seems implicit that the sentence "made up of a combination of letters and digits" means made up only of those. For this part, as others have mentionned, you can use built-in methods of the String or Character classes such as String.charAt(), Character.isDigit() and Character.isLetter().
make it a habit to declare stuff at the latest possible time (i.e just before it's used). In your example, you have String thePassword, then 2 other lines, then you assign something to thePassword. Instead, write it directly as String thePassword = in.nextLine(). This will help make the code less cluttered and easier to read. Same for your other declarations (char c, int len, etc.).
try to use the enhanced for loop if you can, in order to avoid having to figure out the length and determine where to stop (potential for errors). In your example, your loop could be something like for (char c : thePassword.toCharArray()). If you haven't talked about this loop in your class yet, you don't have to use, and you should know how the simple for loop works as well, but this is just a suggestion. In your code example, your loop does not make sense, so I'd advise you to read up on loops.
I'm going to pretend that you just read in from the command line arguments, if you need it to be able to accept multiple passwords you can generalize it. Here is how I would easily do it:
public class Password {
public static void main(String[] args) {
String thePassword = args[0];
int passLength = thePassword.length();
boolean hasLetters = false;
boolean hasDigits = false;
boolean hasSomethingElse = false;
for (int i=0; i < passLength; i++) {
char c = thePassword.charAt(i);
if(Character.isLetter(c)) hasLetters = true;
else if(Character.isDigit(c)) hasDigits = true;
else hasSomethingElse = true;
}
if (hasLetters && hasDigits && !hasSomethingElse && (passLength >= 6)) {
System.out.println("Password is correctly formatted");
} else {
System.out.println("Password is not correctly formatted");
}
}
}

Categories