Java string loop pattern - java

I'm going through some introductory exercises and I can not understand how to get java to output a string of five letters in the particular pattern shown below.
Initially I thought it followed the tribonacci sequence for number of characters per line. Without just printing the line, I can not figure out how to have java logically replicate the pattern. They seem to copy each other, but don't really follow a pattern.

The strings are palindrome and getting its end from the last string, for example; line 2 has "ABA" string, so line 3 will copy "ABA" at its end and will insert character C in the middle, so the final string will be "ABACABA"
String LastPattern="";
for(int i=0;i<5;i++){
System.out.println( LastPattern + (char)(65+i) +LastPattern);
LastPattern=LastPattern + (char)(65+i) +LastPattern;
}

Maybe this gets you going:
Something
Something New Something
Something New Something Newer Something New Something
The pattern is there, right in front of you.

Related

Why is my String array length 3 instead of 2?

I'm trying to understand regex. I wanted to make a String[] using split to show me how many letters are in a given string expression?
import java.util.*;
import java.io.*;
public class Main {
public static String simpleSymbols(String str) {
String result = "";
String[] alpha = str.split("[\\+\\w\\+]");
int alphaLength = alpha.length;
// System.out.print(alphaLength);
String[] charCount = str.split("[a-z]");
int charCountLength = charCount.length;
System.out.println(charCountLength);
}
}
My input string is "+d+=3=+s+". I split the string to count the number of letters in string. The array length should be two but I'm getting three. Also, I'm trying to make a regex to check the pattern +b+, with b being any letter in the alphabet? Is that correct?
So, a few things pop out to me:
First, your regex looks correct. If you're ever worried about how your regex will perform, you can use https://regexr.com/ to check it out. Just put your regex on the top and enter your string in the bottom to see if it is matching correctly
Second, upon close inspection, I see you're using the split function. While it is convenient for quickly splitting strings, you need to be careful as to what you are splitting on. In this case, you're removing all of the strings that you were initially looking at, which would make it impossible to find. If you print it out, you would notice that the following shows (for an input string of +d+=3=+s+):
+
+=3=+
+
Which shows that you accidentally cut out what you were looking to find in the first place. Now, there are several ways of fixing this, depending on what your criteria is.
Now, if what you wanted was just to separate on all +s and it doesn't matter that you find only what is directly bounded by +s, then split works awesome. Just do str.split("+"), and this will return you a list of the following (for +d+=3=+s+):
d
=3=
s
However, you can see that this poses a few problems. First, it doesn't strip out the =3= that we don't want, and second, it does not truly give us values that are surrounded by a +_+ format, where the underscore represents the string/char you're looking for.
Seeing as you're using +w, you intend to find words that are surrounded by +s. However, if you're just looking to find one character, I would suggest using another like [a-z] or [a-zA-Z] to be more specific. However, if you want to find multiple alphabetical characters, your pattern is fine. You can also add a * (0 or more) or a + (1 or more) at the end of the pattern to dictate what exactly you're looking for.
I won't give you the answer outright, but I'll give you a clue as to what to move towards. Try using a pattern and a matcher to find the regex that you listed above and then if you find a match, make sure to store it somewhere :)
Also, for future reference, you should always start a function name with a lower case, at least in Java. Only constants and class names should start in a capital :)
I am trying to use split to count the number of letters in that string. The array length should be two, but I'm getting three.
The regex in the split functions is used as delimiters and will not be shown in results. In your case "str.split([a-z])" means using alphabets as delimiters to separate your input string, which makes three substrings "(+)|d|(+=3=+)|s|(+)".
If you really want to count the number of letters using "split", use 'str.split("[^a-z]")'. But I would recommend using "java.util.regex.Matcher.find()" in order to find out all letters.
Also, I'm trying to make a regex to check the pattern +b+, with b being any letter in the alphabet? Is that correct?
Similarly, check the functions in "java.util.regex.Matcher".

Take first half of first string, and put it at beginning of second string based on user input

