My ArrayList (s) are just printing numbers - java

I'm trying to write a bit of code that takes a string and translates it like this;
1. Take the first letter and put it at the end of the word for every word
2. Find the first vowel and put a 'b' and then the vowel again
3. Do the same as #2 except for the last vowel
I think I have it sort of close but my output is all numbers. It doesn't even look like the address of where it's stored.
I hope this helps other people for the reason that they might be having the same problem with printing array lists in a return statement.
By the way, It's a huge code block...Sorry. The only reason I did that is so I didn't have to put both classes in here.
Here's the code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Experiment {
public static void main(String[] args){
String pre = "For every minute you are angry you loose sixty seconds of happiness.";
System.out.println(translate(pre));
}
public static String translate(String sentence){
String[] sentenceArray = sentence.split(" ");
List<String> sentenceList = new ArrayList<>();
List<String> finalList = new ArrayList<>();
String punctuation = getPunctuation(sentenceArray[sentenceArray.length - 1]);
//add all words but the last so i can take punctuation off it
for (int i = 0; i < sentenceArray.length - 1; i ++){
sentenceList.add(sentenceArray[i]);
}
//take the first letter off each word and put at at the end of each word
Arrays.asList(sentenceArray);
for (String el : sentenceArray)
sentenceList.add(firstToLast(el));
//use the addFrontB method on each word
Arrays.asList(sentenceList);
for (String la : sentenceList){
finalList.add(addFrontB(la));
}
//use the addBackB method on each word
Arrays.asList(sentenceList);
for (String le : sentenceList){
finalList.add(addBackB(le));
}
return finalList + punctuation + "\n";
}
//finds the last character of the last word which is punctuation
public static String getPunctuation(String word){
return word.charAt(word.length() - 1) + "";
}
//takes the punctuation off
public static String removePunctuation(String word){
String newWord;
newWord = word.substring(word.length(), word.length());
return newWord;
}
//puts the first letter at the end of the word
public static String firstToLast(String word){
char letter = word.charAt(0);
String newWord = word.substring(1,word.length()) + letter;
return newWord;
}
//insterts a b and then the same vowel behind the first vowel
public static String addFrontB(String word){
StringBuilder finishedWord = new StringBuilder();
for (int i = 0; i < word.length(); i ++){
if (word.charAt(i) == 'a')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
else if (word.charAt(i) == 'e')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
else if (word.charAt(i) == 'i')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
else if (word.charAt(i) == 'o')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
else if (word.charAt(i) == 'u')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
}
String newWord = finishedWord.toString();
return newWord;
}
//does the same as addFirstB but at the end of the word
public static String addBackB(String word){
StringBuilder finishedWord = new StringBuilder();
finishedWord.append(word);
finishedWord.reverse();
for (int i = 0; i < word.length(); i ++){
if (finishedWord.charAt(i) == 'a')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
else if (finishedWord.charAt(i) == 'e')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
else if (finishedWord.charAt(i) == 'i')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
else if (finishedWord.charAt(i) == 'o')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
else if (finishedWord.charAt(i) == 'u')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
}
return finishedWord.toString();
}
}

Your mistake is here:
return finalList + punctuation + "\n";
Since you add "\n" with the plus operator, java calls the toString() method of your list, which returns nonsense. You have to iterate through the list and build your own string, best practice is to use StringBuffers.

return finalList + punctuation + "\n";
You are treating the List as if it were a string here.. Do you need to do .toString() or something similar?
asList(T... a)
Returns a fixed-size list backed by the specified array.
You are not using the return value either, of Arrays.asList

Related

Having dashes change into guessed letters

