Trying to update the content of a JLabel - java

I'm back again with a simpler question! I'd like the content of this JLabel (triedLettersLA) to update periodically throughout the application (I have that part handled).
But I'd like to ADD text to the label. NOT rewrite it entirely. For example.. If the text said "Letters Tried: ", I'd want to add "N", and "X", and then "H" on three separate occasions. So at the end, it'd look like this "Letters Tried: N X H". Here's what I have, and it's totally not working..
This is way up top,
JLabel triedLettersLA = new JLabel("Tried letters:");
public boolean used[] = new boolean[26];
And this is lower down in my code..
StringBuffer missedLetter = new StringBuffer();
for (int le = 0; le <= 25; le++) {
if (used[le]) missedLetter.append((char)(le + 'a'));
String triedLettersLA.getText(t);
triedLettersLA.setText(t + " " + missedLetter.toString());
}

The code you posted makes no sense (nor could it ever compile). Well, it would compile now, possibly.
That being said, a String in Java is immutable; you can't change it. To change the text of a JLabel you need to create a new String and call the JLabel's setText() method.
String old = triedLettersLA.getText();
String newString = old + " N"; // this creates a new String object
triedLettersLA.setText(newString);

Nonsence code:
String triedLettersLA.getText(t);
Change it to:
String t = triedLettersLA.getText();

Related

How to find a specific occurrence of a string inside of a string

