Converting JTextField to an int array with exceptions - java

So I've been trying to figure this out but to no avail. I have to convert JTextField to an int array while having two exceptions, NumberFormatException, and ArrayIndexOutOfBoundsException. I was able to find a method to convert it, but it wont throw the NumberFormatException when I enter letters.
try {
int j=0;
String str = "" + numbersField.getText();
char digit[] = str.toCharArray();
for (int i=0; i<digit.length; i++) {
if (Character.isDigit(digit[i])) {
array[j]=Character.getNumericValue(digit[i]);
System.out.print(array[j] + " "); //Checking if it works
++j;
}
}
} catch (NumberFormatException e1) {
System.err.println("NumberFormatException: Array can only hold integers");
} catch (ArrayIndexOutOfBoundsException e1) {
System.err.println("ArrayIndexOutOfBoundsException: Array can only hold up to 10 elements");
}
Personally, I believe it's not throwing the NumberFormatException because it converts JTextField to char, but I could be totally wrong. Any help is appreciated.
EDIT: I only included part of the program since it's kinda lengthy in my opinion. Array is initialized way before this. The ultimate goal of this portion of the program is to have the user input a limit of 10 numbers while throwing an exception if a letter is inputted or if it exceeds 10 numbers. This is my first time using exceptions so I'm still relatively new to it, so please excuse me for any mistakes I've done.

You can check if whole text has only digits, then convert text to int and then put all digits to array.
Try an alternative:
String str = numbersField.getText();
try {
int value = Integer.parseInt(str);
int[] array = new int[str.lenght - 1];
j = array.length - 1;
while (value > 0) {
array[j] = value % 10;
value /= 10;
--j;
}
} catch (NumberFormatException ex) {
System.out.println("Enter only digits!")
}
UPD: also you need to check if value < 0 and show an error (if you don't accept minus sign) and use str.trim() before converting to int

Hmmm well maybe this could help, maybe not the most efficient but does its job:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class JTextFieldIntToArrayValidation extends JFrame {
private int[] integerArray;
private JButton button;
private JTextField tf;
public JTextFieldIntToArrayValidation() {
createAndShowUI();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JTextFieldIntToArrayValidation test = new JTextFieldIntToArrayValidation();
test.setVisible(true);
}
});
}
private void createAndShowUI() {
setTitle("Converting JTextField to an int array with exceptions");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addComponentsToPane();
addListeners();
pack();
tf.grabFocus();
}
private void addComponentsToPane() {
button = new JButton("Convert JTextfield to array");
tf = new JTextField(10);
getContentPane().add(tf, BorderLayout.EAST);
getContentPane().add(button, BorderLayout.WEST);
}
private void addListeners() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String tmp = tf.getText();
char[] chars = tmp.toCharArray();
integerArray = new int[chars.length];
try {
if (integerArray.length > 10) {//if digits entered are greater then 10. This however only allows for single digits!!!
throw new ArrayIndexOutOfBoundsException("Array cannot be larger then 10: " + integerArray.length);
}
for (int i = 0; i < tmp.length(); i++) {
if (!Character.isLetter(chars[i])) {//if its not a letter
integerArray[i] = Integer.parseInt(chars[i] + "");//stops java handling chars as ints
} else {//its a letter
throw new NumberFormatException("Only valid integers must be entered no letters: " + chars[i]);
}
}
printArray();
} catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) {
JOptionPane.showMessageDialog(getContentPane(), ex.getMessage());
}
}
});
}
private void printArray() {
for (int i : integerArray) {
System.out.println(i);
}
}
}

Related

How to use JTextArea and Append