my program currently takes a random word and turns into dashes based on how many letters are in the word. I then determine if a letter guessed is in the word, but I was unable to figure out how to have the correctly guessed letter replace the dashes accordingly. I looked through possible solutions on the site, but was unable to have one work for my current code.
Code:
public String hiddenWord(){
word = randomWord.getRandomWord();
String dashes = word.replaceAll("[^ ]", " _ ");
return dashes;
}
public String guessNotification(){
if(word.indexOf(hv.keyChar)!=-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
letterGuessed = "There is a " + hv.keyChar + " in the word";
}
else if(word.indexOf(hv.keyChar)==-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
letterGuessed = "No " + hv.keyChar + " in the word";
guesses++;
System.out.println(guesses);
}
else{
letterGuessed = "Not a valid letter";
}
return letterGuessed;
}
public void newGame() {
hv.createNotification(this, size);
guesses = 0;
System.out.println(word);
}
}
Here is how the logic of how to replace the appropriate dash with the correct user guess might look
public static String guessNotification(String word, char userGuess, StringBuilder dashes) {
int guessedIndex = word.indexOf(userGuess);
if (guessedIndex != -1 && (userGuess >= 'a' && userGuess <= 'z')) {
letterGuessed = "There is a " + userGuess + " in the word";
dashes.setCharAt(guessedIndex*3+1, userGuess);
}
else if (guessedIndex == -1 && (userGuess >= 'a' && userGuess <= 'z')) {
letterGuessed = "No " + userGuess + " in the word";
guesses++;
}
else {
letterGuessed = "Not a valid letter";
}
return letterGuessed;
}
Comments are all correct. But you may want to see example code: Add an array of correct guesses:
char[] correct = new char[26]; // or more, depends on whether u use non ascii chars
Initialize the array with e.g. ' '. Then replace the dashes:
StringBuilder guessedPart = new StringBuilder;
for (int lc = 0; lc < word.lenght(); lc++) {
for (char c : correct)
if (word.indexOf(lc) = c) guessedPart.append(c);
if (guessedPart.length() < lc) guessedPart.append('_');
String guessedWord = guessedPart.toString();
That should do.

Attempting to remove characters from a string

I am attempting to remove vowels from a randomly generated 20 letter word. I have to use substring for this assignment but am having issues with it conceptually. With this code, the value of word never changes and stays its original value. When I do i+2 for the second half of the string it jumps two characters and messes up when there are two vowels directly after one another. If I have to use substring how can I improve this to work every time.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
for(int i = 0; i < 20; i++) {
if(word.charAt(i) == 'a') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'e') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'i') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'o') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'u') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'y') {word = word.substring(0, i) + word.substring(i++);}
System.out.println(word);
}
finalWord = word;
}
public String getWord()
{
return finalWord;
}
}
You can use the simplified code as below to do so:
public static void main(String[] args) {
String stringPara = "this example will remove the vowals aeiou";
stringPara = removeCharFromString(stringPara, "a");
stringPara = removeCharFromString(stringPara, "e");
stringPara = removeCharFromString(stringPara, "i");
stringPara = removeCharFromString(stringPara, "o");
stringPara = removeCharFromString(stringPara, "u");
System.out.println(stringPara);
}
public static String removeCharFromString(String str, String characterToRemove){
while(str.contains(characterToRemove)){
str = str.substring(0, str.indexOf(characterToRemove)) + str.substring(str.indexOf(characterToRemove)+1, str.length()) ;
}
return str;
}
Why won't you use a simple Regex?
String str = "Hello world!";
str = str.replaceAll("[AEIOUaeiou]", "");
The new value of str will be Hll wrld!
The problem is in your i++ operator. It messes up both your character checking as well as your loop. The post decrement operator (i++) takes the original value of i as method argument but increases its value by one for all subsequent instructions.
To illustrate this, let's assume the input is "Treyarch". Then, at index 2 the character at i is e. And the instruction
word = word.substring(0, i) + word.substring(i++); will have the following consequences:
word = Treyarch
i = 3
Not only does it not expel the vowel from the String it also messes up your index (i) . Because for the rest of the loop the i is 4 and when you enter the next iteration it will be 5, so your program never checks the first two if condition.
That being explained, the best practice for this solution would be to check for any of the conditions in one if statement and use immutable index. In other words:
for(int i = 0; i < word.length(); i++) {
if(word.charAt(i) == 'a' || word.charAt(i) == 'e' || word.charAt(i) == 'i' || word.charAt(i) == 'o' || word.charAt(i) == 'u' || word.charAt(i) == 'y') {
word = word.substring(0, i) + word.substring(i + 1);
}
You got a problem with your incrementation logic. When you remove a char, you missed the following one.
Your code could be easier to read if you use switch statements.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
// don't go too far !!
for (int i = 0; i < word.length(); i++) {
switch (word.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
// remove this vowel
word = word.substring(0, i) + word.substring(i + 1);
// step back in order to analyse the new i-th char
i--;
}
System.out.println(word);
}
finalWord = word;
}
public String getWord() {
return finalWord;
}
}
public static void main(String[] args)
{
String WordsWithoutVowels ="mayank";
String updated="";
for(char char1: WordsWithoutVowels.toCharArray())
{
switch(char1)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
updated+=char1;
}
}
System.out.println(updated);
}
I fixed your original solution. First of all - iterate over each letters - to word.length(). Other problem was with increasing "i".
for (int i = 0; i < word.length(); ) {
if (word.charAt(i) == 'a') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'e') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'i') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'o') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'u') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'y') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
i++;
System.out.println(word);
}
finalWord = word;
Here more elegant way:
public class WordsWithoutVowels {
String finalWord;
List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u', 'y');
public WordsWithoutVowels(String word) {
for (int i = 0; i < word.length(); ) {
if (vowels.contains(word.charAt(i))) {
word = word.substring(0, i) + word.substring(i + 1);
continue;
}
i++;
System.out.println(word);
}
finalWord = word;
}
public String getWord() {
return finalWord;
}
}
simplified your solution to meet the requirement.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
StringBuilder sb = new StringBuilder(word);
for(int i = 0; i < sb.length;) {
if(sb.charAt(i)=='a' || sb.charAt(i)=='e' || sb.charAt(i)=='i' || sb.charAt(i)=='o' || sb.charAt(i)=='u')
sb.deleteCharAt(i);
else
i++;
}
finalWord = sb.toString();
}
public String getWord()
{
return finalWord;
}
}
public WordsWithoutVowels(String word) {
for (int i = 0; i < 20; i++)
{
if (word.charAt(i) == 'a') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'e') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'i') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'o') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'u') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } if (word.charAt(i) == 'y') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } System.out.println(word + " " + i);
} finalWord = word; }

