Ignoring particular elements in a string array - java

I am writing a program that that ignores everything between the symbols "/" and "/" in a string, similarly as the IDE would in a real life scenario. I'm splitting the string into lines and storing it in an array, I then have a while loop to build words from the individual characters in the current line ignoring the symbols, however it my output isn't quite right.
Below is an example of what i'm trying to achieve.
Phrase: The quick brown /* fox jumped over the */ lazy dog.
Desired output: The quick brown lazy dog.
Essentially removing everything between the comments.
Here is my current attempt.
public class Testing6 {
public static void main(String[] args) {
String riddle = "The Quick \n" +
" brown /* fox \n" +
" jumped over \n" +
" the */ lazy \n" +
" dog \n";
String[] lines = riddle.split("\\r?\\n");
for (String line : lines) {
int n = line.length();
int index = 0;
String word = "";
while (index < n) {
char ch = line.charAt(index);
word = word + ch;
if (ch == ' ' ) //if ch is empty, word is complete, print word.
{
System.out.println(word);
word = "";
}
if (ch == '/' || ch == '*') { // checking for symbols
index++;
if (ch == '*' || ch == '/')
{
index++;
break; // breaking if symbols match
}
}
index++;
}
}
}
}
Current output:
The
Quick
brown
jumped
over
the `
Thank you in advance for any feedback.

I am modifying your answer to display the line as per your expectation. There is no real enhancement done to your code here.
Following are the issues in your code:
You are using println which prints each string in a new line.
You are also printing empty words thereby seeing gaps in the strings in the output.
I fixed both the above problems and it is displaying properly now
String riddle = "The Quick \n" +
" brown /* fox \n" +
" jumped over \n" +
" the */ lazy \n" +
" dog \n";
String[] lines = riddle.split("\\r?\\n");
String word = "";
for (String line : lines) {
int n = line.length();
for (int index = 0; index < n; index++) {
char ch = line.charAt(index);
if (ch == ' ') { // if ch is empty, word is complete, print word.
if (!word.isEmpty()) { // do not log empty word
word = word + ch;
System.out.print(word);
word = "";
}
continue;
}
if (ch == '/' || ch == '*') { // checking for symbols
index++;
if (ch == '*' || ch == '/') {
index++;
break; // breaking if symbols match
}
}
word = word + ch; // only non-empty chars are added here
}
}
Output is
The Quick brown jumped over the dog
Note that the last word may contain extra space based on your input. But I think you can take it forward from here.

Related

How to write a program in Java that looks for a '00' checking every character in a string?

I'm trying to write a simple program that asks the user for an input consisting of zeroes and ones and checks every character looking for a double zero '00', if the current character is a '1' the program is considered to be in state "A" and so it prints the state and the character, if the character is a '0' the program is in state "B" and if there's a '00' the program is in state "C", after entering state "C" (after finding a '00') the program can't exit that state,that means that it will keep checking every character,but the resulting string should be "State C" + character even if the character is a single zero or one.
As of now I have something like this
import java.util.Scanner;
public class onesandzeroes {
public static void main(String[] args) {
System.out.println("Write a String that consists of 0 and 1");
Scanner scanner = new Scanner(System. in);
String inputString = scanner.nextLine();
for (int index = 0; index < inputString.length();
index++) {
char aChar = inputString.charAt(index);
if (aChar == '0'){
System.out.println("State B " + aChar);
/* This is the part I'm having trouble with, I was thinking about something like
if(aChar =='0' && charAt(index + 1 == '0')){
System.out.println("State C" + aChar + charAt(index + 1);
}
to look for a '0' that is followed by another '0' but it doesn't work
*/
} else{
System.out.println("State A " + aChar);
}
}
}
}
I know that you can probably look the entire string and only check if there's a '00' but I want to check every character individually except when it looks for '00'
So I have 2 questions:
How can I look for a '00' in the string? The ideal way would be to check every '0' for a following '0'.
And how can I make the program print "State C" + character ONLY after the first '00' has been found? that is after the program finds a '00' it should stay in State C for '00' and every other character following it.
maybe this way:
import java.util.Scanner;
public class StringScanner {
public static void main(String[] args) {
System.out.println("Write a String that consists of 0 and 1");
final var scanner = new Scanner(System.in);
final String inputString = scanner.nextLine();
var currentState = State.A;
for (int index = 0; index < inputString.length(); index++) {
final char currentChar = inputString.charAt(index);
System.out.println("The current char is " + currentChar + " and I'm in state " + currentState);
if (currentState == State.C) {
// do nothing because final state has already been reached
continue;
}
if (currentState == State.B) {
if (currentChar == '0') {
// 2 zeros found got into final state :)
currentState = State.C;
} else {
//
currentState = State.A;
}
continue;
}
if (currentState == State.A) {
if (currentChar == '0') {
currentState = State.B;
}
}
}
}
private enum State {
A, B, C
}
}
Firstly you can check inputString.contains("00");
If true write
inputString.charAt(inputString.indexOf("00") + 2);

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.

Check whether the brackets and delimiters contained in a string are balanced

Here is simple code to check whether the brackets/delimiters contained in a string are balanced - can anyone help why wont it work! I'm sure there are many things I could to to improve efficiency but for the purpose of my current tutorial I would like to know why it doesn't work in this form and what the current problems are.
Firstly, I cannot add the variable c to the LinkedList, I have to use the literal value - I have identical in another tutorial and it adds the variable just fine.
Secondly, in some instances it simply doesn't add the delimiters to my linkedlist as per the if statements. the string '(i wonder(if) the delimiters in this) [sentence] will evaluate as[ balanced}' evaluates as balanced but from my code it shouldn't do - Please help I am pulling my hair out here.
Finally, I have had the same error but sporadically not for every string - some i type in randomly for example 'csadlkfsd kljf[]{}[ ][ ]{ '
this returned the error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at set07102.Delimiter.main(Delimiter.java:16)
and line 16 is 'char c = s.charAt(0);' and as far as i see this shouldn't be happening.
System.out.println(strStack); is only there are at the end to inspect the LinkedList - if it makes it that far through the code!
any help will be amaaaaaaaaazing thanks guys.
import java.util.LinkedList;
import java.util.Scanner;
public class Delimiter {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a string containing different types of brackets: ");
String str = scanner.nextLine();
String[] strSplit = str.split(" ");
LinkedList<Character> strStack = new LinkedList<>();
System.out.println(" ");
for(String s : strSplit) {
char c = s.charAt(0);
if(c == '('){
strStack.push('(');
}
if( c == '{'){
strStack.push('{');
}
if(c == '['){
strStack.push('[');
}
if(c == '<'){
strStack.push('<');
}
if(c == ')' && strStack.get(0) != '('){
System.out.println("The delimiters in the string " + "'" + str + "'" + " are not balanced!");
break;
}
if(c == ']' && strStack.get(0) != '['){
System.out.println("The delimiters in the string " + "'" + str + "'" + " are not balanced!");
break;
}
if(c == '}' && strStack.get(0) != '{'){
System.out.println("The delimiters in the string " + "'" + str + "'" + " are not balanced!");
break;
}
if(c == '>' && strStack.get(0) != '<'){
System.out.println("The delimiters in the string " + "'" + str + "'" + " are not balanced!");
break;
}
}
System.out.println("The delimiters in the string " + "'" + str + "'" + " are balanced. ");
System.out.println(" ");
System.out.println(strStack);
}
}
Here is one way of doing it. I'm not sure if it's completely bug free and will handle all cases, but I think it might be close.
As other users have commented, splitting the input string is the wrong approach. You'll need to iterate over each character and use the stack to keep track of what brackets you've seen and what should be closed next.
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;
public class BalancedBrackets
{
public static void main(String[] args)
{
HashMap<Character,Character> bracketPairs = new HashMap<Character,Character>();
bracketPairs.put('[', ']');
bracketPairs.put('(', ')');
bracketPairs.put('{', '}');
bracketPairs.put('<', '>');
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a string containing different types of brackets: ");
String str = scanner.nextLine();
for(int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if(bracketPairs.keySet().contains(c))
{
stack.push(c);
}
if(bracketPairs.values().contains(c))
{
if(stack.size() == 0)
{
System.out.println("Unexpected closing bracket.");
return;
}
char lastOpen = (char) stack.peek();
char expectedClose = bracketPairs.get(lastOpen);
if(expectedClose == c)
{
stack.pop();
}
else
{
System.out.println("Unexpected closing bracket.");
return;
}
}
}
if(stack.size()==0)
{
System.out.println("String is balanced.");
}
else
{
System.out.println("String is unbalanced.");
}
}
}

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

My ArrayList (s) are just printing numbers

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

Categories