Code detects string as having duplicate letters, even when it does not - java

I wrote a program to check whether a word does not have any duplicate letters. There are two problems I am having:
1 - I wrote this in object oriented code and I am having an issue calling my main method.
2- When I had the code in one method - not broken up into pieces - the Boolean was not changing base on my checkLetters method. The output was the same - no matter what the test value was.
I am a java beginner and I would appreciate any advice.
Thank you!
import java.util.Scanner;
public class uniqueLetters
{
boolean isUnique;
char temp;
int i = 0;
String str;
char[] letters;
public static void main(String[] args)
{
testWord testing = new testWord();
}
private void testWord()
{
getArray();
checkLetters();
getStatement();
}
private void getArray()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your word:");
str = keyboard.nextLine();
letters = str.toCharArray();
}
private boolean checkLetters()
{
boolean isUnique = true;
for (i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
}
}
return isUnique;
}
private void getStatement()
{
if (checkLetters())
System.out.print("This word has all unique letters");
else
System.out.print("This word has duplicate letters");
}
}

In you loop you do
for (i = 0; i < letters.length; i++)
{
for (int j = 0; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
break;
}
}
but as the second loop is also starting at 0, then it will always find a duplicate.
try
for (i = 0; i < letters.length; i++)
{
for (int j = i + 1; j < letters.length; j++)
{
if (letters[i] == letters[j])
isUnique = false;
}
}
Also, as you are calling checkLetters from getStatement then you do not need to call it from the testWord method.
Also as testWorld is a method not a class, you should not instantiate it, just call it.

Related

How can I compare these two strings and remove a common letter without using arrays?

This was the code I designed to solve this problem but it seems not to work at all.I used nested for loops to compare the letters of the first string and the second string since they are likely to have different lengths
import java.util.*;
public class Trim
{
public static String myTrim(String input, String list)
{
String r = "";
for (int i = 1; i < input.length();i++)
{
for (int k = 1; k < list.length();k++)
{
if (input.charAt(i) != list.charAt(i))
{
r += input.charAt(i);
}
}
}
return r;
}
}
I guess you should use the method String.indexOf.
So:
public static String myTrim(String input, String list)
{
StringBuilder result = new StringBuilder();
char c;
for (int i = 0; i < input.length(); i++)
{
c = input.charAt(i);
if (list.indexOf(c) < 0)
result.append(c);
}
return result.toString();
}
Try using a flag to determine whether to character gets repeated or not:
String r = "";
for (int i = input.length() - 1; 0 <= i; i --) {
if (-1 == list.indexOf(input.charAt(i))) {
r += input.charAt(i);
}
}
OR
String r = "";
boolean found;
for (int i = input.length() - 1, j = list.length() - 1; 0 <= i; i--) {
found = false;
for (int k = j; 0 <= k; k--) {
if (list.charAt(k) == input.charAt(i)) {
found = true;
break;
}
}
if (!found) {
r += input.charAt(i);
}
}
We have to filter out the characters from input which appears in list.
Now we have to check whether each character of the input appears in the list or not.
The k value will be less then list.length() if the character of input present in the list string.
After the loop we check the k value and append it to the new string.
public static String myTrim(String input, String list)
{
String r = "";
for (int i = 0; i < input.length();i++)
{
int k = 0;
for (; k < list.length();k++)
{
if (input.charAt(i) == list.charAt(k))
{
break;
}
}
if(k == list.length())
r += input.charAt(i);
}
return r;
}
A nice one-liner solution would be to use Guava Charmatcher:
CharMatcher.anyOf(list).removeFrom(input);
I have tried this code and it's working fine with both of your inputs
for (int i = 0; i < S1.length(); i++) {
for(int j=0;j< S2.length();j++) {
if(S1.charAt(i)==S2.charAt(j)) {
char Temp= S2.charAt(j);
String Temp2=String.valueOf(Temp);
S1=S1.replace(Temp2, "");
}
}
}
This is code
import java.util.Scanner;
public class StringRemoveChar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String S1, S2;
S1 = scanner.nextLine();
S2 = scanner.nextLine();
for (int i = 0; i < S1.length(); i++) {
for (int j = 0; j < S2.length(); j++) {
if (S1.charAt(i) == S2.charAt(j)) {
char Temp = S2.charAt(j);
String Temp2 = String.valueOf(Temp);
S1 = S1.replace(Temp2, "");
System.out.println(S1.length());
}
}
}
System.out.println(S1);
}
}
Input:
Miyazaki
you
Output:
Miazaki
We can use replaceAll and use one loop over ,this will make the solution simple
public static String myTrim(String input, String list)
{
for(int i=0;i<list.length();i++)
{
input=input.replaceAll(list.charAt(i)+"","");
}
return input;
}
Input: myTrim("Miyazaki","you")
Output: Miazaki
Full code for reference
package stackoverflow.string;
public class StringManipulation
{
public static void main(String[] args)
{
System.out.println(myTrim("University of Miami","city"));
}
public static String myTrim(String input, String list)
{
for(int i=0;i<list.length();i++)
{
input=input.replaceAll(list.charAt(i)+"","");
}
return input;
}
}