Please Help. When I run this GUI the numbers run off the frame. I know I have to use JTextArea and append but where do I put that in my code. can someone explain to me in simple terms and show me? I want to make it scroll vertically and horizontally and when I do add the JTextArea I get this error: error: cannot find symbol panel.setMessage(message);
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class prime extends JFrame
{
public static void main(String[] args)
{
prime frame = new prime();
}
private JTextArea panel;
private JPanel inPanel;
private JTextField inField;
public prime()
{
final int width = 500;
final int height = 500;
setSize(width, height);
setTitle("Find Prime Numbers");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JTextArea(20, 10);
add(new JScrollPane(panel), "Center");
inPanel = new JPanel();
inPanel.add(new JLabel("Enter Your Number", SwingConstants.RIGHT));
inField = new JTextField(20);
ActionListener inListener = new TextListener();
inField.addActionListener(inListener);
inPanel.add(inField);
add(inPanel, "South");
setVisible(true);
}
private class TextListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String message = inField.getText();
inField.setText("");
panel.setMessage(message);
}
}
class TextPanel extends JPanel
{
private String message;
private Color backGroundColor;
public TextPanel()
{
message = "";
backGroundColor = Color.white;
}
public TextPanel(String x, Color background)
{
message = x;
backGroundColor = background;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int width = getWidth();
int height = getHeight();
setBackground(backGroundColor);
g2.setColor(Color.black);
Font x = new Font("TimesNewRoman", Font.BOLD,20);
g2.setFont(x);
FontMetrics fm = g2.getFontMetrics(x);
g2.drawString(message,50, 50);
if(!(message.equals("")))
g2.drawString(previousPrime(message),50,78);
}
public void setMessage(String message) {
if (isPrime(Integer.parseInt(message))){
this.message = message + " is a prime number.";
}
else
this.message = message + " is not a prime number.";
repaint();
}
public boolean isPrime(int num){
for(int i = 2; i < num; i++){
if (num % i == 0)
return false;
}
if(num < 2)
return false;
return true;
}
public String previousPrime(String message){
String totalPrimeNum = "";
int finalNum = Integer.parseInt(message.substring(0,message.indexOf(" ")));
int count = 0;
for(int i = 2; i < finalNum; i++){
if(isPrime(i)) {
totalPrimeNum += " " + i;
count++;
}
if(count == 10) {
totalPrimeNum += "\n";
count = 0;
}
}
if (isPrime(Integer.parseInt(message.substring(0,message.indexOf(" ")))))
totalPrimeNum += " " + finalNum;
System.out.println(totalPrimeNum);
return totalPrimeNum;
}}}
Look at what you have and what you want to achieve. You have a method which can verify if a value is a prime or not, but it does not produce any output. You have a JTextArea which allows you to add content to it.
You have a square peg and a round hole. One of these things needs to change. You have control over the setMessage method, but you don't have control over the JTextArea, this would suggest that the setMessage needs to change. While you could pass the JTextArea to the setMessage method, a better solution would be to change the setMessage to return some kind of meaningful value or simply get rid of it in favor of using the isPrime method instead
Take your TestPane and move the functionality used to calculate and test for a prime number to a new class, for example...
public class PrimeCalculator {
public boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
if (num < 2) {
return false;
}
return true;
}
public String previousPrime(String message) {
StringBuilder totalPrimeNum = new StringBuilder(128);
int finalNum = Integer.parseInt(message.substring(0, message.indexOf(" ")));
int count = 0;
for (int i = 2; i < finalNum; i++) {
if (isPrime(i)) {
totalPrimeNum.append(" ").append(i);
count++;
}
if (count == 10) {
totalPrimeNum.append("\n");
count = 0;
}
}
if (isPrime(Integer.parseInt(message.substring(0, message.indexOf(" "))))) {
totalPrimeNum.append(" ").append(finalNum);
}
System.out.println(totalPrimeNum);
return totalPrimeNum.toString();
}
}
This now makes no assumptions over what you want to do and simply produces output. You can now use these methods and make decisions about how to use the output, for example...
private class TextListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
PrimeCalculator calc = new PrimeCalculator();
String message = inField.getText();
inField.setText("");
String text = message + " is not a prime number\n";
try {
if (calc.isPrime(Integer.parseInt(message))) {
text = message + " is a prime number\n";
}
} catch (NumberFormatException exp) {
text = message + " is not a valid integer\n";
}
panel.append(message);
panel.setCaretPosition(panel.getDocument().getLength());
}
}
Sometimes, you need to rethink your design to support what it is you want to achieve.
The process of verifying and calculating the prime numbers should do just that, they should not do anything else (like update the screen), this way you can decouple the code and re-use it in different ways which you didn't original think of (like outputting to a file or the web)
See How to Use Text Areas and How to Use Scroll Panes for more details

Change output after each run to one output after all runs

