Get the first instance of a letter from the string - java

I am working on this very simple method I know I am very close to finish it, but I am missing a detail. I appreciate any help. Thank you.
/**
Gets the first letter in this string.
#return the FIRST LETTER, or "" if there are no letters.
add1=AD3F add2=EF4G result=32SFB (BUT THESE ARE RANDOM ONLY INTS AND CHARS)
*/
public String firstLetter()
{
String line = add1+add2+result;
for(int i=0; i<line.length(); i++){
char ch=new Character(line.charAt(i));
if(Character.isLetter(ch)){
System.out.println("This is the first letter"+ch);
return ch;
}
else
System.out.println("No it is not a character: "+ch);
return "";
}

Your return type is String, but you're only trying to return a single character. Why not make it return a char, with \0 as the "no characters" return value - or possibly throwing an exception...
You also need to think about the ends of blocks - your if statement, your else clause, the loop, and the method itself. I would strongly recommend:
Using braces for all cases, even when there's only a single statement in the block (as per the else clause
Paying attention to indentation. It makes all the difference in clarity for this sort of thing.

You need to move the else code outside the loop so that it is only executed when you have tested all of the characters:
public class FirstLetter
{
public static void main(String[] args)
{
System.out.println(firstLetter());
}
public static String firstLetter()
{
String line = "AD3F" + "EF4G" + "32SFB";
for (int i = 0; i < line.length(); i++)
{
char ch = line.charAt(i);
if (Character.isLetter(ch))
{
System.out.println("This is the first letter: " + ch);
return Character.toString(ch);
}
}
System.out.println("No character found");
return "";
}
}
This kind of problem is more obvious when you format the code clearly.
I have kept the return type as String as per your original, but see also Jon Skeet's comments about changing that to char.

Your logic should look like this:
char ch;
for (int i = 0; i < line.length(); i++) {
ch = new Character(line.charAt(i));
if (Character.isLetter(ch)) {
System.out.println("This is the first letter" + ch);
return String.valueOf(ch);
}
}
System.out.println("No letters, sorry.")
return "";
As soon as a letter is found, it is reported and returned. But if the end of the end of the line is reached (i.e. the for loop completes), then obviously no letter was found, so report that and return an empty string.

Related

What is the best way to replace a letter with the letter following it in the alphabet in Java?

I'm a programming newbie and I am doing a coderbyte exercise that says "
Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a)"
i'm thinking of the following methods:
declare a string called "abcdefghijklmnopqrstuvxyz" and compare each string's char index position with the alphabet's index position, and then just bring the alphabet char that is located at the i+1 index location. But I don't know how it would work from z to a.
I've seen some techniques using ASCII values for every char but I've never done that before and not sure how it works
convert the given string into a char[] array, but then I'm not sure how I would tell the system to get me the next alphabet char
What would be the easiest way to do this?
EDIT
this is my code so far, but it doesn't work.
import java.util.*;
import java.io.*;
class Main {
public static String LetterChanges(String str) {
// code goes here
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String newWord = "";
for (int i = 0; i < str.length(); i++){
for (int j = 0; j < alphabet.length(); i++){
if (str[i] == alphabet[i]){
if (alphabet[i+1].isVowel()){
newWord = newWord + toUpperCase(alphabet[i+1]);
}
else{
newWord = newWord + alphabet[i+1];
}
}
}
}
return str;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterChanges(s.nextLine()));
}
}
Can't I ask for the index position of a Char that is a part of a String? in C I could do that.
Other than that not sure why it doesn't work.
I would definitely go with method 1.
I believe what you're looking for is the indexOf method on a String.
First of, I would create a method that given a character finds the next letter in the alphabet and return that. This could be done by finding the letter in your alphabet string and then fetch the letter at index+1. As you also pointed out you would need to take care of the edge case to turn 'z' into 'a', could by done with an if-statement or by having an extra letter 'a' at the end of your alphabet string.
Now all that remains to do is create a loop that runs over all characters in the message and calls the previously made method on that character and constuct a new string with the output.
Hope this helps you figure out a solution.
Assuming that there would be only lower case English letters in the given String the most performant way would be to add +1 to every character, and use either if-statement checking whethe the initial character was z or use the modulo operator % as #sp00m has pointed out in the comment.
Performing a search in the alphabetic string (option 1 in your list) is redundant, as well extracting array char[] from the given string (option 3).
Checking the edge case:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = str.charAt(i);
if (next == 'z') result.append('a'); // checking the edge case
else result.append((char) (next + 1));
}
return result.toString();
}
Applying modulo operator:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = (char) ((str.charAt(i) - 'a' + 1) % 26 + 'a');
result.append(next);
}
return result.toString();
}
main()
public static void main(String[] args) {
System.out.println(shiftLetters("abc"));
System.out.println(shiftLetters("wxyz"));
}
Output:
bcd // "abc"
xyza // "wxyz"