Palindrome program debugging

The problem is fixed but I need help with creating a method for one of the pieces of code. Any inputs will be appreciated. I tried using void methods but it didn't work. I have highlighted where i want the code to be a method.
import java.util.*;
public class Finalpal {
public Finalpal() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String word;
int len, counter = 0;
System.out.println("Enter your word");
word = scan.next();
word = word.toUpperCase();
len = word.length();
char array[] = new char[len];
char reverse[] = new char[len];
for (int i=0; i < len; i++)
{
array[i] = word.charAt(i);
}
for (int j=len-1; j>=0; j--)
{
array[counter] = word.charAt(j);
counter++;
}
// This part needs to be a method
for (int k = 0; k < len; k++)
{
if (array[k] != reverse[k])
{
System.out.println("Not a palindrome");
break;
}
if ((array[k] == reverse[k]) && (k == len -1))
{
System.out.println("It is a palindrome");
}
}
}
}
You are not filling in the reverse array
try
for (int j=len-1; j>=0; j--)
{
reverse[counter] = word.charAt(j);
counter++;
}
You have used array[counter] instead of reverse[counter]. You have never filled reverse array
There is a way of doing this without creating a reversed string to compare to the original...
If I knew the length of the string, I could make a loop that checked the characters on either end to see if they were the same and move inward:
[a] [b] [c] [b] [a]
Loop 0: a = a
Loop 1: b = b
Loop 2: c = c
Result: Palindrome!
Functions you need:
int len = String.length();
char c = String.charAt(int);

Going back and forth with methods in Java