My program is pretty much all finished except for the output, I want it to display everything in one output rather than one after each run, it is supposed to run 500 times but made it only 10 until I have this problem fixed.
package assignment5;
import javax.swing.JOptionPane;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.text.*;
public class assignment5
{
public static void main(String[] args)
{
lottery pic=new lottery();for(int i = 0; i <10; i++)
{
pic.Get_player_numbers();
pic.Get_jackpot_number();
pic.Check_winner ();
pic.Write_data();
}
}
}
class lottery
{
int[] picks= new int[5];
int[] cpick=new int[5];
int i;
int j,c;
int match=0;
double matchcount0=0;
double matchcount1=0;
double matchcount2=0;
double matchcount3=0;
double matchcount4=0;
double matchcount5=0;
int jackpot = 25000000;
int payout;
void Get_player_numbers ()
{
int temp,dupflag=0;
for(i=0;i<=4;++i)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
dupflag=0;
while(dupflag==0)
{
temp = (int)Math.round(Math.random()*99)+1;
dupflag=1;
for(c=0;c<=i;++c)
{
if(temp==picks[c])
{
dupflag=0;
}
}//inner for loop
if(dupflag==1)
picks[i]=temp;
}
}
}
//void jackpot()
void Get_jackpot_number()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="Computer Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
}
void Check_winner ()
{
match=0;
for(int i=0;i<=4;++i)
{
for(int j=0;j<=4;++j)
{
if(picks[i]==cpick[j])
{
match=match+1;
}
}
}
}
void Write_data ()
{
if(match==0)
{
matchcount0=matchcount0+1;
payout=0;
jackpot=jackpot+25000;
}
else if(match==1)
{
matchcount1=matchcount1+1;
payout=100;
jackpot=jackpot+100000;
}
else if(match==2)
{
matchcount2=matchcount2+1;
jackpot=jackpot+250000;
payout=1000;
}
else if(match==3)
{
matchcount3=matchcount3+1;
jackpot=jackpot+500000;
payout=10000;
}
else if(match==4)
{
matchcount4=matchcount4+1;
jackpot=jackpot+1000000;
payout=100000;
}
else if(match==5)
{
matchcount5=matchcount5+1;
payout=jackpot;
jackpot=jackpot-jackpot+2500000;
}
System.out.println("Current Jackpot Player# Winner# #Matched Payout\n"+jackpot+" "+picks[0]+" "+picks[1]+" "+picks[2]+" "+picks[3]+" "+picks[4]+" "+cpick[0]+" "+cpick[1]+" "+cpick[2]+" "+cpick[3]+" "+cpick[4]+" "+match+" "+payout+"\nThe percent of plays where 0 numbers matched = "+matchcount0/i*100+"%\nThe percent of plays where 1 numbers matched = "+matchcount1/10+"%\nThe percent of plays where 2 numbers matched = "+matchcount2/10+"%\nThe percent of plays where 3 numbers matched = "+matchcount3/10+"%\nThe percent of plays where 4 numbers matched = "+matchcount4/10+"%\nThe percent of plays where 5 numbers matched = "+matchcount5/10+"%\n");
}
}
Use StringBuilder class. In each run you can just append new line two your StringBuilder instance.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; ++i) {
builder.append(System.getProperty("line.separator") + "Current Jackpot player...");
}
When everything is done you can use
builder.toString();
to get your output.

Adding data to a program if exist; else do generate random data in java

