What I need have happen: Take a list of names from a multiline TextArea, put them into an array, modify them a bit, and then print them out in a list.
What I'm having problems with: Actually getting the input from the TextArea and sticking it in an array -- I have the rest down. I read someone's similar question, but the solution for that question isn't working for me; I keep getting a NullPointerException when I reference it, meaning that there's nothing there, and that the input wasn't put into the array.
The coding: The TextArea is called "taClient" and is all activated by a mouse click on a button called "btnProcess"
private void btnProcessMouseClicked(java.awt.event.MouseEvent evt)
{
String[] names = taClient.getText().split("\\n");
Account[] account = new Account[names.length];
for(int x = 0; x<names.length; x++)
{
account[x].Name = names[x];
}
//All the modifications and other code and printout.
}
As far as I'm aware, this should work, but I don't have much experience with textareas or the String.split() method, so I could just be way off. (Plus, as I said before, this design was based off of someone else's question on here, and they said this answer solved their problem...but not mine.)
Thanks in advance!
Did you try to split the string with just one backslash, likes this: .split("\n").
You are probably on Windows and want to read Split Java String by New Line
Also using Guava's new LineReader(new StringReader(taClient.getText())) can do the trick (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/LineReader.html)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am new to java. Trying to create a function to remove a given string "arg" from myString which is previously set and return a new string not affecting myString. I believe i could solve this problem if it was not for all non alphabetical character of arg should remain in the string. so if arg has a 7 in it that should still be included in the final string. characters being removed are case insensitive as well.
I have edited the previous code and post, i can now run my code but I am not getting the correct results, I am trying to remove all numbers from arg before using it to remove all the characters. myString method is previously defined and working properly to return a string.
For examplecurrent string "my lucky numbers are 6, 8, and 19.", calling remove("ra6") would return "my lucky numbes e 6, 8, nd 19."
or "my lucky numbers are 6, 8, and 19.", calling remove("6,.") would return "my lucky numbers are 6, 8, and 19."
thank you!
public String remove(String arg) {
char[] charArray=arg.toCharArray();
String result="";
String newString="";
for (int i = 0; i < charArray.length; i++) {
if (!Character.isDigit(charArray[i])) {
result = result + charArray[i];
return result;}}
if (myString==null || myString=="") {
this.myString="";}
if (myString!=null) {
newString= myString.replaceAll(result,"");}
return newString;
}
Here is one way using streams. Just create a stream of characters via the chars() method and allow only letters to pass thru. Then each character to a String and join them together. Then remove that result from the original passed string.
String myString = "abcdTLK123efgh";
String arg = "TLK###123";
String result = remove(arg, myString);
System.out.println("Result = " + result);
prints
Result = abcd123efgh
The method
I modified the method to accept two strings.
the one to remove characters(arg).
and the from which to remove modified arg from myString
it works by
streaming all the characters of arg.
filtering out all but letters and digits
joining them as a string.
and then removing that filtered string from the myString.
public static String remove(String arg, String myString) {
if (myString == null || myString.isBlank()) {
return "";
}
return arg.chars().filter(
ch -> Character.isLetter(ch))
.mapToObj(Character::toString)
.collect(Collectors.collectingAndThen(
Collectors.joining(),
str -> myString.replace(str, "")));
}
Note: If myString is null then assigning an empty string to it will contain nothing to change. Nor an initial empty string. So I just returned an empty String if those conditions existed.
I believe i could solve this problem if it was not for all non alphabetical character of arg should remain in the string.
The good news is that you can solve it yourself.
The bad news is that the code above is in such a mess that it would be difficult for you to fix it by yourself. (Given your current level understand of Java syntax, way of working, etcetera.)
(Also, there is a long more wrong than the "if it were not for ..." ...)
So here is what I advise you to do.
Save a copy of the current version of the (entire) class somewhere safe so that you can look it again if you need to, or revert to it.
Develop a model of what the method needs to do and how it will do it; see below.
Delete all lines of code between the first { and last } shown in the question. Yes. Delete them.
Compose the new version of the code, one line at a time. As follows:
Add a line.
Compile the code (or let the IDE compile it for you).
Read the compilation error(s) that just appeared.
Understand the compilation errors.
Make the necessary changes to fix the compilation errors. Don't rely on your IDE's facility for suggesting corrections. (The IDE doesn't understand your code, what you are going to add next, or what you are trying to achieve. Its suggestions are liable to be unhelpful or even wrong.)
Repeat until you have dealt with all of the compilation errors that were introduced.
Now you are ready to add another line.
Once you have a complete method, you can then try to run it.
You will most likely find that the code doesn't work. But at least it will be valid Java code. And in the process of doing 4. above, you will (hopefully!) have learned enough Java syntax to be able to read and understand the code that you wrote. And 2. will help you understand what the code you are writing should do.
My other observation is that it looks like you have been adding and removing statements to this code with no clear understanding of what they do or what needs to happen. Maybe you started with some code that did something else ... correctly ... but it is hard to tell now.
Changing things randomly to try to make the code work is not a sensible approach. It rarely works. You need to have a model (or plan) in your head or on paper (e.g. as pseudo-code or flowcharts) about how the code ought to work.
Programming is about 1) developing the model, then 2) translating the model into code. The first part is the hard (and interesting) part. But if you skip the first part, the second part is an essentially random process, and unlikely to succeed.
The problem with starting with someone else's code is that you risk not developing a mental model of how that code works. Let alone the model that you are aiming for.
Finally, a professional programmer will use a version control system for their source code, and make relatively frequent commits of their code to their repository. Among other things, that allows them to quickly "roll back" to an earlier version if they need to, or keep track of exactly what they changed.
It is probably too early for you to learn about (say) using Git ... but it would help you solve your problem if you could just "roll back" all of the changes where you were "messing" with the code to get it to work.
Im fairly new in programming java (just started a couple of months ago) and i am unfortunatly in a bit of confused state at the moment.
I am presently using BlueJ for my programming, and ive encountered a exercise in in my book which i do have some problems getting the grips of how to further add the wanted functionality.
The exercise has two previously made classes (ReaderInput & WriterOutput), and i am to create a new class which calls and makes use of the preceeding classes methods. The exercise includes two .txt files, one includes a story, and the second one includes differents kinds of adjectives(words). Then, i have to read the story.txt file, and replace Strings in that file with a specific value(a string with the value "ADJECTIVE"), with randomly chosen words from the adjectives.txt file, and finally, output them (write) to a completely new file.
A sample from the story.txt file:
'Once upon a time there was a ADJECTIVE girl who were in a ADJECTIVE birthday togheter with lots of ADJECTIVE friends etc....'
A sample from the adjectives.txt file:
whiny
old
little
stupid
etc...
So, i created a new class, added and initialized new field objects of the ReaderInput class, like so;
private ReaderInput reader;
private WriterOutput writer;
private Random random;
public StoryCreator()
{
reader = new ReaderInput();
writer = new WriterOutput();
random = new Random();
}
Then i created a new method called createAdjectiveStory with parameters to specify both the story filename and adjectives.
public void createAdjectiveStory(String storyFilename, String adjectivesFilename/*, String outputFilename*/)
Then, i declare two variables to hold the reader words from the ReaderInput class(specifying the file to read through parameters):
ArrayList<String> story = reader.getWordsInFile(storyFilename);
ArrayList<String> adjective = reader.getWordsInFile(adjectivesFilename);
Then here comes the big headache. While, i have been able to declare a String varible wordToChange = "ADJECTIVE"; , create a for-each loop to iterate over the story arraylist collection, with an if statement to check if string in element is equal to wordToChange. At last i made a random to go trough the adjective arryalist, and get a random word from the collection (This gets a random word from the file each time i call the method and print it individually)
for(String reader : story){
int index = random.nextInt(adjective.size());
String word = adjective.get(index);
if(reader.equals(wordToChange))
Collections.replaceAll(story,wordToChange,word);
}
}
In the if statement, i tried to use the replaceAll function, like so:
Collections.replaceAll(story,wordToChange,word);
The problem here is that if i try to print this out (just to verify that it works), i get this:
'Once upon a time there was a OLD girl who were in a OLD birthday togheter with lots of OLD friends etc....'
Now i rather want this.
'Once upon a time there was a OLD girl who were in a WHINY borthday togheter with lots of STUPID friends etc....'
Ive tried make use of the .replace function, like so:
Collections.replace(story,wordToChange,word);
But i get an error specifying: 'Cannot find symbol - method replace'.
I am quite stuck right about here, and i cannot seem to find the right solution for this. Ayone have any tips/tricks or solution for this?
New programmer needing a little "push" in the right direction. Any help will be appreciated highly:)
The problem is that it's choosing the word to change it to once and then the replaceAll is replacing every instance of REPLACE immediately.
What you should do instead is use an iterator in your for loop:
Iterator<String> i=story.iterator();
while (i.hasNext()) {
String check = i.next();
if (check.equals(stringToReplace)) {
i.set(getRandomAdjective());
}
}
You should create a method for your code to get a random adjective.
I have assigment to make notepad using NetBeans Java. I already made the whole thing, I just don't know how to implement find/replace dialog, can you help me with this. I'm using jTextArea.
I will assume that you already know about Swing and how to make the appropriate dialog box (since you apparently have already made the JTextArea for the Notepad equivalent), and that you just want to know how to make it work on the back end.
What I would do is have a Scanner object go through your file to perform the find and replace.
String myAlteredText = "";
Scanner scanner = new Scanner(myText);
while(scanner.hasNext()) {
String next = scanner.next();
if(next.equals(userFindInput)) {
myAlteredText += userReplaceInput;
}
else {
myAlteredText += next;
}
myAlteredText += " ";
}
You can use .equalsIgnoreCase() if case doesn't matter. Likewise, you can tweak to adjust to your user parameters (i.e., if it doesn't have to match the whole word, use .contains() instead). There may be some nit-picky other things you need to do to maintain abnormal spacing and line breaks, but this is the general approach I would use.
You could use a JTable although this is rather unconventional. You could load each word into a new cell. This way when you need to replace 1 word you don't need to update the entire jtextarea for just 1 character unless I am mistaken. This would require a lot of work however in order to get this to work
Is there a way to dynamically change output in Java? For instance, in a terminal window if I have:
System.out.print("H")
and then I have:
System.out.print("I")
The output will be:
HI
Is there a way to assign a position to outputs that allows you to replace characters dynamically? For instance (and I know this would not output what I want, I merely want to demonstrate my thinking) this:
System.out.print("H")
Thread.sleep("1")
System.out.print("I")
And it would first print out
H
and then after a second, replace the H with an I?
I'm sure this sounds stupid, I am just interested in dynamically changing content without GUIs. Can someone point me in the direction for this technique? Thank you very much in advance.
You might want to take a look at
System.out.printf
Look at the example shown here: http://masterex.github.com/archive/2011/10/23/java-cli-progress-bar.html
edit:
printf displays formatted strings, which means you can adapt that format and change it for your needs.
for example you could do something like:
String[] planets = {"Mars", "Earth", "Jupiter"};
String format = "\r%s says Hello";
for(String planet : planets) {
System.out.printf(format, planet);
try {
Thread.sleep(1000);
}catch(Exception e) {
//... oh dear
}
}
Using the formatted string syntax found here: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
As the comment says this solution is only limited to a singular line however dependent on your needs this might be enough.
If you require a solution for the whole screen then a possible solution would be (although quite dirty) would be to hook the operating system using JNA and get a handle on the console window, find its height and then loop println() to "clear" the window then redraw your output.
If you would like to read more then I can answer more questions or here is a link: https://github.com/twall/jna
You can use \b to backspace and erase the previous character.
$ cat T.java
import java.lang.Thread;
public class T {
public static void main(String... args) throws Exception {
System.out.print("H");
System.out.flush();
Thread.sleep(1000);
System.out.print("\bI\n");
System.out.flush();
}
}
$ javac T.java && java T
I
It will output H, then replace it with I after one second.
Sadly, it doesn't work in Eclipse console, but in normal console it does.
This is what you need (uses carriage return '\r' to overwrite the previous output):
System.out.print("H");
Thread.sleep(1000);
System.out.print("\rI");
The C library that is usually used to do this sort of thing is called curses. (Also used from scripting languages that rely on bindings to C libraries, like Python.) You can use a Java binding to it, like JCurses. Google also tells me a pure-Java equivalent is available, called lanterna.
Total Java noob, I need to figure out how to capture string entered as an argument for one method in order to reuse it later.
Basically, here I pass String content as a label when creating buttons:
public void start() {
// set up the label for one button
viewer.setButtonLabel(1, "");
viewer.setButtonLabel(2, "");
viewer.setButtonLabel(3, "");
// start the viewer
viewer.open();
}
Then I want to reuse the string I've given as the button label as the keywords for a search in the next method, taking into account which button was pressed:
public void buttonPressed(int n) {
// fetch an image of the Forum from Flickr
Photo photo = finder.find("", 5);
}
I feel I'm making this much harder than it has to be but I'm totally new to Java and can't seem to find what I'm looking for.
Would really appreciate any tips you may have.
String buttonLabel1 = "Blah blah blah";
viewer.setButtonLabel(1, buttonLabel1);
Next Method
blahMethod(buttonLabel1);
This is one way of doing this, but probably the easiest to see. You can get a bit more complicated by storing all your button labels into a list instead (which will make your code look cleaner), but since you are new, I suggest you try it this way. Eventually, to make your code dynamic (ex. If I select the 4th button, get the 4th label), you will have to use some sort of data structure to avoid from getting extremely sloppy/messy.
You also can probably "get" the label of the button in order to retrieve the same string value.