error on using uppercase in palindrome prog in java

package Assignments;
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int i=0,j=str.length()-1,count=0;
while(i!=j) {
if(str.charAt(i)!=str.charAt(j)) {
count++;
break;
}
i++;
j--;
}
if(count!=0) {
System.out.println("Not a Palindrome");
}
else {
System.out.println("Palindrome");
}
}
}
Upon entering Uppercase letter in input it is showing error. "assa" as input is working fine but "Assa" is showing error.
I know it is a minor fault somewhere but I am new to java. Can anyone help?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at Assignments.Assignment1.main(Assignment1.java:12)
a and A are not the same character. If you don't care about the case, you could convert all the character to lowercase (or to upper case) explicitly when comparing them:
while (i != j) {
if (Character.toLowerCase(str.charAt(i)) != Character.toLowerCase(str.charAt(j))) {
count++;
break;
}
i++;
j--;
}
EDIT:
The updated exception in the question clarifies the problem - it is unrelated to upper/lower case discrepancies, but to a wrong handling of strings with an even number of characters. To handle this you could use the < operator instead of !=:
while (i < j) {
A and a are not the same character, so it is normal that the string doesn't match.
What you could do is, before processing the string to see if it's a palindrome, you convert it to lowercase:
str = str.toLowerCase();
Replace
if(str.charAt(i)!=str.charAt(j))
with
if(Character.toUpperCase(str.charAt(i))!=Character.toUpperCase(str.charAt(j)))
Alternatively,
Replace
if(str.charAt(i)!=str.charAt(j))
with
if(Character.toLowerCase(str.charAt(i))!=Character.toLowerCase(str.charAt(j)))
The key is to compare the characters in the same case.
Apart from this, you also need to
replace
while(i!=j)
with
while(i < j)
in order to avoid StringIndexOutOfBoundsException.

Java exception error for Disemvowel [duplicate]

I have a bug in this block of code. The debugger suggest it´s cause is this line of code char chr = getSecretWord.charAt(i);
What this code does is look for a match between userInput and secretWord. I have the for loop to go through the length of the secretWord letters one by one, and if there is a letter matching return true. If not, return false... but the program crashes when it is suppose to just return false... I guess it is something with this line, but do not know exactly what getSecretWord.charAt(i);
private boolean isMatchingSecretWord(String userInput)
{
String secretWord = "";
String getSecretWord = getSecretWord();
for (int i = 0; i <= getSecretWord.length();i++)
{
char chr = getSecretWord.charAt(i);
secretWord = ""+chr;
if (secretWord.equals(userInput))
{
println("is true");
return true;
}
}
return false;
}
As an side note, is what I´ve done with this code correct, assigning the getSecretWorld() Method to a String so I can use the Strings method length()?
String getSecretWord = getSecretWord();
for (int i = 0; i <= getSecretWord.length();i++)
Debug code:
Exception in thread "Thread-4" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at Hangman.isMatchingSecretWord(Hangman.java:49)
at Hangman.userInput(Hangman.java:34)
at Hangman.run(Hangman.java:20)*
for (int i = 0; i <= getSecretWord.length(); i++)
should be:
for (int i = 0; i < getSecretWord.length(); i++)
// ^^^
// see here
The valid indexes for an n-character string (or an n-element array) are 0 through n-1 inclusive.
So, if your secret word is xyyzy, the valid indexes are zero through four. Your original loop iterates with i set to zero through five, hence the problem.
But there seems to be a lot of unnecessary code in there, when you could get away with something simple.
First, I would remove a source of confusion - the function name sounds like the user input and the secret word have to match completely whereas your comment indicates otherwise:
Thanks, this works. But the reason for the loops is that the user enters one letter, I want to see if that letter is within the SecretWord. (it´s a hangman game).
In that case, you simply want to see if the single character exists in the secret word. I would change the function name to suit and, even then, it can be done with a lot less code:
private boolean isInSecretWord (String userInput) {
String secretWord = getSecretWord();
return secretWord.contains(userInput);
}
You were getting out of bounds error as your for loop wasn't looping correctly, I have modified it so that the loop doesn't go out of bounds and also your secretWord variable wasn't populating correctly, the code should now work as intended :)
private boolean isMatchingSecretWord(String userInput)
{
String secretWord = "";
String getSecretWord = getSecretWord();
for (int i = 0; i < getSecretWord.length();i++)
{
char chr = getSecretWord.charAt(i);
secretWord = secretWord + chr;
if (secretWord.equals(userInput))
{
println("is true");
return true;
}
}
return false;
}

Comparing a string array index to a string

I'm having trouble comparing an array that holds a word that's broken up into letters. Here is my code: (it's part of a hangman game)
public static void isGuessCorrect( String guess, String wordInPlay, String[] hangmanScores){
String[] letterGuessedAgainst = wordInPlay.split("");
for (int i = 0;i < letterGuessedAgainst.length; i ++)
System.out.print(letterGuessedAgainst[i]);
System.out.println("Letter guessed against is: "+letterGuessedAgainst[1]);//testing purposes
System.out.println("My guess is: "+guess.charAt(0));//testing purposes
for (int i = 0;i < letterGuessedAgainst.length; i++){
if (letterGuessedAgainst.equals(guess.charAt(0))){//this line isn't working
System.out.println("they're equal");//want it to return this
}//end if
else
System.out.println("they're not");//returns this instead
}//end for
}//end method
guess is a String
holds a letter
wordInPlay is the word that is in play
letterGuessedAgainst is the letter of the word that is being played
hangmanScores is an array that only holds "_", corresponding to the number of letters in the word
Any help would be immensely appreciated! Thanks!
The problem is that letterGuessedAgainst is an array and you are trying to compare a String[] vs char
if (letterGuessedAgainst.equals(guess.charAt(0))){//this line isn't working
First of all, you have to use the index i in the loop
letterGuessedAgainst[i]
Secondly, you need to compare against guess and not guess.charAt(0) since you will not be able to do equals() when comparing String and char
Since you already defined that guess is a String the contains only 1 character then you could do:
if (letterGuessedAgainst[i].equals(guess)) {
Updated your code to start working:
public static void isGuessCorrect(String guess, String wordInPlay, String[] hangmanScores) {
char[] letterGuessedAgainst = wordInPlay.toCharArray(); //Changed to Char Array
for (int i = 0; i < letterGuessedAgainst.length; i++) {
System.out.print(letterGuessedAgainst[i]);
}
System.out.println("Letter guessed against is: " + letterGuessedAgainst[1]);//testing purposes
System.out.println("My guess is: " + guess.charAt(0));//testing purposes
for (int i = 0; i < letterGuessedAgainst.length; i++) {
if (letterGuessedAgainst[i] == guess.charAt(0)) {//Made == since they are all Chars now
//System.out.println("Nice guess! Here are all the "+guess+"'s in the word.");
//System.out.println(hangmanScores);
System.out.println("they're equal");//want it to return this
}//end if
else {
System.out.println("they're not");//returns this instead
}
}//end for
}//end method
There is likely other places that can be improved but this fixes your direct problem.
Rather then splitting into a number of single character String(s), I suggest you use wordInPlay.toCharArray(); then you could iterate that char[] with a For-Each loop (and I believe you wanted to either search the entire String and say the character was found or not; not whether each individual character matches) and your code might look something like
public static void isGuessCorrect(String guess, String wordInPlay,
String[] hangmanScores) {
char[] letterGuessedAgainst = wordInPlay.toCharArray();
char ch = guess.charAt(0);
System.out.println("My guess is: " + ch);
boolean found = false;
for (char letter : letterGuessedAgainst) {
if (letter == ch) {
found = true;
break;
}
}
if (found) {
System.out.printf("%s contains guess %c%n", wordInPlay, ch);
} else {
System.out.printf("%s does not contain guess %c%n", wordInPlay, ch);
}
}
You're comparing a char (which charAt() returns) to a string, which they are not equal. I would suggest using either character arrays, or also using charAt() on letterGuessedAgainst.
Source:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
if (guess.length==0) return null; // some kind of error handling
char quessedChar = guess.charAt(0);
for (int i = 0;i < letterGuessedAgainst.length; i++){
if (letterGuessedAgainst.charAt(i) == quessedChar ){
//System.out.println("Nice guess! Here are all the "+guess+"'s in the word.");
//System.out.println(hangmanScores);
System.out.println("they're equal");//want it to return this
}//end if
else
System.out.println("they're not");//returns this instead
}//end for
I would suggest at first place some code to validate your input data. You will fail if you will pass an empty string for guess.
Secondly you are comparing String with a character. Use above code.
Wouldn't you need to do
if (letterGuessedAgainst[i].charAt(0).equals(guess.charAt(0))){
instead of comparing an array to a char

Java Compare single char to char array

I need to compare single char to char array and see if array has that char.
My current code looks like this:
public boolean isThereChar(char[] chaArray, String chr){
boolean bool = false;
for(int i=0; i < chaArray.length; i++)
{
if(chr.equals(chaArray[i])){
bool = true;
}
}
return bool;
}
Edit Notes:
Really sorry for being confusing! I am just a Java Beginner =/
Basically I am writing small Hangman game with GUI.
My program reads off text file and randomly chooses word which player has to guess, then prints it out in hidden manner like this: _ _ _ _ _
In this case I want player to input character or string (person can guess either whole word or just one letter)
Then I want my program to take that letter or string and compare to my hidden word
Following code chooses word and hides it:
public String pickWord(){
String guessWord = (wordsList[new Random().nextInt(wordsList.length)]);
return guessWord.toLowerCase();
}
//Hides picked word
public char[] setWord(){
char[] word = new char[pickWord().length() * 2];
for (int i = 0; i < word.length; i+=2) {
word[i] = '_';
word[i + 1] = ' ';
}
return word;
}
Then person input his character which he guesses to program with following code:
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action == "Guess Letter"){
inputChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
if (inputChar.length() > 1){
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInString(inputChar);
//For testing purposes
System.out.println("This is String: " +glr.getInString());
}else{
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInChar(inputChar);
//For testing purposes
System.out.println("This is Char: " +glr.getInChar());
}
}
Lastly I want to take that character which was inputted and compare to my array of chars which is my hidden word:
public boolean isThereChar(char[] array, String str){
return isThereChar(array, str.charAt(0));
}
public boolean isThereChar(char[] array, char c){
for(int i=0; i<array.length; i++){
if (array[i] == c) return true;
}
return false;
}
I want to check what does my code returns (true or false), but I keep failing at doing so.
(Right now I am trying to call method in my main class to check it, if you can give me tips how to do it otherwise please let me know.)
I would use: Chars.contains(array, chr); with Guava Chars
The NullPointerException is happening because either chaArray or chr is null when you call the method. (And if not, then the NullPointerException is occurring somewhere else!!)
The other problem with your code is this line:
if (chr.equals(chaArray[i])) {
Since chr is actually a String, what is going to happen here is that the value of chaArray[i] will be auto-boxed as a Character object, and then passed as an argument to String.equals(Object). But the String.equals(Object) will return false unless its argument is a String ... so your code wouldn't find the character anyway.
You need to either compare the character like this:
if (chr.charAt(0) == chaArray[i]) {
or declare chr to be a char and compare it as:
if (chr == chaArray[i]) {
Let's see if I got what you need :
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action == "Guess Letter"){
inputChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
if (inputChar.length() > 1){ //User input is a string here, right?
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInString(inputChar);
System.out.println(wordToGuess.contains(glr.getInString())); //This will print true if wordToGuess is equal to glr.getInString() or if it just contains it
//For testing purposes
System.out.println("This is String: " +glr.getInString());
}else{ //Here the user gave us just a character, so we've got to know if this character is contained in the word, right?
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInChar(inputChar);
System.out.println(wordToGuess.contains(glr.getInChar()); //This will print true if your char is in the wordToGuess string
//For testing purposes
System.out.println("This is Char: " +glr.getInChar());
}
}
}
Select the character from the parameter passed in, or pass in a char e.g.
chr[0]
or
public String isThereChar(char[] chaArray, char chr){
for(int i=0; i < chaArray.length; i++)
{
if(chr.equals(chaArray[i])){
return chr;
}
}
return "Guess Again";
}
String chr might be null causing NullPointerException.
Use char chr instead of String.
public boolean isThereChar(char[] chaArray, char chr){
boolean bool = false;
for(int i=0; i < chaArray.length; i++) {
if(chr==chaArray[i])){
bool = true;
}
}
return bool;
}
public boolean isThereChar(char[] chaArray, char chr){
for(int i=0; i < chaArray.length; i++)
{
if((chaArray[i]==chr)){
return true; // means Character exist in the Character array
}
}
return false; //// means Character does not exist in the Character array
}

Categories

Resources