PigLatin program help...Capitalize?

I have the program working except for the capitalization part:
Here's how to translate the English word englishWord into the Pig Latin word pigLatinWord:
a. If there are no vowels in englishWord, then pigLatinWord is just englishWord + "ay". (There are ten vowels: 'a', 'e', 'i', 'o', and 'u', and their uppercase counterparts.)
b. Else, if englishWord begins with a vowel, then pigLatinWord is just englishWord + "yay".
c. Otherwise (if englishWord has a vowel in it and yet doesn't start with a vowel), then pigLatinWord is end + start + "ay", where end and start are defined as follows:
1. Let start be all of englishWord up to (but not including) its first vowel.
2. Let end be all of englishWord from its first vowel on.
3. But, if englishWord is capitalized, then capitalize end and "uncapitalize" start.
How do you do the capitalization part?
So far, I get Hasta= astaHay. It should be Hasta = Astahay
Here is the basic program so far:
public static boolean isVowel(char c) {
if (c == 'a' && c == 'A') {
return true;
} else if (c == 'e' && c == 'E') {
return true;
} else if (c == 'i' || c == 'I') {
return true;
} else if (c == 'o' || c == 'O') {
return true;
} else if (c == 'u' || c == 'U') {
return true;
} else {
return false;
}
}
public static String convertPigLatinWord(String englishWord) {
int length = englishWord.length();
if (englishWord.charAt(length - 1) == '.' && englishWord.charAt(length - 1) == '!' && englishWord.charAt(length - 1) == '?') {
char ch = englishWord.charAt(0);
String rest = englishWord.substring(1, length - 1);
return (rest + ch + "ay" + englishWord.charAt(length - 1) + "\"" + " ");
} else if (isVowel(englishWord.charAt(0))) {
return (englishWord + "yay" + " ");
} else {
char ch = englishWord.charAt(0);
String rest = englishWord.substring(1);
return (rest + ch + "ay" + " ");
}
}
public String translate() {
String pigLatinPhrase = "";
while (englishPhrase.length() > 1) {
String word = getWord();
pigLatinPhrase += convertPigLatinWord(word) + " ";
}
return pigLatinPhrase;
}
public static void main(String[] args) {
String answer = "";
do {
Scanner keyboard = new Scanner(System.in);
String input;
System.out.print("Please enter an English phrase: ");
input = keyboard.nextLine();
PigLatin3 first = new PigLatin3(input);
System.out.println(first.translate());
System.out.println("Would you like to translate another phrase? (y or n)");
answer = keyboard.nextLine();
} while (!(answer.equals("N")) && !(answer.equals("n")));
System.exit(0);
}
}
You can capitalize a letter by breaking the string to substrings and then capitalizing them:
String word = word.substring(0, 1).toUpperCase() + word.substring(1);
So just use the toUpperCase() and toLowerCase() methods of String ...
There is also a neat trick that you can use with single characters based on the ASCII table. Just xor them with 32 to get the other case.
What you are looking for is something like this:
public static String onlyFirstLetterUpperCase(String a){
int i;
for (i = 0; i < a.length(); i++){
if("AEIOUaeiou".indexOf(a.charAt(i)) != -1 )
break;
// indexOf looks for a char in a given string and returns its
// position or -1 if not found. So if this indexOf returns -1 I can be sure,
// that the character is not a vowel
}
return a.substring(0, i + 1).toUpperCase() + a.substring(i + 1).toLowerCase();
}
Just call this method after performing your operations