I built a tic tac toe game using java but I just have one issue. I want my code to bounce back and forth from the validPlayerOneInput and validPlayerTwoInput methods. As you can see in my main, I'm calling both methods procedurally which be incorrect as it just stops after the method is called. I want this to keep running until a winner is determined.
How do I do so?
import java.util.*;
public class tictactoe {
private static char board[][] = {{1,2,3}, {4,5,6}, {7,8,9}};
char p1Sym, p2Sym;
public tictactoe() {
p1Sym ='X';
p2Sym = 'O';
boardFill();
}
void boardFill() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j]);
System.out.print(" | ");
}
System.out.println();
}
}
void validInputPlayerOne() {
boolean isSet = true;
int player1Input, player1CorrectedInput;
System.out.println("Player 1, enter a number between 1-9: ");
Scanner player1 = new Scanner(System.in);
player1Input = player1.nextInt();
Scanner correctedInput = new Scanner(System.in);
while(player1Input < 1 || player1Input >= 10) {
System.out.println("This isn't a number between 1-9, try again: ");
player1CorrectedInput = correctedInput.nextInt();
player1Input = player1CorrectedInput;
}
// or
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == player1Input) {
// set new value
board[i][j] = p1Sym;
// set
isSet = true;
}
}
}
if (!isSet) {
System.out.println("not found");
}
}
void validInputPlayerTwo() {
boolean isSet = true;
int player2Input, player2CorrectedInput;
System.out.println("Player 2, enter a number between 1-9: ");
Scanner player2 = new Scanner(System.in);
player2Input = player2.nextInt();
Scanner correctedInput = new Scanner(System.in);
while(player2Input < 1 || player2Input >= 10) {
System.out.println("This isn't a number between 1-9, try again: ");
player2CorrectedInput = correctedInput.nextInt();
player2Input = player2CorrectedInput;
}
// or
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == player2Input){
board[i][j] = p2Sym;
isSet = true;
}
}
}
if (!isSet) {
System.out.println("not found");
}
}
public static void main(String[] args) {
tictactoe t = new tictactoe();
t.validInputPlayerOne();
t.boardFill();
t.validInputPlayerTwo();
t.boardFill();
}
}
You could do something like:
int turn = 0;
while (t.noWinner()) {
if (turn % 2 == 0) t.validInputPlayerOne();
else t.validInputPlayerTwo();
t.boardFill();
turn += 1;
}
Of course, now you have to actually write the noWinner function.
Answering your question directly, you could have a boolean that toggles on each move:
boolean firstPlayer = true;
while (t.gameIsNotFinished()) {
if (firstPlayer)
t.validInputPlayerOne();
else
t.validInputPlayerTwo();
firstPlayer = !firstPlayer;
}
However you have a lot of other issues with your code that you need to address. For example if a player enters an invalid value then it goes to the next player rather than asking for them to reenter the value.
You should also try to have a single validInputPlayer method that works for both players with the firstPlayer variable passed in. At the moment you have a lot of repeated code in those methods.

Java String Out of Bounds Exception

import java.util.*;
import java.lang.*;
public class pro19
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String word;
System.out.print("Enter word: ");
word = in.nextLine();
StringBuffer s = new StringBuffer(word);
int l = word.length();
for(int i = 1; i<=l; i++)
{
for(int j = i+1; j<=l; j++)
{
if(s.charAt(i)==s.charAt(j))
{
s = s.deleteCharAt(j);
l--;
}
else
continue;
}
}
System.out.println("Word after deletion of duplicate letters: "+s);
}
}
I wrote this program to delete duplicate characters as school homework.
But whenever I run it I get the following output(exercise being the input):
Enter word: exercise
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8
at java.lang.StringBuffer.charAt(Unknown Source)
at pro19.main(pro19.java:19)
Please help and tell me where I am going wrong.
You Write
for(int i = 1; i<=l; i++)
You can Write like This
for(int i = 0; i<=l-1; i++)
{
for(int j = i+1; j<=l-1; j++)
{
if(s.charAt(i)==s.charAt(j))
{
s = s.deleteCharAt(j);
l--;
}
else
continue;
}
Correct your loop conditions :
for(int i = 1; i < l; i++)
{
for(int j = i+1; j < l; j++)
{
What about word.replaceAll("(.)\\1+", "$1") ?

How come this doesn't work [trying to print out a new sentence with all the constants]

import javax.swing.JOptionPane;
public class Indexof {
public static void main(String[] args) {
String newSentance = "";
String sentance = JOptionPane.showInputDialog("Enter sentance");
String vowels = "AEIOU";
int len = sentance.length();
for (int i = 0; i >=len; i++)
{
if(vowels.indexOf(sentance.toUpperCase().charAt(i))>0)
{
newSentance+=sentance.charAt(i);
}
}
System.out.println(newSentance);
}
}
I am getting no errors in NetBeans yet it still returns nothing when printing newSentance
the .length is definitely working as it returns the number correctly if printed
what else could it be?
Modifying the code with
int i = 0; i < len; i++
and
vowels.indexOf(sentance.toUpperCase().charAt(i)) < 0
results in only the constants getting printed.
This code::
for (int i = 0; i >= len; i++) {
if (vowels.indexOf(sentance.toUpperCase().charAt(i)) > 0) {
newSentance += sentance.charAt(i);
}
}
should be something like:
for (int i = 0; i < len; i++) {
if (vowels.indexOf(sentance.toUpperCase().charAt(i)) >= 0) {
newSentance += sentance.charAt(i);
}
}

Categories

Resources