How come my split("\n") isn't working - java

I've tried "\n\n" and "\r" and everything else, including replaceAll("\r\n", "n") and I still do not understand why it doesn't work. I've also tried "\w", "\n", "\n+" - I've basically tried everything under "My split("\n") doesn't work" on Google search.
I'm trying to split a word with a lot of "\n". I basically have two different classes. One generates this word, and via the other class constructor object transfers it into the split("\n") method. But whatever I do, the array still stays empty.
I've also tried word.split(System.getProperty("line.separator")) even though I didn't have a clue as to what it meant, but it also came up under one of the solutions to this problem.
Here's my Code:
//in Class A
public String getWord()
{
word = word +"\n" + horizontal;
return word;
}
//in Class B
classA a = new classA();
String grid = a.getWord();
String [] lines = grid.split("\n");
EDIT: Sorry, typo mistake, I'll just ask again later. I did actually put grid.split("\n") in my code. What now? The array really is empty. I did System.out.println(array.length) and it was 0. Also, I typed System.out.println("array is " + array) and it only gave me "array is" as output. I know I'm making a stupid mistake somewhere, and I know I can't expect people to answer my question if I don't know what info to provide.
I also wanted to add some stuff in the comments section here for the comfort of those sitting in front of their laptops...
word and horizontal is a string. It's actually a crossword puzzle together.
See? Look!
LONDONPYVRAOMNDDEFSG
GCPZVBATHYXAZXEZIMOZ
NKDGBERLINCHPLTMHMSM
ZMUKPGCHRKDTYGIMRLHO
TVRWBXPRETORIAJBVKWT
OGIVSDFULULHQHAHEJNV
PNWEJHBAKBJZNBPARIS
PHKCZCYGTXEEXDUCPMXF
QIMQMABRASILIALJOFJQ
GXNXKTAHIQMMIFPSYDLI
CAIROYKZYSWEFPUZPKRG
BTNAUNIDQAYVYAPGWWIN
QXZMQSZBTCBEIJINGBSD
QWQRYTBPTKRBCJUOMJTV
SODHAMSTERDAMEMSLVAM
YQHEVNXQQJXCDZKEYQVT
NAIROBISVDNTCFJNYDEG
AKXVOIGYTZTJHGIAFIKZ
BAGHDADSADJTWOOMVRYT
YCPOBXQQMQKBTDMYPYWT
It's city names. At the end of this, I'm supposed to show the solution to the puzzle by changing cases. I know how to do this, but the problem is that I can't seperate them into lines anymore. I don't know why. That's my only problem here. It seems to work for everyone, except for me.
Answers with clues will be appreciated? To delve into a dark and deep mystery...

It should be
grid.split("\n");
not
instance.split("\n")

Call grid.split("\n");
You can't split a class.
Better a.getWord().split("\n");

In your code there isn't no method named split , also your didn"t call your method getword inside System.out.println() ....
First Class :
public class A {
public String returnedWord ="";
public String getWord(String word , String horizontal)
{
returnedWord = word +"\n" + horizontal;
return returnedWord ;
}
}
the Second Class :
public class B {
public String word = "Hello";
public String horizontal = "World";
public static void main (String [] args ) {
A a = new A();
System.out.println(a.getword(word,horizontal));
}
}
you will get the output below :
Hello
World

Related

Color words in sentence that are uppercase different color