I am at the beginning chapters in my Java I class. This seems beyond what I have learned thus far.
I have to ask a user to input the first string. It could be anything. Then they have to input a second string. I have to take the first half of the first string and place it in front of the second string, then the other half of the first string and place it at the end of the first string. For example:
Enter something: ----
Enter something: word
Output: --word--
The only thing I've learned up until now is concatenation, indexes, and getting length. I have not learned arrays, if they can be relevant to this. What methods would I use to split this string up when I only know the strings after the user enters them? Even just informing me of unknown method calls would lead me in the right direction. I don't want (and can't) copy anyone's code.
Based on your example this is how you achieve that:
String firstString = "----"; //this should be read in from the user input.
String secondString = "word"; //this too should be read in from the user.
String finalString = firstString.substring(0,firstString.length()/2)+secondString+firstString.substring(firstString.length()/2,firstString.length());
Test code here
You should look into the Java StringAPI for substring. This will help you understand the code above.
You can use the substring method of the String class
something like this should work:
int idxMiddle = (string1.length()-1)/2;
string1.substring(0,idxMiddle) + string2 + string1.substr(idxMiddle);

Replacing parts of a string with characters JAVA

I know I was here earlier asking something similar, but I think I have narrowed down what i want to ask.
Ok, so I am making a program that plays the game of hangman on the jedit console. The user will guess one character at a time. At the beginning of the game, the program will display asterisks the same length of the word they are guessing. They have as many guesses as letters in the word. When they get a letter correct, the program will display the letters in place of asterisks. Here is an example of what the console should look like.
if the word is homework ********
they guess the letter e ***e**** (the bold e just happened because stars so that, it doesn't need to be bold)
then they guess the letter h h**e****
etc until there are no more asterisks
So I created a method that prints out the number of asterisks based on the number of letters in the word. I don't know how to place the letters in the place of the asterisks. I want to know if I should make a method that replaces the asterisks, or how else I can go about this. Thank you in advance for the help.
p.s I am not asking for anyone to dump code on me, that is not what I want. Just having help, and me having someone to ask questions to about things that I don't understand would be nice. by the way, I am in an intro to computer science class, so my knowledge of java is fairly low.
There are many ways you could approach this. The first that popped into my head is that you could start with a char[] the same length as the answer string. Look up the Arrays class for an easy way to fill it with asterisks. As the user guesses letters, search the answer string for that letter and replace the corresponding indexes of the char[]. Then construct a String from the char[] and display it.
Why not make something more clever, make a list of all the chars guessed so far and each time you want to print the word just go over each letter and replace it with * if not in the set.
Short: make a set of all the guesses so far. You don't have to work on the same data structure as you show the user.
I would use a list of characters instead of String for ****.
List<Character> hiddenWord = new ArrayList<Character>();
Instantiate the list with the number of * you need.
Create a function that will receive the guessed letter.
Check if the word contains that letter (use indexOf(int ch, int fromIndex) repeatedly until you get -1 - read about it here), and for each result you get that is !=-1, set the position in the array to be that letter (something like hiddenWord.set(poz, letter), where poz is the result of indexOf and letter is the guessed letter).
You can use StringBuffer insead String. In class StringBuffer exists method setCharAt.
Breifly, you will have variable String word - for guessing word, and StringBuilder guess for asterisks and guesed letters. When letter is guessed you will update guess with setCharAt.

Removing items from String

I am trying to replace all occurrences of a substring from a String.
I want to replace "\t\t\t" with "<3tabs>"
I want to replace "\t\t\t\t\t\t" with "<6tabs>"
I want to replace "\t\t\t\t" with "< >"
I am using
s = s.replace("\t\t\t\t", "< >");
s = s.replace("\t\t\t", "<3tabs>");
s = s.replace("\t\t\t\t\t\t", "<6tabs>");
But no use, it does not replace anything, then i tried using
s = s.replaceAll("\t\t\t\t", "< >");
s = s.replaceAll("\t\t\t", "<3tabs>");
s = s.replaceAll("\t\t\t\t\t\t", "<6tabs>");
Again, no use, it does not replace anything. after trying these two methods i tried StringBuilder
I was able to replace the items through StringBuilder, My Question is, why am i unable to replace the items directly through String from the above two commands? Is there any method from which i can directly replace items from String?
try in this order
String s = "This\t\t\t\t\t\tis\t\t\texample\t\t\t\t";
s = s.replace("\t\t\t\t\t\t", "<6tabs>");
s = s.replace("\t\t\t\t", "< >");
s = s.replace("\t\t\t", "<3tabs>");
System.out.print(s);
output:
This<6tabs>is<3tabs>example< >
6tabs is never going to find a match as the check before it will have already replaced them with two 3tabs.
You need to start with largest match first.
Strings are immutable so you can't directly modify them, s.replace() returns a new String with the modifications present in it. You then assign that back to s though so it should work fine.
Put things in the correct order and step through it with a debugger to see what is happening.
Take a look at this
Go through your text, divide it into a char[] array, then use a for loop to go through the individual characters.
Don't print them out straight, but print them using a %x tag (or %d if you like decimal numbers).
char[] characters = myString.tocharArray();
for (char c : characters)
{
System.out.printf("%x%n", c);
}
Get an ASCII table and look up all the numbers for the characters, and see whether there are any \n or \f or \r. Do this before or after.
Different operating systems use different line terminating characters; this is the first reference I found from Google with "line terminator Linux Windows." It says Windows uses \r\f and Linux \f. You should find that out from your example. Obviously if you strip \n and leave \r you will still have the text break into separate lines.
You might be more successful if you write a regular expression (see this part of the Java Tutorial, etc) which includes whitespace and line terminators, and use it as a delimiter with the String.split() method, then print the individual tokens in order.

Print string up to a certain word - Java

I was wondering in Java how I could print a string until it reaches the word "quit" in that string and then instantly stop printing at that point. For instance if the string value was:
"Hi there this is a random string quit this should not be printed"
All that should be printed is "Hi there this is a random string".
I was trying something like this, but I believe it to be wrong.
if ( input.indexOf( "quit" ) > -1 )
{
//code to stop printing here
}
Instead of thinking about the problem as "how to stop printing" (because once you start printing something in Java it's pretty hard to stop it), think about it in terms of "How can I print only the words up to a certain point?" For example:
int quit_position = input.indexOf("quit");
if (quit_position >= 0) {
System.out.println(input.substring(0, quit_position));
} else {
System.out.println(input);
}
Looks like homework, so this answer is in homework style. :-)
You're on the right track.
Save the value of that indexOf to an integer.
Then it's like you have a finger pointing at the right spot - ie, at the end of the substring you really want to print.
That's a hint anyway...
EDIT: Looks like people are giving it to you anyway. But here are some more thoughts:
You might want to think about upper and lower case as well.
Also consider what you are going to do if 'quit' is not there.
Also the solutions here don't strictly solve your problem - they'll print unnecessary spaces too, after the last word ends, before 'quit' starts. If that is a problem you consider String Tokenization or an adapation of the replaceAll solution above to cover for leading whitespace into `quit'.
This has a one-line solution:
System.out.println(input.replaceAll("quit.*", ""));
String.replaceAll() takes a regex to match, which I've specified to be "the literal 'quit' and everything following", which is to be replaced by a blank "" (ie effectively deleted) from the returned String
If you don't mind trailing spaces in your string
int index = input.indexOf("quit");
if (index == -1) index = input.length();
return input.substring(0, index);

Categories