I am working on a pig latin translator which translator the given word into pig latin. Here is the pig latin method and the isVowel method.
public static void pigLatin(String s) {
char[] array = s.trim().toCharArray();
if(isVowel(s.charAt(0)) && !Character.toString(s.charAt(0)).equalsIgnoreCase("y")){
System.out.println(s+"way");
}else {
int i = 0;
String toReturn = "";
do {
toReturn += array[i];
i++;
}while(!isVowel(s.charAt(i)) && !Character.toString(array[i]).equalsIgnoreCase("y"));
System.out.println(s.substring(i)+toReturn+"ay");
}
}
public static boolean isVowel(char c) {
char[] vowels = new char[] {'a','e','i','o','u','y'};
for(int i = 0;i<vowels.length;i++) {
if(Character.toString(vowels[i]).equalsIgnoreCase(Character.toString(c))) {
return true;
}
}
return false;
}
The problem is when I input words "BIrD" and "quiet". First one throws java.lang.StringIndexOutOfBoundsException: String index out of range: 4
The second one doesn't convert properly. Quiet prints uietqay, when it supposes to be ietquay, but that doesn't make sense because, you supposed to take all constants upto the vowel, which should mean uietquay so why is it ietquay? Can someone please point me in the correct direction?
NOTE: This is not homework.
Ignoring case, Is that a "BLRD" or a "bird"? Because if it has no vowels, your do-while loop doesn't terminate except by going out of bounds.
Your second case, "quiet" should be "uietqay" unless you want to add special logic to keep "qu" together. You could accomplish this in your while condition by making it uglier:
while( (!isVowel(s.charAt(i)) || isQU(s, i)) && !Character.toString(array[i]).equalsIgnoreCase("y"))
And then implement the appropriate isQU(String s, int index).
But I'd suggest that a little more rewriting is in order to make your code more readable. As is, I'm not quite sure why your isVowel checks for "y" and your while condition also checks for "y". Some of the time you use array[i] and some of the time you use charAt(i). This inconsistency makes your code harder to read with little or no benefit.
public static String pigLatin(String a){
a=a.toLowerCase();
String [] x=a.split(" ");
int vowl=0;
String c="";
String d="";
String trans="";
for(int i=0; i<x.length; i++){
for(int j = 0;j<x[i].length();j++){
if(x[i].charAt(j)=='a'||x[i].charAt(j)=='e'||x[i].charAt(j)=='i'||x[i].charAt(j)=='o'||x[i].charAt(j)=='u'){
vowl=j;
j=x[i].length();
}
}
c=x[i].substring(0,vowl);
d=x[i].substring(vowl,x[i].length());
trans+= d+c+"ay ";
}
return trans;
}
Related
I've been given the task to create a method that takes in a single char and does an equality check to see if it matches any char in an array.
For the number of times that a match is found, a counter is supposed to go up. I'm pretty sure that the syntax on the for loop is correct, but I have no idea how to run the equality check.
if(tiles.toCharArray()==letter) is my current attempt. Any thoughts on how I could switch out or change this line of code to get the equality test to work?
public class ScrabblePlayer {
private String tiles;
int count;
// A String representing all of the tiles that this player has
public char ScrabblePlayer() {
tiles = "";
}
public int getCountOfLetter(char letter) {
count = 0;
for(char character : tiles.toCharArray()) {
if(tiles.toCharArray() == letter);
count += 1;
}
return count;
}
In your getCountOfLetter method code you have two problems:
The useless semicolon ; in the end of the if condition line.
And you are using the wrong variable in the if condition, tiles.toCharArray() should be replaced with character, as you are looping over it.
This is how should be your code:
public int getCountOfLetter(char letter) {
count = 0;
for(char character : tiles.toCharArray()) {
if(character == letter)
count ++;
}
return count;
}
It should be this:-
if(character == letter) {
count += 1;
}
On a side note, I think public char ScrabblePlayer() should maybe be public ScrabblePlayer() if it's supposed to be the constructor.
I am not very good at java so that's why some things might not make sense at all. I was just simply using code from bits I found online which I know is wrong.
My current issue is that it simply prints a blank code; I am not sure how to get it to print it like so:
Input:
APPLE
Output:
A
AP
APP
APPL
APPLE
Current Code:
import java.util.Scanner;
public class WordGrow
{
public static void main(String[]args)
{
//take your word input
//enter word as a parameter in WordGrow()
System.out.println("Please enter the word to *GROW*");
Scanner scan = new Scanner(System.in);
String theword = scan.next();
System.out.println(makeTree(theword, theword.length()));
}
public static String makeTree(String word, int len)
{
int count = 0;
//start with the first letter and print
//and add another letter each time the loop runs
if (word.length() > 0)
{
for(int i = 0; i < word.length();i++)
{
return word.substring(0, i++);
}
}
return (word.charAt(1) + makeTree(word, len));
}
}
Take Java out of it. Let's take this back to pen and paper.
First, look at the pattern you're printing out. How would you print out just one letter of that string? How would you print out two?
Let's start with that approach. Let's try to print out one letter in that string.
public void printStringChain(String word) {
System.out.println(word.substring(0, 1));
}
What about two letters?
public void printStringChain(String word) {
System.out.println(word.substring(0, 2));
}
What about word.length() letters?
public void printStringChain(String word) {
System.out.println(word.substring(0, word.length()));
}
The main thing I'm trying to get you to see is that there's a pattern here. In order to accomplish this, you likely need to go from zero to the length of your string in order to print out each line on its own.
Here's a start. I leave figuring out the nuance and barriers inside of the substring as an exercise for the reader.
public void printStringChain(String word) {
for (int i = 0; i < word.length(); i++) {
// the question mark relates to i, but in what way?
System.out.println(word.substring(0, (?)));
}
}
If recursion is not compulsory, you could simply iterate through the given String:
String str = "APPLE";
for(int x=0; x<str.length(); x++){
System.out.println(str.substring(0, x+1));
}
Output:
A
AP
APP
APPL
APPLE
One cannot return multiple times, at the first moment the result is passed on to the caller.
For String there is a buffering class for efficiency, the StringBuilder.
Including the empty string that would be:
public static String makeTree(String word) {
StringBuiilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++){
sb.append(word.substring(0, i));
sb.append("\r\n");
}
return sb.toString();
}
It uses the Windows end-of-line characters CR+LF aka \r\n.
You can make that platform independent, but you get the idea.
WITH RECURSION
public static String makeTree(String word)
{
if (word.length() <= 1){
return word;
}
return makeTree(word.subSequence(0, word.length()-1).toString()) + System.lineSeparator() + word;
}
Here is my class for finding the amount of spaces, amount of vowels and amount of consonants in a sentence. It works fine but i need it to ignore the cases. How do i do this? I am familiar with the "ignore case" code but im not sure where to put it in this particular program.
public class Counting{
private String sentence;
private int spaces;
private int vowels;
private int consonants;
public Counting(){
sentence = new String();
spaces = 0;
vowels = 0;
consonants = 0;
}
public void setSentence(String sentence){
this.sentence = sentence;
}
public void compute(){
for(int i =0; i < sentence.length();i++){
char letter = sentence.charAt(i);
if(sentence.charAt(i)==' ' ){
spaces++;
}
else if((letter=='a')||(letter=='e')
||(letter=='i')||(letter=='o')||(letter=='u'))
vowels++;
else{
consonants++;
}
}
}
public int getSpaces(){
return spaces;
}
public int getVowels(){
return vowels;
}
public int getConsonants(){
return consonants;
}
}
A common way to do this is to simply convert the original string to all lower case.
Convert the string passed to your class to lower case:
public Counting(){
setSentence("");
spaces = 0;
vowels = 0;
consonants = 0;
}
public void setSentence(String sentence){
this.sentence = sentence.toLowerCase();
}
Use
letter.equalsIgnoreCase("a")
for checks the letter is A or a
It would probably be easier to just maintain a set of all vowels, and consonants and include upper and lower cases - your code as is will include numbers and punctuation as consonants
if (consonents.contains(c)) consonents++;
else if (vowels.contains(c)) vowels++;
else if (spaces.contains(c)) spaces++
alternatively you could keep a map of char and property (an enum starting at 0 and incremented by 1 and including misc as a catch all) and then just keep an array of property counts:
counts[property.get(c)]++;
Put it in your compute() method. This is not very efficient, but it's the simplest thing to do.
public void compute() {
String lowerCaseSentence = sentence.toLowerCase();
//...
}
And replace sentence with lowerCaseSentence in the rest of the code in compute()
Yes, The best way is to convert the whole input sentence into upper case or Lower case and carry out the required operations on it
Try it:
sentence.toLowerCase();
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;
}
I have a string similar to this ,,,foo,bar and I need to count the amount of "," at the beginning of the string in java any ideas?
Have a counter variable which counts the number of occurrences. Then loop through the entire String, using charAt(i) to get the char at position i. Test to see if it's equal to charAt(0). If it is, increment counter and if it isn't, break out of the loop.
Take a look at the String javadoc. It contains methods you can use to get the length of the String and get characters at certain positions.
If starting characters are known then build a regex pattern and get the first group. First group string will contain the exact match of desired sequence, length of this string is the resultant count.
You can also use regexp:
public static int countCommasAtBegin(String str) {
Matcher commas = Pattern.compile("^,*").matcher(str);
if (commas.find()) {
return commas.group().length();
} else {
return 0;
}
}
but for such trivial task I prefer to use simple loop.
A simple loop (while or for) containing a if with a condition of equality that increments a counter if true should be enough.
This quick-n-dirty solution worked for me.
public static void main(String[] args)
{
String s = ",,,foo,bar";
int count = 0;
for (int i = 0; i < s.length() ; i++) {
if (s.charAt(i) != ',')
break;
count++;
}
System.out.println("count " + count);
}
Update: just realized that you only need to count the ',' at the beginning of the string and not the middle. I've updated the code to do that.
If you don't want to use any any external jars just write a simple function:
public static int countAtBegin(String str, char c) {
for (int ret = 0; ret < str.length(); ret++) {
if (str.charAt(ret) != c)
return ret;
}
return str.length();
}