I am attempting to color all words sent from my chat packet blue by default but if any word is uppercase (just the first letter of word) in the sentence (other than the first word) I would like to color it lime green. I am a beginner with java but this is what I have come up with so far. The problem is that it is still setting the color of any word blue no matter if it is uppercase or not.
public void sendChatPacket(String s, int id) {
boolean isUpperCase = Character.isUpperCase(s.length());
s = isUpperCase ? "<col=65280>\" + s + \"</col>" : "<col=255>\" + s + \"</col>";
}
public void showInformation(Player player) {
sendChatPacket("I can start this quest by speaking to Hetty", 8147);
sendChatPacket("who is in Rimmington.", 8148);
}
Any help is appreciated, thank you!
Replace
boolean isUpperCase = Character.isUpperCase(s.length());
with
boolean isUpperCase = s.toUpperCase().equals(s);
The problem is that you are checking if the length of the string (which is a number) is uppercase.
Also, you are re-assigning s in the last line of the method. This won't change the original string. See https://stackoverflow.com/a/40523/1039555 for more details.
Edit based on new information in comments:-
String[] words = s.split("\\s+");
for (String word : words) {
if (Character.isUpperCase(word.charAt(0))) {
s = s.replace(word, "<col=65280>" + word + "</col>");
} else {
s = s.replace(word, "<col=255>" + word + "</col>");
}
}
Not sure what you are trying to do here but whatever you assign to s is not going to take effect to caller:
public void sendChatPacket(String s, int id) {
boolean isUpperCase = Character.isUpperCase(s.length());
s = isUpperCase ? "<col=65280>\" + s + \"</col>" : "<col=255>\" + s + \"</col>";
}
Method parameter are passed by value in Java. Even you are assigning s to something else, the argument passed by caller is not going to be affected.
In your caller, you are not doing anything with the message you passed in either. So your code simply do nothing meaningful.
If it is not your real code, please offer code that demonstrate the problem. Tell us what the expected result is and how your example code not fulfilling your expectation.
A little recommendation next time you are asking: You are giving too much irrelevant context here. For example in this question, you should have done diagnosis yourself and should found that after calling sendChatPacket, the result is unexpected. You do not need to tell us whatever coloring. You are just manipulating a String, and the String manipulation does not work as expected. By simplifying the scenario, you could have provide a MVCE which makes people a lot easier to understand your problem (hence, offering help)
You are begginer but please next time you ask something take longer explaining your goal...
the following code will pick first color to the words which start with capital letter, the second color to all other words
if (s != null && s.length() > 0) {
StringBuilder result = new StringBuilder(s.length() * 2);
result.append("<col=255>");
String[] split = s.split(" ");
for (String t : split) {
boolean isUpperCase = Character.isUpperCase(t.charAt(0));
if (isUpperCase)
result.append("<col=65280> " + t + "</col>");
else
result.append(" "+t);
}
result.append("</col>");
s = result.toString();
}
if your are printing pure html this is going to work...
anyway i strongly advise to start basics before jumping into complex things...

transform short word to original word

I used some word counting algorithm and by a closer look I was wondering because I got out less words than originally in the text because they count for example "it's" as one word. So I tried to find a solution but without any success, so I asked myself if their exist anything to transform a "short word" like "it's" to their "base words", say "it is".
Well, basically you need to provide a data structure that maps abbreviated terms to their corresponding long versions. However, this will not be as simple as it sounds, for example you won't want to transform "The client's car." to "The client is car."
To manage these cases, you will probably need a heuristic that has a deeper understanding of the language you are processing and the grammar rules it incorporates.
I just built this from scratch for the challenge. It seems to be working on my end. Let me know how it works for you.
public static void main(String[] args) {
String s = "it's such a lovely day! it's really amazing!";
System.out.println(convertText(s));
//output: it is such a lovely day! it is really amazing!
}
public static String convertText(String text) {
String noContraction = null;
String replaced = null;
String[] words = text.split(' ');
for (String word : words) {
if (word.contains("'s")) {
String replaceAposterphe = word.replace("'", "$");
String[] splitWord = replaceAposterphe.split('$');
noContraction = splitWord[0] + " is";
replaced = text.replace(word, noContraction);
}
}
return replaced;
}
I did this in C# and tried to convert it into Java. If you see any syntax errors, please point them out.

Replacing words in a String java

Say I have a string,
String templatePhrase = "I have a string that needs changing";
I also have a method to replace words in any given String. Here is the method:
public String replace(String templatePhrase, String token, String wordToPut) {
return templatePhrase.replace(token, wordToPut);
}
Now say (for the sake of my actual task) I have all the words in my String str in a List named wordsInHashtags. I want to loop through all the words in wordsInHashtags and replace them with words from another List named replacement using the replace() method. Each time the loop iterates, the modified String should be saved so it will hold its replacement(s) for the next loop.
I will post my code if anyone would like to see it, but I think it would confuse more than help, and all I am interested in is a way to save the modified String for use in the next iteration of the loop.
I was just reading about strings in beginning Java 2 the other day, :"Strings Objects are immutable" Cant be changes basically however StringBuffer Objects were created to deal with such a circumstance as i understand it. You could try:
StringBuffer templatePhrase = "I have a string to be changed";
templatePhrase.replace(token, wordToPut);
String replacedString = (String)templatePhrase;
Line 3 may cause a problem?
public class Rephrase {
public static void main(String[] args) {
/***
Here is some code that might help to change word in string. originally this is a Question from Absolute Java 5th edition. It will change two variable whatever you want but algorithm never change.So the input from keyboard or any other input source.
********/
String sentence = "I hate you";
String replaceWord = " hate";
String replacementWord = "love";
int hateIndex = sentence.indexOf(replaceWord);
String fixed = sentence.substring(0,hateIndex)+" "+replacementWord+sentence.substring(hateIndex+replaceWord.length());
System.out.println(fixed);
}
}

Efficent way to replace underscore with char or string