The problem is this, I'm trying to find and get only one occurrence of a string, when the only way I can get one is by using a keyword that occurs multiple times.
Ex. 4 potato, 4 (string I want), 4 house, 4 car
How do I only get the string I want, when I can't type in any keywords that the string might contain.
Imagine it as trying to take only one paragraph out of an essay.
I've tried the stringy.replaceAll(Str1, Str2); variable, but to no avail. All that happens is I replace all of the string (go figure with a name like replace all)
package com.donovan.cunningham;
import java.util.ArrayList;
import java.util.Random;
public class EssayCreator {
//Creating varz
private static String[] lf = {"happy", "sad", "unhappy", "atractive",
"fast", "lazy"};
private static String[] op = {"estatic", "melhencohly", "depressed",
"alluring", "swift", "lackadaisical"};
private static String pF = " ";
private static String temp[];
private static String conv = " ";
private static String comm = ", ";
private static Random random = new Random();
private ArrayList<String> array = new ArrayList<String>();
public static void Converter(String in) {
in = in.replace(comm, conv);
for (int i = 0; i < lf.length; i++){
in = in.replace(lf[i], op[i]);
}
in = in.replace(conv, comm);
//int rand = random.nextInt(in.indexOf(pF));
for (int i = 0; i < in.indexOf(pF); i++){
/*
Where I want to get an exact string of an essay
I'd convert pF to conv, and then remove the paragraph to
change the order
} */
}
CreateGUI.output.setText(in);
Sound.stopSound();
}
}
Thanks
Your question is not very clear though. You want (1) to find the most occurrence string which you don't know or you want (2) to replace the occurrence string that you know?
The most naive way to do (1) is to chop your text by space and put them in a string-to-integer HashMap to calculate the most occurrence string. You can also scan this HashMap to find all the N-occurence strings
For (2), supposed that you already know which key string you want to find, you can apply indexOf(String str, int fromIndex) in String recursively as followed:
int occurenceCount = 0;
String input = "Here is your text with key_word1, key_word2, ...etc";
StringBuffer output = new StringBuffer();
int index = input.indexOf("key_word");
int copiedIndex = 0;
for(index>0)
{
output.append(input.substring(copiedIndex, index));
occurenceCount++;
if(occurenceCount==4) //Find 4th occurrence and replaced it with "new_key_word"
{
output.append("new_key_word")
}
else
{
output.append("key_word")
}
copiedIndex = index+("key_word".length);
index = input.indexOf("key_word", index+("key_word".length));
if(index==-1)
break;
}
Ref: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)
Not sure if I had answered your question though...
I've combed through your code and tried running it with a use case I made from the cryptic info you've given. As folks above are saying, it's not clear what you're trying to accomplish. Typically regex is your friend when trying to do more complex string pattern matching if String's built in methods are not enough. Try googling 'pattern match string in paragraph regex java' or something to that effect. Meanwhile, I've added some comments to your code which might help with making this question more clear. Happy to help if I can better understand what you're trying to do. See code and comments below:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class EssayCreator {
// Creating varz
private static String[] lf = { "happy", "sad", "unhappy", "atractive",
"fast", "lazy" };
private static String[] op = { "estatic", "melhencohly", "depressed",
"alluring", "swift", "lackadaisical" };
private static String pF = " ";
private static String temp[];
private static String conv = " ";
private static String comm = ", ";
private static Random random = new Random();
private List<String> array = new ArrayList<String>();
// Bradley D: Just some side notes here:
// Don't capitalize method names and don't use nouns.
// They're not class names or constructors. Changed Converter to convert. It'd also be good to
// stipulate what you are converting, i.e. convertMyString to make this a
// little more intuitive
public static void convert(String in) {
/*
* Bradley D: First, you are replacing all commas following by a space
* with 3 spaces. Be good to know why you doin that?
*/
in = in.replace(comm, conv);
for (int i = 0; i < lf.length; i++) {
in = in.replace(lf[i], op[i]);
}
/*
* Bradley D: Now you are replacing the 3 spaces with a comma and a
* space again??
*/
in = in.replace(conv, comm);
// Bradley D: Not really sure what you are trying to iterate through
// here. in.indexOf(pF) is -1
// for the use case I've created for you with the text below (what did I
// miss?)...
// Perhaps you're trying to find the first place in your essay where pF
// (3 spaces) occurs....
// but you've already reconverted your 3 spaces back to a comma and
// single space, so I'm getting even more lost here....
// int rand = random.nextInt(in.indexOf(pF));
for (int i = 0; i < in.indexOf(pF); i++) {
/*
* Bradley D: What is pF?? It appears to be the same as comm...
*/
/*
* Where I want to get an exact string of an essay I'd convert pF to
* conv, and then remove the paragraph to change the order }
*/
// Bradley D: Ok, so if you can make this question clear, I'll give it a shot here
}
// Bradley D: Commenting this out since it was not included
// CreateGUI.output.setText(in);
// Sound.stopSound();
}
public static void main(String[] args) {
EssayCreator ec = new EssayCreator();
String essay = "Let's see if we find the desired string in here. "
+ "Are we happy? Nope, we're not happy. Who's happy? What does happiness mean anyway? "
+ "I'd be very happy if this question we're more clear, but let's give it a go anyway. Maybe "
+ "we're lazy, and that's not attractive, thus rendering us unhappy and lackadasical... jk! "
+ "So hey man... why are you replacing all of the commas with spaces? "
+ "Can you put comments in your code? What is pF? "
+ "Also you should not capitalize method names. They should be in camelCase and they should not "
+ "be nouns like Converter, which makes them look like a constructor. Methods represent "
+ "an action taken, so a verb to describe them is standard practice. "
+ "So use convert, but what are you converting? convertString?? convertWords? "
+ "Anyway, making your method names intuitive would be helpful to anyone trying to understand "
+ "the code.";
ec.convert(essay);
}
}

How do I format text within a JList?

I have items in a JList that I can't get to format correctly.
I've created this method in order to do so:
private String formatString(String string){
string = string.trim();
int SEPERATOR = 20 - string.length();
for(int i = 0; i<SEPERATOR; i++){
string = string + " ";
}
return string;
}
When I output the items in my JList into the output window using a system out print it formats fine, but in my GUI it does not:
I'm not sure if this will help you help me better but here is how I am loading my data into the list:
DefaultListModel m = new DefaultListModel();
while (rs.next()){
String Expense = rs.getString("Expense");
String Cost = "£"+rs.getString("Cost");
String PurchaseDate = rs.getString("Purchase_Date");
String Description = rs.getString("Description");
Expense = formatString(Expense);
Cost = formatString(Cost);
PurchaseDate = formatString(PurchaseDate);
Description = formatString(Description);
String Row = Expense+Cost+PurchaseDate+Description;
m.addElement(Row);
System.out.println(Row);
}
The best solution, as has already been suggested, is to use a JTable. Read the section from the Swing tutorial on How to Use Tables for more information and working examples.
When i output the items in my jlist into the output window using a system out print it formats fine, but in my GUI it does not:
To answer your question you need to use a monospaced font.
list.setFont( new Font("monospaced", Font.PLAIN, 10) );
Also, use standard Java variable names. Variable name (Expense, Cost...) should NOT start with an upper case character.
You can use \t (you might have to use /t/t if the the text of a field is too long) instead of using spaces OR use a JTable