easier way to find vowels and print them? JAVA

Hey this is my first time posting! I got my program to print out the vowels from an input from user but I feel like I have repeated myself a lot in the for loop. Is there a quicker way to do this? Also is this code readable and in the correct format?
import java.util.Scanner;
public class Task09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String vowels ="";
//input from user
String answer= input.next()
//loop to find vowels
for(int i = 0 ;i<answer.length();i++)
{
char answerPosition = answer.charAt(i);
//checks if there are vowels in code
if (answerPosition =='a'
||answerPosition =='e'
||answerPosition =='i'
||answerPosition =='o'
||answerPosition =='u'
||answerPosition =='A'
||answerPosition =='I'
||answerPosition =='O'
||answerPosition =='U')
{
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}
Try this:
String newString = answer.replaceAll("[^AaeEiIoOuU]", "");
System.out.println(newString);
You wont need for loop as well and your code would be compact and sweet.
You could do:
if ( "aeiouAEIOU".indexOf(answerPosition) >= 0 ) {
vowels += answerPosition + " ";
}
inside the loop.
Additionally, as a matter of style, you might write the iteration slightly differently:
for (char c: answer.toCharArray()) {
if ( "aeiouAEIOU".indexOf(c) >= 0 ) {
vowels += c + " ";
}
}
You can do this way too.
import java.util.Scanner;
public class Hi {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String vowels = "";
// input from user
String answer = input.next();
// loop to find vowels
for (int i = 0; i < answer.length(); i++) {
char answerPosition = answer.charAt(i);
char tempAnsPos = Character.toUpperCase(answer.charAt(i));
// checks if there are vowels in code
if (tempAnsPos == 'A' || tempAnsPos == 'E' || tempAnsPos == 'I' || tempAnsPos == 'O' || tempAnsPos == 'U') {
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}

Java Why do I get this error? Exception in thread "main" java.lang.NullPointerException

This is the code that it is giving me the error for on the line with >>>>>>> I've already looked at this thread Exceptions but I still do not understand what I need to change :( I am a total beginner to programming.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class manyVowels {
public static final String wordList = "words.txt";
public static void main(String[] args) {
Scanner fileIn = null;
try {
//locate and open file
fileIn = new Scanner(new FileInputStream("words.txt"));
} catch (FileNotFoundException e) {
//if the file cannot be found, the program prints the message and quits
System.out.println("File not found. ");
System.exit(0);
}
String word = null;
if (fileIn.hasNext()) //if there is another word continue
{
String finalWord = null; // defines the word with most consecutive vowels
int maxVowels = 0;//sets initial value to 0
while (fileIn.hasNext()) {
// for each word in the file
int vowels = 0;
/*error here-->*/ for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
// for each character in the word, and exit early if the word is not long enough to beat maxVowels
if (hasVowels(word.charAt(i))) {
// consonants reset this to 0
vowels++;
} else {
// reached the end of the word so check if the count is higher than maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
vowels = 0;
}
}
// comparing vowels to maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
}
//seek vowels
word = fileIn.next();
for (int i = 0; i < word.length(); i++) {
if
((word.charAt(i) == 'A')
|| (word.charAt(i) == 'E')
|| (word.charAt(i) == 'I')
|| (word.charAt(i) == 'O')
|| (word.charAt(i) == 'U')
|| (word.charAt(i) == 'a')
|| (word.charAt(i) == 'e')
|| (word.charAt(i) == 'i')
|| (word.charAt(i) == 'o')
|| (word.charAt(i) == 'u')) {
//prints the final word with the most consecutive vowels
System.out.println("The word with the most consecutive vowels is: " + word);
System.exit(0);
}
}
}
}
private static boolean hasVowels(char charAt) {
throw new UnsupportedOperationException("Inserted by template."); //NetBeans generated method
}
}
Following the logic, you initialize the String word to null, and then proceed to call word.length().
word, being null, has no length(). Thus, the NullPointerException.
Assign a string to word before attempting to measure its length.
String word = "Hello!";
The variable word seems to be null, I think you skipped an instruction in which you fill it with a word read from fileIn. Your code should read something like this:
while (fileIn.hasNext()) {
// for each word in the file
word = fileIn.next();
int vowels = 0;
for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
...
you defined word as a null. When you say word.length() it means you are saying
null.length() that's why you are getting null pointer exception.
You should initialize String variable "word" before doing any operation( calling any string method by using '.' )
If you have any predefined value, initialize with that else initialize with empty string.
String word = "xyz" ;
String word = "" ;

Categories