I have a math program that shows random math problems, when you click to see the next answer the next answer appears.
I have added a method which uploads a file called upload.txt
I want my program to run the math problems in this file instead of running the random
math problems if the file exist. If not I want the program to run the current way which is running the random math problems.
My current method for adding the text file is not 100 percent accurate.
I wont to just take the problems written in the file to be added. I got it working just uploading numbers to the command prompt by using code from another thread on StackOverflow.
random math problems class
import java.util.Random;
public class MathProblems {
private static final int MAX_NUMBER = 1000;
private static final Random random = new Random();
private double expected = 0;
private String question = "";
public void run() {
final int a = random.nextInt(MAX_NUMBER);
final int b = random.nextInt(MAX_NUMBER);
final int type = random.nextInt(4);
switch (type) {
case 0:
add(a, b);
break;
case 1:
subtract(a, b);
break;
case 2:
multiply(a, b);
break;
case 3:
divide(a, b);
break;
}
}
private void add(final int a, final int b) {
expected = a + b;
askQuestion(a + " + " + b + " = ");
}
private void subtract(final int a, final int b) {
expected = a - b;
askQuestion(a + " - " + b + " = ");
}
private void multiply(final int a, final int b) {
expected = a * b;
askQuestion(a + " * " + b + " = ");
}
private void divide(final int a, final int b) {
expected = (double)a / b;
askQuestion(a + " / " + b + " = ");
}
private void askQuestion(final String question) {
this.question = question;
}
public String getQuestion() {
return question;
}
#Override
public String toString(){
return Double.toString(expected);
}
}
Driver Class
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import javax.swing.*;
public class Driver extends MathProblems {
MathProblems problems = new MathProblems();
Scanner textfile;
String s = "Welcome Students!";
String b = "Start!";
private JFrame f;
private JPanel p;
JFrame frame = new JFrame();
JButton b1 = new JButton(b);
JLabel jl = new JLabel(s);
int i;
private int clicked;
public Driver() {
gui();
}
public void gui() {
f = new JFrame("Flash Card Program");
p = new JPanel();
f.setLayout(new GridLayout(2, 1));
f.add(jl);
f.add(p);
p.setLayout(new GridLayout(2, 1));
p.add(b1);
jl.setHorizontalAlignment(JLabel.CENTER);
// pack the frame for better cross platform support
f.pack();
// Make it visible
f.setVisible(true);
f.setSize(500, 400); // default size is 0,0
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (b1.getText().equals("Click For Answer")) {
jl.setText(problems.toString());
b = "Next Question";
b1.setText(b);
} else {
problems.run();
jl.setText(problems.getQuestion());
b = "Click For Answer";
b1.setText(b);
}
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (clicked++ == 10) {
Object[] options = { "No, thanks", "Yes, please" };
int response = JOptionPane.showOptionDialog(frame,
"Would you like more math questions? ",
"Math Questions", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[1]);
if (response == 1)
clicked = 0; // reset
else
System.exit(0);
}
}
});
}
static void filereader(Scanner textfile) {
int i = 0;
int sum = 0;
while(i <= 19)
{
int nextInt = textfile.nextInt();
System.out.println(nextInt);
sum = sum + nextInt;
i++;
}
}
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Driver();
Scanner textfile = null;
try {
textfile = new Scanner(new File("upload.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
filereader(textfile);
}
});
}
}
.txt file
1 + 1
2 + 2
3 + 3
4 + 4
5 + 5
6 + 6
7 + 7
8 + 8
9 + 9
10 + 10
You need to define a global vector of question values for each of a and b. A nicer way to do this is to define a class called "OneProblem" which has members for a, b, and op. You create a single 'Vector<OneProblem>' and as you read the file you create a OneProblem object for each line of the source. Then, at run time you either pick a random math problem, or loop through all the OneProblem objects, or you generate a completely random OneProblem from the random number generator. Something like:
class OneProblem {
public int a = 0;
public int b = 0;
public int op = 0;
public OneProblem(int _a, int _op, int _b) {
a =_a;
b = _b;
op = _op;
}
}
class MathProblems {
Vector<OneProblem> problems = new Vector<OneProblem>();
//...lot of your other code here as well....
workQuestion(OneProblem problem) {
switch (problem.op) {
case 0:
add(problem.a, problem.b);
break;
case 1:
subtract(problem.a, problem.b);
break;
case 2:
multiply(problem.a, problem.b);
break;
case 3:
divide(problem.a, problem.b);
break;
}
}
}
You file reader needs to read each line and parse the first and second values out of the line, as well as (I presume) the operand between them. Read the line, and search for the operand, and separate the integer before and the integer after. Then as you read each line, construct an instance of OneProblem to match each line. Now you are set to run.
When presenting the math questions, you loop through the values from i=0 to i<problems.size(). If there was no file read, those vectors will have no entries and so it will fall through. After you finish the vectors, or if the vectors are empty, present math questions with random values.
if (problems.size()>0) {
for (int i=0; i<problems.size(); i++) {
OneProblem selProblem = problems.get(i);
workQuestion(selProblem);
}
}
else {
workQuestion(new OneProblem({{random a}}, {{random op}}, {{random b}}));
}
Fill in the appropriate method for 'askQuestion'. This is represented above as a loop, but maybe you want to pick a random one of the test values for presentation? Then pick a reasonable random value for i in that range, and get the problem out of the vectors.
In your filereader method, you have this line, in a loop:
int nextInt = textfile.nextInt();
But the sample text that you show contains '+' characters between your numbers, and I see no code present to take that into account.
To fix, you can either define '+' as a delimiter on your Scanner object, or make sure your loop reads it as a string.

accept only a single digit in java