Separate Multiple Integers from a String

I've got a question about making a save function.
I'm trying to have a string be saved as a single file to set specific settings on a game. So saveFile would read "002007...", having 002 be a player's location, then 007 a player's level, for example.
I understand how to compile the various variables into a single string, but how would I return it to individual variables?
You better go with SQLite or SharedPreferences if you really want to save settings for a game on Android.
On the other hand, if you have to stick with saving a String on a file, you might want to use a delimiter(ie \r\n or # or | would do it) between numbers. So while parsing back delimiters will help you a lot, but beware when things get complicated a single String won't do the thing nicely. Then you might want to use JSON (for simplicity I would prefer gson) to encode your settings into one String and vice verse.
You could use a delimiter between the values like this:
int location = 02;
int level = 3;
int powerUps = 46;
... and so on
String saveString = location + "#" + level + "#" + powerUps + "#" + ...
Then to load the String back into variables:
String[] values = saveString.split("#");
location = values[0];
level = values[1];
powerUps = values[2];
... and so on
My advice is to check out Shared Preferences and you can read Android's documentation on it here.
If you did want to use your single String, file method, I suggest using delimiters. That simply means to put commas, or other types of delimeters in between different integer values. Instead of "002007", save it as "002,007". Example:
String s = "002,007"
String[] values = s.split(","); // values[0] is "002" and values[1] is "007"
Using the .split(String) command will return a String array with each element in the array containing parts of the String that was split up by the parameter, in this case: ,
If you wanted to separate values per person, something like this could be done:
String s = "002,007;003,008";
String[] people = s.split(";"); // people[0] is "002,007", people[1] is "003,004"
String[][] person = new String[people.length][people[0].split(",").length];
for (int i = 0; i < people.length; i++)
{
person[i] = people[i].split(",");
}
Here is what the array would then contain:
person[0][0] is "002"person[0][1] is "007" person[1][0] is "003" person[1][1] is "008"
// print it for your own testing
for (String ppl[] : person)
{
for (String val : ppl)
{
System.out.print(val + " ");
}
System.out.println("");
}

Issue in Combining splitted String

I have extracted text from "web 2.0 wikipedia" article, and splitted it into "sentences". After that, I am going to create "Strings" which each string containing 5 sentences.
When extracted, the text looks like below, in EditText
Below is my code
finalText = textField.getText().toString();
String[] textArrayWithFullStop = finalText.split("\\. ");
String colelctionOfFiveSentences = "";
List<String>textCollection = new ArrayList<String>();
for(int i=0;i<textArrayWithFullStop.length;i++)
{
colelctionOfFiveSentences = colelctionOfFiveSentences + textArrayWithFullStop[i];
if( (i%5==0) )
{
textCollection.add(colelctionOfFiveSentences);
colelctionOfFiveSentences = "";
}
}
But, when I use the Toast to display the text, here what is gives
Toast.makeText(Talk.this, textCollection.get(0), Toast.LENGTH_LONG).show();
As you can see, this is only one sentence! But I expected it to have 5 sentences!
And the other thing is, the second sentence is starting from somewhere else. Here how I have extracted it into Toast
Toast.makeText(Talk.this, textCollection.get(1), Toast.LENGTH_LONG).show();
This make no sense to me! How can I properly split the text into sentences and, create Strings containing 5 sentences each?
The problem is that for the first sentence, 0 % 5 = 0, so it is being added to the array list immediately. You should use another counter instead of mod.
finalText = textField.getText().toString();
String[] textArrayWithFullStop = finalText.split("\\. ");
String colelctionOfFiveSentences = "";
int sentenceAdded = 0;
List<String>textCollection = new ArrayList<String>();
for(int i=0;i<textArrayWithFullStop.length;i++)
{
colelctionOfFiveSentences += textArrayWithFullStop[i] + ". ";
sentenceAdded++;
if(sentenceAdded == 5)
{
textCollection.add(colelctionOfFiveSentences);
colelctionOfFiveSentences = "";
sentenceAdded = 0;
}
}
add ". " to textArrayWithFullStop[i]
colelctionOfFiveSentences = colelctionOfFiveSentences + textArrayWithFullStop[i]+". ";
I believe that if you modify the mod line to this:
if(i%5==4)
you will have what you need.
You probably realize this, but there are other reasons why someone might use a ". ", that doesn't actually end a sentence, for instance
I spoke to John and he said... "I went to the store.
Then I went to the Tennis courts.",
and I don't believe he was telling the truth because
1. Why would someone go to play tennis after going to the store and
2. John has no legs!
I had to ask, am I going to let him get away with these lies?
That's two sentences that don't end with a period and would mislead your code into thinking it's 5 sentences broken up at entirely the wrong places, so this approach is really fraught with problems. However, as an exercise in splitting strings, I guess it's as good as any other.
As a side problem(splitting sentences) solution I would suggest to start with this regexp
string.split(".(\\[[0-9\\[\\]]+\\])? ")
And for main problem may be you could use copyOfRange()

Replace char at specific substring

first of all I want to say that I am kinda new to Java. So please be easy on me :)
I made this code, but I cannot find a way to change a character at a certain substring in my progress bar. What I want to do is this:
My progressbar is made out of 62 characters (including |). I want the 50th character to be changed into the letter B (uppercase).It should look something like this: |#########----B--|
I tried several things, but I dont know where to put the line of code to make this work. I tried using the substring and the replace code, but I can't find a way to make this work. Maybe I need to write my code in a different way to make this work? I hope someone can help me.
Thanks in advance!
int ecttotal = ectcourse1+ectcourse2+ectcourse3+ectcourse4+ectcourse5+ectcourse6+ectcourse7;
int ectmax = 60;
int ectavg = ectmax - ecttotal;
//Progressbar
int MAX_ROWS = 1;
for (int row = 1; row == MAX_ROWS; row++)
{
System.out.print("|");
for (int hash = 1; hash <= ecttotal; hash++)
System.out.print ("#");
for (int hyphen = 1; hyphen <= ectavg; hyphen++)
System.out.print ("-");
System.out.print("|");
}
System.out.println("");
System.out.println("");
}
Can you tell a little more what you want. Because what i sea it that, that you write some string into console. And is not way to change that what you already print to console.
Substring you can use only at String varibles.
If you want to change lettir with substring method in string varible try smth. like this:
String a="thi is long string try it";
if(a.length()>50){
a=a.substring(0,49)+"B"+a.substring(51);
}
Other way to change charater in string is to use string builder like this:
StringBuilder a= new StringBuilder("thi is long string try it");
a.setCharAt(50, 'B');
Sure you must first check the length of string to avoid the exceptions.
I hope that I helped you :)
Java StringBuilder has method setCharAt which can replace character at position with new character.
StringBuilder myName = new StringBuilder(<original string>);
myName.setCharAt(<position>, <character to replace>);
<position> starts with index 0
In your case:
StringBuilder myName = new StringBuilder("big longgggg string");
myName.setCharAt(50, 'B');
You can replace a certain index in a string by concatenating a new string around the intended index. For example the following code replaces the letter c with the letter X. Where 2 is the intended index to replace.
In other words, this code replaces the 3rd character in the string.
String s = "abcde";
s = s.substring(0, 2) + "X" + s.substring(3);
System.out.println(s);

Categories