I have researched this topic for a while, but without much success. I did find the StringBuilder and it works wonders, but that's as far as I got. Here is how I got my hangman program to work like it should:
if(strGuess.equalsIgnoreCase("t")){
mainword.replace(0,1,"T");
gletters.append('T');
}
else if(strGuess.equalsIgnoreCase("e")){
mainword.replace(1,2,"E");
gletters.append('E');
}
else if(strGuess.equalsIgnoreCase("c")){
mainword.replace(2,3,"C");
gletters.append('C');
}
else if(strGuess.equalsIgnoreCase("h")){
mainword.replace(3,4,"H");
gletters.append('H');
}
else if(strGuess.equalsIgnoreCase("n")){
mainword.replace(4,5,"N");
gletters.append('N');
}
else if(strGuess.equalsIgnoreCase("o")){
mainword.replace(5,6,"O");
mainword.replace(7,8,"O");
gletters.append('O');
}
else if(strGuess.equalsIgnoreCase("l")){
mainword.replace(6,7,"L");
gletters.append('L');
}
else if(strGuess.equalsIgnoreCase("g")){
mainword.replace(8,9,"G");
gletters.append('G');
}
else if(strGuess.equalsIgnoreCase("y")){
mainword.replace(9,10,"Y");
gletters.append('Y');
}
else{
JOptionPane.showMessageDialog(null, "Sorry, that wasn't in the word!");
errors++;
gletters.append(strGuess.toUpperCase());
}
SetMain = mainword.toString();
GuessedLetters = gletters.toString();
WordLabel.setText(SetMain);
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
However, I can't do this for EVERY letter for EVERY word, so is there a simple and efficient way to do this? What I want is to have a loop of some sort so that I would only have to use it once for whatever word. So the word could be technology (like it is above) or apple or pickles or christmas or hello or whatever.
I have tried using a for loop, and I feel the answer lies in that. And if someone could explain the charAt() method and how/where to use it, that'd be good. The closest I got to being more efficient is:
for(i = 0; i < GuessWord.length(); i++) {
if (GuessWord.charAt(i) == guess2) {
mainword.replace(i,i,strGuess.toUpperCase());
}
So if you could use that as a basis and go off of it, like fix it? Or tell me something I haven't thought of.
It's a good question. There's clearly repeated code, so how do you replace all that with something reusable. Actually, you can dispense with all of your code.
That whole code block can be replaced by just one line (that works for every word)!
String word = "TECHNOLOGY"; // This is the word the user must guess
mainword = word.replaceAll("[^" + gletters + "]", "_");
This uses replaceAll() with a regex that means "any letter not already guessed" and replaces it with a underscore character "_". Note that Strings are immutable, and the replaceAll() method returns the modified String - it doesn't modify the String called on.
Here's some test code to show it in action:
public static void main(String[] args) {
String word = "TECHNOLOGY"; // what the user must guess
StringBuilder gletters = new StringBuilder("GOTCHA"); // letters guessed
String mainword = word.replaceAll("[^" + gletters + "]", "_");
System.out.println(mainword);
}
Output:
T_CH_O_OG_

Java, how to compare Strings with String Arrays

I have been searching here for some time but haven't been able to find the answer to it.
I am basically required to use an array for this assignment from college. And then I am supposed to check that the input (which is also a String) matches whatever's stored within the String array.
I know one can easily compare Strings by using the .equals() method. However, the same method is not working with the String array.
I created the following example of code for the purpose of StackOverflow so you can use it to explain it to me, if you'd like.
What am I doing wrong?
import java.util.Scanner;
class IdiocyCentral {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
/*Prints out the welcome message at the top of the screen*/
System.out.printf("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf("%55s", "=================================\n");
String [] codes = {"G22", "K13", "I30", "S20"};
System.out.printf("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2], codes[3]);
System.out.printf("Enter one of the above!\n");
String usercode = in.nextLine();
if (codes.equals(usercode)) {
System.out.printf("What's the matter with you?\n");
}
else {
System.out.printf("Youda man!");
}
}
}
I apologize if this has been asked before and I just missed it, if its a double question, I will remove it.
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.
if(Arrays.asList(codes).contains(userCode))
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
Iterate over the codes array using a loop, asking for each of the elements if it's equals() to usercode. If one element is equal, you can stop and handle that case. If none of the elements is equal to usercode, then do the appropriate to handle that case. In pseudocode:
found = false
foreach element in array:
if element.equals(usercode):
found = true
break
if found:
print "I found it!"
else:
print "I didn't find it"
If I understand your question correctly, it appears you want to know the following:
How do I check if my String array contains usercode, the String that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
Instead of using array you can use the ArrayList directly and can use the contains method to check the value which u have passes with the ArrayList.
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner in = new Scanner (System.in);
/*Prints out the welcome message at the top of the screen */
System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf ("%55s", "=================================\n");
String[] codes =
{
"G22", "K13", "I30", "S20"};
System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
codes[3]);
System.out.printf ("Enter one of the above!\n");
String usercode = in.nextLine ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}

Categories

Resources