Counting the number of words in a text area - java

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;
}

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

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.

Analysing word frequencies in applet

i am writing a program in applet to measure the frequencies of word lengths in a given amount of text and display these frequencies during applet. i have written the program and it debugs without error.
however the output says i have 255 words of every length in the text i input, i have been staring at this for hours with no luck, i am aware that the drawstring method lists these outputs horizontally which i will be fixing at a later time.
i am assuming the problem resides in the analyseText method.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.util.*;
public class StringAnalysis extends Applet implements MouseListener, ActionListener {
Font arielBold;
Label pr_Label;
TextField pr_txt;
int textFieldSize = 15;
Button pr_input1, pr_input2, pr_input3;
String textToAnalyse = ("Nothing has been entered.");
boolean output = false;
String testing ="";
//create array to show respective lengths of words
int [] lengthsOfWords = new int[textFieldSize];
//first we must separate strings from spaces and populate array for comparison
String [] arrayOfWords = new String[textFieldSize];
public void init() {
pr_Label = new Label("Enter the text you wish to analise: ");
add(pr_Label);
pr_txt = new TextField(textFieldSize);
add(pr_txt);
pr_input1 = new Button("Analyse");
pr_input2 = new Button("Reset");
add(pr_input1);
add(pr_input2);
pr_input1.addActionListener(this);
pr_input2.addActionListener(this);
}
public void start (){
setSize(1000, 500);
arielBold = new Font ("Ariel", Font.BOLD, 20);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == pr_input2) {
showStatus("Resseting....");
reset();
}
else if (e.getSource() == pr_input1){
showStatus("Analysing...a");
textToAnalyse = pr_txt.getText();
analyseText(textToAnalyse);
}
}
public void paint(Graphics g) {
String statsToOutput = ("There are:" + "\n" );
int counter = 1;
for (int lengths: lengthsOfWords) {
statsToOutput = statsToOutput +lengthsOfWords[0] + " words of length " + counter + "\n ";
counter ++;
}
if (output = true){
g.drawString(statsToOutput, 25, 200);
g.drawString("The text to be analysed is: " + textToAnalyse, 25, 100);
showStatus("Finished.");
}
else if (output = false){
g.setFont(arielBold);
g.drawString(textToAnalyse,50, 100);
showStatus("Finished.");
}
}
public void analyseText(String text){
///////////////////////////////////////////////////////////////////////////////////////////////////////
int position1 = 0, position2 = 0;
String newWord = "";
String currentLetter;
int pos1 = 0, pos2 = 0;
for ( pos1 = 0; pos1 <= arrayOfWords.length-1; pos1++) {
//Initializes a string object for each address in array
for (position1 = 0; position1 <= text.length()-1; position1++){
//steps through each character in text
currentLetter = Character.toString(text.charAt(position1));
if (currentLetter.matches("[A-Z][a-z][0-9]")) {
//checks if character is alphanumeric using regular expressions (regex)
newWord = newWord + currentLetter;
//if passes regex then ads character to word
}
}
if (newWord.length() > 0) {
pos1 = arrayOfWords.length;
}
arrayOfWords[pos1] = newWord;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
emptyArrayInt(lengthsOfWords);
//now compare each word with rest of array\
for ( pos2 = 0; pos2 <= arrayOfWords.length-1; pos2++) {
position2 = 0;
for (position2 = 0; position2 <= arrayOfWords.length-1; position2++){
if (arrayOfWords[pos2].length() == arrayOfWords[position2].length());
lengthsOfWords[arrayOfWords[pos2].length()] = lengthsOfWords[arrayOfWords[pos2].length()] + 1;
}
}
showStatus("finished analysing.");
output = true;
repaint();
}
public void emptyArrayInt(int[] array) {
int position = 0;
for (position = 0; position <= array.length-1; position ++)
array[position] = 0;
}
public void emptyArrayStr(String[] array) {
int position = 0;
for (position = 0; position <= array.length-1; position ++)
array[position] = "";
}
public void reset() {
pr_txt.setText("");
textToAnalyse = ("Nothing has been entered.");
emptyArrayInt(lengthsOfWords);
emptyArrayStr(arrayOfWords);
//repaint();
showStatus("Reset Successful.");
repaint();
}
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
i would appreciate any help on this please, (I'm desperate).
Let's try section of code :
private Map<String, int> freqWords = new HashMap<String, int>();
public void analyzeText(String text) {
// You can split with another type of delimiter
String regex = ....
String[] inputs = text.split(regex);
for (String s : inputs) {
if(freqWords.containtsKey(s)) {
int frequency = inputs.get(s);
frequency++;
inputs.put(s, frequency);
} else {
inputs.put(s, 1);
}
}
}
Hope that it can help you. The main point here is you should use data structure Map to store the frequency words.

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.

Converting JTextField to an int array with exceptions

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);
}
}
}

Categories