java char array to String with spaces - java

I'm trying something like a crossword puzzle. in a 5 by 5 grid.
25 of them have different letters in them, 1 is the submit button. So whenever i hit the submit button. It will do something like this. str is the word that i retrieve from a text file, and guess is the char array.
if (count == str.length())
{
String a = String.copyValueOf(guess);
a= a.replaceAll("\\s+$", "");
if (str.equals(a))
{
JOptionPane.showMessageDialog(null, "Correct! Well Done!");
score += 10;
totalScore.setText ("Score: " + score);
}
else
JOptionPane.showMessageDialog(null, "Please try again");
the thing is, whether the answer is correct or not, it will only display "please try again". It can work if i change my array size to [5], but if it goes out of bound if i click 6 buttons. Anyone can tell me what's wrong with this?
edit: i added a messageDialog, and it display jump with tons of spaces at the back
JOptionPane.showMessageDialog(null, "|" + a + "|" + str + "|");
Changing it to
a= a.replace(" ", "");
doesn't work too.

Use trim() function. The easiest method to trim spaces from a string.

Related

Android check if string contains number before a word

I am currently using an arraylist to store some text and then later checking that list to see if it contains certain words and parsing them for the numbers. For example my arraylist could contain:
[cancel, port, 4.5, 3 min, 3/4 terminal]
And I want to parse the 3 min to get the number 3. I currently use:
for (int i = 0; i < textArray.size(); i++) {
if (textList.contains("min")
number = Double.parseDouble(textList.get(i).replaceAll("[^0-9]", ""));
}
But the issue I am having is that it will see the 3 min and it will also see the 3/4 terminal because it contains min. Is there a way to use contains to make sure the word is exactly min?
Instead of contains() use endsWith():
if (textList.endsWith(" min") {
number = Double.parseDouble(textList.get(i).replaceAll("[^0-9]", ""));
}
How about checking if the string starts with a number and then checking if that string has an exact match for the word min?
String[] strValues = {
"cancel",
"port",
"4.5",
"3 min",
"3/4 terminal"
};
for(String str : strValues){
if(str.matches("^[0-9].*$"))
System.out.println(str + " starts with a number");
String[] results = str.split("\\s+");
Boolean matchFound = Arrays.asList(results).contains("min");
System.out.println(str + " is a number that contains a the word min");
else
System.out.println(str + " does not start with a number");
}
Code is untested but it should give you what you asked for which was to use contains.
There are better ways though as others have answered

Java. word positioning in a string

I am currently programming java and have been asked to develop a program that analyses a sentence that contains several words without punctuation. when a word in that sentence is input, the program identifies all of the positions where that word occurs in that string..
String example:
ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU, ASK WHAT YOU CAN DO FOR YOUR COUNTRY.
Code:
String Scan_word;
Scan_word = JOptionPane.showInputDialog("Word to be scanned for");
String Full_Scan;
Full_Scan = "You have entered " + Scan_word + " "; // the input dialog box will display this when a word is inputted
String sentence = "Ask not what your country should do for you but what you should do for you country"; //The sentence
JOptionPane.showMessageDialog(null, Full_Scan);
if (sentence.contains(Scan_word)); {
String[] sentenceWords = sentence.split(" ");
for (int i = 0; i < sentenceWords.length; i++) {
if (sentenceWords[i].equals(Scan_word)); {
} System.out.println(Scan_word + " is located in the: " + i + "th position");
}
ALL code is in Static void section as should be.
SORRY IT HAS CODING COMMENTS.
PLS ignore the CAQ1STOPBLOCKINGTHEM title as my netbeans projects were being locked for no reason or another.
Your bug seems to be related to your if that is not properly written, indeed you put a semicolon just after it meaning that there no instruction to launch, moreover you print your message outside the curly brackets and finally you should print the value of i + 1 not i since it starts from 0, so your code should rather be:
if (sentenceWords[i].equals(Scan_word)) {
System.out.println(Scan_word + " is located in the: " + (i + 1) + "th position");
}
Consider reading some articles about the naming conventions in java like this one for example. In a nutshell, a varaiable name should start with a lower case.

Having trouble with Java GUI String formatting in JList

I am making a homework planner GUI program in Java. One GUI takes in data from the user about the assignment, determines priority for the order the homework should be done in, then allows the user to view their schedule as another GUI that displays all their assignments in the appropriate days of the week that they will work on them.
My problem is that I can't get the Strings to format correctly in the JLists. See here:
I'm filling the JLists with String representations of Homework Objects from a PriorityQueue, like this:
while(!sun.isEmpty())
sundayListItems.add(sunday.poll().toString());
.
.
.
sundayList = new JList(sundayListItems.toArray());
My toString method in my Homework class looks like this, which works as it's supposed to in the console when I put in System.out.prints to see how it's working:
String string = nameOfAssignment + " for " + hoursPerDay +" hours";
if (string.length()>17) {//17 characters per line in this JList
String[] words = string.split(" ");
string = "";
int count = words.length;
int i = 0;
while(count>0) {
do{
string += words[i] + " "; //adding words to a line until 17 characters
i++;
count--;
} while(string.length() <= 17);
string += "\n";//skips line when 17 characters
do{
string += words[i] + " ";
count--;
i++;
} while(i < words.length);
string += "\n\n";//separates assignments w/ 2 lines
}
}
return string;
But, in the GUI JLists, the Strings are not formatting the way I want. I want the String to wrap around to the next line after 17 characters. Anyone have any ideas?

Can't get out of my while loop

I was wondering if someone can tell me why my while loop is acting funny. When I input a 3 word phrase it should create an acronym. For a reason beyond my java understanding the while loop executes but then keeps executing even when the client inputs the right answer. Any idea why? I have read what seems million posts and watch youtube videos about it, but no clue.
import javax.swing.*;
import java.util.*;
public class ThreeLetterAcronym
{
public static void main(String args[])
{
//variables
String phrase;
int wordCount;
String acronym;
//input
phrase = JOptionPane.showInputDialog(null, "Please enter a three word phrase.");
String [] word = phrase.split("\\s+");
wordCount = word.length;
//loop for error when less than 3 words
do
{
JOptionPane.showMessageDialog(null, "Error, you need to input a 3 word phrase to create a 3 letter acronym." + '\n'
+ "Please try again.");
phrase = JOptionPane.showInputDialog(null, "Please enter a three word phrase");
}
while(wordCount !=3);
//create acronym
acronym = Character.toString(word[0].charAt(0)).toUpperCase() +
Character.toString(word[1].charAt(0)).toUpperCase() +
Character.toString(word[2].charAt(0)).toUpperCase();
//output
JOptionPane.showMessageDialog(null, "The phrase you inputed is " + "."
+ phrase + "\nYour 3 letter acronym is " + acronym + ".");
}
}
enter code here
Your loop will fail if the user types 4 or more words. Change wordCount != 3 to wordCount < 3 or be ready to handle longer phrases like North Atlantic Treaty Organization.
A do-while loop always executes at least once. Here, where you are checking for errors, that's actually reasonable, but you are also never recalculating your word array, so the error condition persists. You want logic like:
String[] words; // words, not word. There is more than one.
while (true) {
// 1. Fill in the word array from the user's input.
// 2. Check the input for errors.
// a. If there are none, break out of the loop with a break statement.
// b. Otherwise, show the error message.
}
// Create the acronym. Try to use a loop for this too, as in:
StringBuilder acronym = new StringBuilder();
for (String word: words) {
// Append to acronym.
}
// report acronym.
Finally, try not to do all your work in main. Create a ThreeLetterAcronym object, give it instance variables and methods, and tell it to do the work. Break up the work in main into smaller methods. Now, you can test those methods.
Your loop is executing after entering a three-word phrase because, as Eric mentioned, a 'do-while' loop will always execute at least once. The best, simple solution to resolve that issue would be to use a while loop instead, as follows:
while(wordCount != 3)
{
JOptionPane.showMessageDialog(null, "Error, you need to input a 3 word phrase to create a 3 letter acronym." + '\n'
phrase = JOptionPane.showInputDialog(null, "Please enter a three word phrase");enter code here
}
A do-while loop performs an action and then checks if it should perform that action again. A while loop checks if it should perform an action first, which is what you want to be doing.
There are also some other significant issues that would be worth resolving at the same time.
Your variables word and wordCount are not being updated once the program enters your do-while loop. If a user first enters a three-word phrase, they're fine. If they enter a phrase of any other length the program will loop indefinitely. Since the program is executing the logic inside the do-while loop only, and that does not include saving new words into the variable word or figuring their length an dstoring it in wordCount, there is no way to exit the loop.
As a quick fix I added these two lines to solve those issues:
word = phrase.split("\\s+");
wordCount = word.length;
You could also eliminate the wordCount variable entirely by checking, but I'm honestly not sure if there's value in doing that versus having the variable in use. phrase.split("\\s+").length in the while loop.
Your main problem is that your loop will never terminate; wordCount is not being updated inside of your do...while block.
Your next problem is that a do...while loop always runs at least once.
What you can do to fix this issue is move another instantiation of word into your loop body, remove the unnecessary wordCount variable (since it's a property of the array, and we only need it in one spot), and change your do...while to a while.
//input
phrase = JOptionPane.showInputDialog(null, "Please enter a three word phrase.");
String[] word = phrase.split("\\s+");
//loop for error when less than 3 words
while(word.length < 3) {
JOptionPane.showMessageDialog(null, "Error, you need to input a 3 word phrase to create a 3 letter acronym." + '\n'
+ "Please try again.");
phrase = JOptionPane.showInputDialog(null, "Please enter a three word phrase");
word = phrase.split("\\s+");
}
Solved
use this code -
import javax.swing.*;
public class ThreeLetterAcronym
{
public static void main(String args[])
{
//variables
String phrase;
int wordCount;
String acronym;
//input
phrase = JOptionPane.showInputDialog(null, "Please enter a three word phrase.");
String [] word = phrase.split(" ");
wordCount = word.length;
//loop for error when other than 3 words
while(wordCount!=3)
{
JOptionPane.showMessageDialog(null, "Error, you need to input a 3 word phrase to create a 3 letter acronym." + '\n'
+ "Please try again.");
phrase = JOptionPane.showInputDialog(null, "Please enter a three word phrase");
}
//create acronym
acronym = Character.toString(word[0].charAt(0)).toUpperCase() +
Character.toString(word[1].charAt(0)).toUpperCase() +
Character.toString(word[2].charAt(0)).toUpperCase();
//output
JOptionPane.showMessageDialog(null, "The phrase you inputed is " + "."
+ phrase + "\nYour 3 letter acronym is " + acronym + ".");
}
}

Using JOptionPane

if i was using a JOptionPane message dialog box how would I be able to show an the whole array in the message section such as this little snipit? or would that evenbe possible?
public void showTheMessage()
{
JOptionPane.showMessageDialog(null,"These are are all the colors to
choosfrom,\n"+ arrayOfcolors[the whole array], "Color box");
}
The easiest thing to do would be to concatenate all the elements of the array into one big string.
String colors = "";
for(int i = 0; i < arrayOfColors.length; i++)
colors += arrayOfColors[i] + " ";
The showOptionDialog method lets the user select a single element from an array of options, which I think is what you're looking for.
In case its an array of Color objects
String colors="";
for (Color c: arrayOfColors)
colors+= c.toString() + " ";
Otherwise if its an array of String objects
String colors="";
for (String s: arrayOfColors)
colors+= s + " ";
Just a note, using StringBuilder is much faster, but this is just a small array i guess.

Categories

Resources