I am writing a simple program that takes multiple inputs and displays the largest then second largest. My only problem is that I want the program to accept only single digits. I know this goes back to basics, but bear with me. The code I have written so far is:
import javax.swing.JOptionPane;
public class Largest
{
public static void main (String args[])
{
/*Set variables and include a while function to force the program to take
* ten numbers before proceeding to the rest of the program. */
int counter = 0;
int number = 0;
int largest = 0;
int second = 0;
while (counter < 10)
{
// Set the counter
counter++;
//Input integer, set the largest number as the first output
number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
if (number >= largest) {
largest=number;
} else if (number >= second && number <= largest) {
// Set the second largest integer as the output
second=number;
}
}
//Display the largest number, followed by the second largest number
System.out.println("Largest number input: " + largest);
System.out.println("Second largest input: " + second);
System.exit(0); //terminate the application
} //end method main
} //end class
For this type of problem, personally, I would use a DocumentFilter
It allows you to restrict the type of characters coming into the field as well as the number of characters.
public class RestrictInput {
public static void main(String[] args) {
new RestrictInput();
}
public RestrictInput() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(2);
field.setHorizontalAlignment(JTextField.RIGHT);
((AbstractDocument) field.getDocument()).setDocumentFilter(new RestrictFilter());
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JLabel("Please enter a integer:"), gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
panel.add(field, gbc);
int result = JOptionPane.showConfirmDialog(null, panel, "Input", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println("Use entered " + field.getText());
}
}
});
}
public class RestrictFilter extends DocumentFilter {
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
if (currentText.startsWith("-") || text.equals("-") || fb.getDocument().getLength() < 1) {
String value = text.substring(0, 1);
if (value.equals("-")) {
if (currentText.startsWith("-")) {
super.remove(fb, 0, 1);
} else {
super.insertString(fb, 0, value, attr);
}
} else if (fb.getDocument().getLength() < 2 && (value.equals("-") || Character.isDigit(value.charAt(0)))) {
super.insertString(fb, offset, value, attr);
}
}
}
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
}
Check out MDP's Weblog and Text Component Features, in particular the section of Implementing a Document Filter
//Set the counter
counter++;
while (true) {
//Input integer, set the largest number as the first output
number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
if (number < 10 && number > -10) break; //If it's one digit, it's OK
JOptionPane.showMessageDialog(null, "Enter only one digit",
"Too many digits", JOptionPane.ERROR_MESSAGE);
}
What this does is start an infinite loop. If the number is only one digit, it will end the loop and continue on. Otherwise, it will start from the beginning of the loop again and ask for a valid number.
Just use a custom JOptionDialog where you restricted the JTextField to 1 char width.

Counting the number of words in a text area

Hello everyone my first question on stack overflow
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
public class TI extends JFrame implements ActionListener
{
static int count=0;
String ct;
JTextField word;
JTextArea tohide;
public static void main(String arg[])
{
TI ti=new TI();
}
public TI()
{
JPanel j=new JPanel();
JLabel def=new JLabel("Enter the text to be encrypted");
word=new JTextField("",20);
tohide=new JTextArea("",5,20);
JButton jb=new JButton("COUNT");
tohide.setBorder(BorderFactory.createLoweredBevelBorder());
j.add(def);
j.add(tohide);
j.add(word);
j.add(jb);
add(j);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
jb.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String txt=tohide.getText();
StringTokenizer stk=new StringTokenizer(txt," ");
while(stk.hasMoreTokens())
{
String token=stk.nextToken();
count++;
}
ct=Integer.toString(count);;
word.setText(ct);
}
}
I want to count the number of words that are being typed in the textarea.There is a logical error.As I keep clicking the count button the word count increases.
You never reset the count to 0 before recalculating the number of words. There doesn't seem to be a need for count to be a class variable. Making that change would make this kind of mistake impossible.
Use javax.swing.text.Utilities which has
public static final int getWordStart(JTextComponent c, int offs)
public static final int getWordEnd(JTextComponent c, int offs)
Separating by spaces is not enough. The separator could be also tab, \n etc. chars
public void actionPerformed(ActionEvent ae) {
word.setText(String.valueOf(tohide.getText().split("\\s").length));
}
I am using the following code to do the task. The idea behind it is that each pair of words is separated by a space. hence using space to split seems straight forward. if words contain carriage return, then, replacing the carriage return with empty string has to be done before counting. I hope that it helps
public int WordCount(String Words){
//Initiate Result
String s = Words+" "; //Add space after the received string
String result ="";
int i = 0;
int count = s.length();
try {
for (i = 0; i <= count - 1; i++) {
if (count - i > 1) {
String tempString = s.substring(0, s.indexOf(" "));
if (s.contains(" ") && (!s.isEmpty())) {
s = s.substring(s.indexOf(" ") + 1, s.length());
//get substring between " " and lenght ;
} else {
if(!s.isEmpty()) {
//output nothing
}
}
} else {
//output nothing;
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return i;
}

Categories