How to have a proper JTextField IP address in Java? - java
First of all, I couldn't find any of my question on google.
This is the following code that I used.
ipAddress = new MaskFormatter("###.###.###.###");
JTextField txtAddress = new JFormattedTextField(ipAddress);
But the code above gives user to (must) input exactly 12 characters.
How to make the JTextField can be written as "12.10.25.25" ?
I would do it differently:
Simply wait for the user to somehow confirm that he has finished entering the address (for example by observing when the field looses focus) and retrieve the value of the field and use one of the many regular expressions that check all properties of valid ip addresses.
Looking at the Oracle tutorial here it seems to me that using a JTextFormattedTextField simply is the wrong answer. That class and the corresponding formats are for either locale-based formatting of dates or numbers.
I think you should be rather looking into input validation; see here for details; and as said; your validation could be based on the things you find here.
Finally: the point is to come up with a consistent user experience. Dont put yourself into a corner by saying: I saw this approach; so I absolutely must use that type of component. Instead, check out the possible options, and go for that one that (given your "budget" of development resources) gives the user the best experience.
Example: instead of using 1 JFormattedTextField, you could go for 4 textfields, and even write code that would move the focus automatically forth and back. Many things are possible; it only depends on how much time you are willing to spend.
My homegrown IP address control based on a single JTextField
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class JIp4AddressInput extends JTextField
{
private final char[] buff = " 0. 0. 0. 0".toCharArray();
private int bpos;
private void putnum (int num, int offset)
{
int a = num/100;
num -= a*100;
int b = num/10;
num -= b*10;
buff[offset] = (char)('0'+a);
buff[offset+1] = (char)('0'+b);
buff[offset+2] = (char)('0'+num);
}
private void align (int base)
{
int end = base+3;
StringBuffer sb = new StringBuffer();
for (int s=base; s<end; s++)
{
if (buff[s] != ' ')
sb.append(buff[s]);
}
while (sb.length() > 1 && sb.charAt(0) == '0')
sb.delete(0,1);
while (sb.length() < 3)
sb.insert(0, ' ');
try
{
int num = Integer.parseInt(sb.toString().trim());
if (num > 255)
sb = new StringBuffer("255");
if (num < 0)
sb = new StringBuffer(" 0");
}
catch (NumberFormatException e)
{
sb = new StringBuffer(" 0");
}
for (int s=base; s<end; s++)
{
buff[s] = sb.charAt(s-base);
}
}
private void alignAll()
{
align(0);
align (4);
align(8);
align (12);
}
private void fwd ()
{
bpos = bpos == 15 ? bpos : bpos +1;
}
private void back ()
{
bpos = bpos == 0 ? bpos : bpos -1;
}
private void backspace()
{
back();
if (bpos == 3 || bpos == 7 || bpos == 11)
{
return;
}
if (bpos < 15)
buff[bpos] = ' ';
}
private void setChar (char c)
{
if (bpos == 3 || bpos == 7 || bpos == 11)
{
fwd();
}
if (bpos < 15)
buff[bpos] = c;
fwd();
}
public JIp4AddressInput()
{
super();
setPreferredSize(new Dimension(110, 30));
setEditable(false);
Action beep = getActionMap().get(DefaultEditorKit.deletePrevCharAction);
beep.setEnabled (false);
setText (new String (buff));
addFocusListener(new FocusListener()
{
#Override
public void focusGained(FocusEvent e)
{
setText (new String (buff));
setCaretPosition(0);
getCaret().setVisible(true);
}
#Override
public void focusLost(FocusEvent e)
{
alignAll();
setText(new String(buff));
}
});
addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped (KeyEvent e)
{
bpos = getCaretPosition();
char c = e.getKeyChar();
if ((c>= '0' && c<= '9') || c == ' ')
{
setChar (c);
}
else if (c == KeyEvent.VK_BACK_SPACE)
{
backspace();
}
else if (c == KeyEvent.VK_ENTER)
{
alignAll();
}
setText(new String(buff));
setCaretPosition(bpos);
}
});
}
////////////////////////////////////////////////////////////////////////////////////////
public InetAddress getAddress()
{
String[] parts = new String(buff).split("\\.");
byte[] adr = new byte[4];
for (int s=0; s<4; s++)
adr[s] = (byte)Integer.parseInt(parts[s].trim());
try {
return InetAddress.getByAddress(adr);
} catch (UnknownHostException e) {
return null;
}
}
public void putAddress (InetAddress in)
{
byte[] adr = in.getAddress();
putnum(adr[0]&0xff, 0);
putnum(adr[1]&0xff, 4);
putnum(adr[2]&0xff, 8);
putnum(adr[3]&0xff, 12);
alignAll();
setText (new String(buff));
}
}
Related
Java: Error in code for a Recursive Maze for using Java
this code below is for a maze via recursion and is supposed to solve the maze. There are three different txt files that it reads from S is the start, G is the goal, X is a barrier and O is a free space GOOOOXO //maze1 XXOXOOX OXOOOXX XXXOOXO XXXXOXX SOOOOOX XXXXXXX XOOOOXO //maze2 XXOXOOG OXOOOXX XXXOOOX XXXXOXX SOOOOOX XXXXXXX XOOOOXO //maze3 XXOXOXG OXOOOXX XXXOOOX XXXXOXX SOOOOOX XXXXXXX These are the mazes. maze1 and maze2 have a solution but every time I run it, it returns "unsolvable". I'm not sure where the error is. Here is the full code: import java.util.ArrayList; import java.util.Scanner; import java.io.File; import java.io.IOException; public class Maze2 { private static char[][] maze; private static int startrow, startcol, finishrow, finishcol; private static ArrayList<String> mazeBuffer; public static void initializeMaze(String fileName) { startrow = startcol = finishrow = finishcol = -1; mazeBuffer = new ArrayList<String>(); int numcols = 0; try { Scanner file = new Scanner(new File(fileName)); while(file.hasNext()) { String nextLine = file.nextLine(); mazeBuffer.add(nextLine); if (nextLine.length() > numcols) numcols = nextLine.length(); } } catch(Exception e) { System.out.println(fileName + " has an issue"); } int numrows = mazeBuffer.size(); maze = new char[numrows][numcols]; for (int r = 0; r < numrows; r ++) { String row = mazeBuffer.get(r); for (int c = 0; c < numcols; c++) { if(row.length() >= c) maze[r][c]=row.charAt(c); else maze[r][c]='*'; if (maze[r][c] == 'S') { startrow = r; startcol = c; } if (maze[r][c] == 'G') { finishrow = r; finishcol = c; } } } System.out.println("Maze loaded"); } public static void printMaze() { for (char[] row: maze) { for (char c: row) System.out.print(c); System.out.println(); } System.out.println(); } public static void main (String[] args) { initializeMaze("maze3.txt"); printMaze(); if (solveMaze(startrow, startcol)) printMaze(); else System.out.println("Unsolvable."); } public static boolean solveMaze(int r, int c) { if(r < 0 || c < 0 || r >= maze.length || c >= maze[0].length) return false; if(maze[r][c]=='G') return true; if (maze[r][c] != '0'|| maze[r][c] != 'S') return false; maze[r][c]='A'; if(solveMaze(r-1,c)) { maze[r][c]= '#'; return true; } if(solveMaze(r+1,c)) { maze[r][c]='#'; return true; } if(solveMaze(r,c-1)) { maze[r][c]='#'; return true; } if(solveMaze(r,c+1)) { maze[r][c]='#'; return true; } else{ return false; } } } If all is correct, mazes 1 and 2 should be solvable but as of now they are not for some reason. plz help it's a project due soon and I can't figure it out.
The problem lies in the condition if you are on a valid path. The first error is, that you are checking for the number 0 instead of the capital letter O. The second error is the combination of the two conditions. If you start at 'S' you are obviously not at an 'O'. So your condition tells you, that you are not on a valid path. The check should be: if(!(maze[r][c] == 'O'|| maze[r][c] == 'S')) If you fix this, everything should be working fine.
Java: Fixing array "linking" to allow for resetting
Firstly, I know Lists are better in almost(if not all) every way. I have encountered a substantial bug in an encoder program that I am making. In this program, I have a button that resets the "wheels" responsible for encoding(One of the wheels rotates after every letter encoded). I have a final int[][] called wheelsOriginal that is supposed to store the original value of the int[][] called wheels. Both of these arrays are int[9][36]. I would like a way of making wheelsOriginal stay unchanged throughout the program instead of changing with wheels for some reason. Here is a good way to recreate the problem(Sorry for the lengthy intToChar and charToInt methods!): Main class: import java.awt.*; import javax.swing.*; public class mainClass { public static void main(String[] args) { JFrame frame = new JFrame("Encoder"); frame.setBackground(new Color(225,225,225)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Display d = new Display(); frame.add(d); frame.pack(); frame.setResizable(false); frame.setVisible(true); } } Display class: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Display extends JPanel implements ActionListener { static JButton button; static JLabel letter; static int currentKey = -10; static int wheel = 0; static int[][] wheels = { {-3,10,-6,2,20,-7,22,5,23,4,6,-9,3,26,0,15,21,-2,13,14,12,1,17,11,-8,-5,18,8,24,9,25,7,19,16,-4,-1}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7}, {18,20,-9,15,12,-6,16,-4,-5,14,24,-7,-8,-3,-1,1,4,7,8,25,10,11,5,6,13,22,19,21,23,-2,3,26,17,9,0,2}, {-3,10,-6,2,20,-7,22,5,23,4,6,-9,3,26,0,15,21,-2,13,14,12,1,17,11,-8,-5,18,8,24,9,25,7,19,16,-4,-1}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7} }; final static int[][] wheelsOriginal = wheels; public Display() { setPreferredSize(new Dimension(250,200)); setFocusable(true); button = new JButton("Reset"); button.setPreferredSize(new Dimension(225,50)); button.setFont(new Font(button.getFont().getFontName(), button.getFont().getStyle(), 25)); letter = new JLabel(" ", SwingConstants.CENTER); letter.setPreferredSize(new Dimension(225,100)); letter.setFont(new Font(letter.getFont().getFontName(), Font.BOLD, 125)); letter.setForeground(new Color(0,0,0)); addKeyListener( new KeyListener() { public void keyPressed(KeyEvent e) { if(currentKey == -10 && e.getKeyCode() >= 65 && e.getKeyCode() <= 90) { currentKey = e.getKeyCode() - 64; letter.setText(encode() + ""); } else if(currentKey == -10 && e.getKeyCode() >= 48 && e.getKeyCode() <= 57) { currentKey = -1 * (e.getKeyCode() - 48); letter.setText(encode() + ""); } } public void keyReleased(KeyEvent e) { currentKey = -10; letter.setText(" "); } public void keyTyped(KeyEvent e) {} } ); button.addActionListener(this); add(button, TOP_ALIGNMENT); add(letter); } public static char encode() { int key = currentKey; for(int i = 0; i < 9; i++) { key = wheels[i][key + 9]; } for(int i = 8; i >= 0; i--) { key = wheels[i][key + 9]; } rotate(wheels[wheel], isEven(wheel)); if(wheel < 8) { wheel++; } else { wheel = 0; } return((char) key); } public static int[] rotate(int[] wheel, boolean positive) { int revolve; if(positive) { revolve = wheel[wheel.length - 1]; for(int i = wheel.length - 2; i > 0; i--) { wheel[i + 1] = wheel[i]; } wheel[0] = revolve; } else { revolve = wheel[0]; for(int i = 1; i < wheel.length - 1; i++) { wheel[i - 1] = wheel[i]; } wheel[wheel.length - 1] = revolve; } return wheel; } public static boolean isEven(int num) { return (num/2 == Math.abs(num/2)); } public void actionPerformed(ActionEvent e) { if(e.getSource().equals(button)) { reset(); grabFocus(); } } public static void reset() { for(int[] i : wheels) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } System.out.println(" "); for(int[] i : wheelsOriginal) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } System.out.println(" "); wheels = wheelsOriginal; for(int[] i : wheels) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } wheel = 0; letter.setText(" "); currentKey = ' '; System.out.println("Pressed"); } } Whenever a key is pressed, the encoded letter appears in the window. Even pressing the same key over and over again will usually produce different letters. Pressing the reset button should reset the encoder so that pressing the letter 'A' three times should produce S, E, and Q in that order. I also have designed this so that whenever you press the reset button, three large bulks of numbers print in the console. These show the wheels array before reset, the wheelsOriginal array, and the product wheels array in that order. If you press keys and click reset several times, you will notice that wheelsOriginal changes with wheels. Please help...
Your problem is that you are creating wheelsOriginal as reference of wheels instead of copy. Thats why when you change wheels, wheelsOriginal changes as well. final static int[][] wheelsOriginal = wheels; Something like this loop can be used to create a copy of wheels int[][] wheelsOriginal = new int[wheels.length][]; for( int i = 0; i < wheelsOriginal.length; i++ ) { wheelsOriginal[i] = Arrays.copyOf( wheels[i], wheels[i].length ); } Also, for your charToInt and IntToChar methods - you could use the fact that chars are numbers and a->z A->Z 0->9 are grouped together to shorten them significantly I didn't test that - in case you decide to use something like this - think and test yourself public int charToInt( char c ) { if( c >= '0' && c <= '9' ) { return '0' - c; } else if( c >= 'A' && c <= 'Z' ) { return c - 'A' + 1; } else if( c >= 'a' && c <= 'z' ) { return c - 'a' + 1; } else { return -10; } } public char intToChar( int c ) { if( c >= -9 && c <= 0 ){ return (char)('0' - c); } else if( c >= 1 && c <= 26 ){ return (char)(c + 'A' - 1); } else{ return ' '; } }
JOptionPane.showMessageDialog keeps reappearing
My code is supposed to ensure that users only enter a binary string. Everything goes right and in order if I enter a correct binary number (1, 0). But when I enter a wrong number (alphabet or number other than 0 and 1) JOptionPane.ShowMessageDialog appears showing the error message, and when I click "OK" or "Cross" Button it reappears again. So to close the app I have to use the process manager to kill "java.exe". Here is the complete code for my app: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; class Bn extends JFrame { private JLabel l1; private JLabel l2; private JLabel l3; private JTextField tf; private JButton oc; private JButton hd; private JButton dc; public Bn() { setTitle("Binary Conversion"); setSize(350 , 190); setResizable(false); setLocation(720 , 200); //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.CENTER, 25, 10)); l1 = new JLabel(">>>>>>>>BINARY CONVERSION<<<<<<<<"); l2 = new JLabel("Enter The Number:"); l3 = new JLabel(" Convert to: "); tf = new JTextField(25); oc = new JButton("Octal"); hd = new JButton("Hexa Decimal"); dc = new JButton("Decimal"); add(l1); // Binary conversion add(l2); // Enter The Number add(tf); // Text Field add(l3); // Conver to add(oc); // Octal add(hd); // Hexa Decimal add(dc); // Decimal oc.addActionListener(new cvr()); hd.addActionListener(new cvr()); dc.addActionListener(new cvr()); setVisible(true); } void res() { int b = 0; String num = tf.getText(); int i , l; l = num.length(); char ch; do { for (i=0 ; i<l ; i++) { b = 0; ch = num.charAt(i); if (Character.isDigit(ch) && (ch == 48 || ch == 49)) b=1; else { JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)"); } } } while(b != 1); } void occ() { res(); String num = tf.getText(); long dec = Long.parseLong(num,2); String oct = Long.toOctalString(dec); JOptionPane.showMessageDialog(null, "Octal equivalent is: "+ oct); } void hdc() { res(); String num = tf.getText(); long dec = Integer.parseInt(num,2); String hex = Long.toHexString(dec); JOptionPane.showMessageDialog(null, "Hexa Decimal equivalent is: "+ hex); } void dcc() { res(); String num = tf.getText(); long decimal = 0, temp, i = 0; temp = Long.parseLong(num); while (temp != 0) { long r = temp % 10; long value = r * (int)Math.pow(2, i); i++; decimal = decimal + value; temp /= 10; } JOptionPane.showMessageDialog(null, "Decimal equivalent is: "+ decimal); } private class cvr implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == oc) { occ(); } if (e.getSource() == hd) { hdc(); } if (e.getSource() == dc) { dcc(); } } } public static void main(String args[]) { Bn obj = new Bn(); } } The code for JOptionPane is located in void res() method. How can I close this Dialog pane so I may reenter the value for input?
Remove the do { } while loop do { for (i=0 ; i < l ; i++) { b = 0; ch = num.charAt(i); if (Character.isDigit(ch) && (ch == 48 || ch == 49)) b=1; else { JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)"); } } } while(b != 1);
Java help! implementing a 2d array of a certain object, the object has multiple private data types and objects
I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this? This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object. "Exception in thread "main" java.lang.NullPointerException at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50) Java Result: 1" Here is my main class: public class WumpusWorldGame { class Agent { private boolean safe; private boolean stench; private boolean breeze; public Agent() { safe = false; stench = false; breeze = false; } } /** * #param args * the command line arguments * #throws java.lang.Exception */ public static void main(String [] args) { // WumpusFrame blah =new WumpusFrame(); // blah.setVisible(true); Scanner input = new Scanner(System.in); int agentpts = 0; System.out.println("Welcome to Wumpus World!\n ******************************************** \n"); //ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>(); for (int i = 0 ; i < 5 ; i++) { WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5]; System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c)."); int wumpusR = input.nextInt(); int wumpusC = input.nextInt(); woah[wumpusR][wumpusC].setPoints(-3000); woah[wumpusR][wumpusC].setWumpus(); if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) { woah[wumpusR][wumpusC].setStench(); } if (wumpusC != 0) { woah[wumpusR][wumpusC - 1].getStench(); } if (wumpusR != 0) { woah[wumpusR - 1][wumpusC].setStench(); } if (wumpusC != 4) { woah[wumpusR][wumpusC + 1].setStench(); } if (wumpusR != 4) { woah[wumpusR + 1][wumpusC].setStench(); } System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c)."); int goldR = input.nextInt(); int goldC = input.nextInt(); woah[goldR][goldC].setGold(); System.out.println("***************************************\n How many pits would you like in your wumpus world?"); int numPits = input.nextInt(); for (int k = 0 ; k < numPits ; k++) { System.out.println("Enter the row location of the pit"); int r = input.nextInt(); System.out.println("Enter the column location of the pit"); int c = input.nextInt(); woah[r][c].setPit(); if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) { woah[r][c].setBreeze(); } if (c != 0) { woah[r][c - 1].setBreeze(); } if (r != 0) { woah[r - 1][c].setBreeze(); } if (c != 4) { woah[r][c + 1].setBreeze(); } if (r != 4) { woah[r + 1][c].setBreeze(); } } for (int x = 0 ; x < 4 ; x++) { int j = 0; while (j < 4) { agentpts = agentpts + woah[x][j].getPoints(); Agent [] [] k = new Agent [4] [4]; if (woah[x][j].getWumpus() == true) { agentpts = agentpts + woah[x][j].getPoints(); System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts); } if (woah[x][j].getStench() == true) { k[x][j].stench = true; System.out.println("You smell something funny... smells like old person."); } if (woah[x][j].getBreeze() == true) { k[x][j].breeze = true; System.out.println("You hear a breeze. yeah"); } if (woah[x][j].getPit() == true) { agentpts = agentpts + woah[x][j].getPoints(); System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now."); } // if breeze or stench, if breeze and stench, if nothing, etc then move. k[x][j].safe = true; // if(k[i][j].isSafe()!=true){ // } else { } } } } } } Here is my class object that I'm trying to implement: package wumpusworld; /** * * #author Jacob */ public class WumpusWorldObject { private boolean stench; private boolean breeze; private boolean pit; private boolean wumpus; private boolean gold; private int points; private boolean safe; public WumpusWorldObject(){ } public boolean getPit() { return pit; } public void setPit() { this.pit = true; } public boolean getWumpus() { return wumpus; } public void setWumpus() { this.wumpus = true; } public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } public boolean getStench() { return stench; } public void setStench() { this.stench = true; } public boolean getBreeze() { return breeze; } public void setBreeze() { this.breeze = true; } public boolean getSafe() { return safe; } public void setSafe() { this.safe = true; } public void setGold(){ this.gold=true; } }
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like which constructor should be used what data should be passed to this constructor. This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly. After creating array iterate over it and fill it with new instances of your class. for (int i=0; i<yourArray.length; i++) for (int j=0; j<yourArray[i].length; j++) yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50]; is not enough, you have to create instances of them like obj[i][j] = new AClass(...); In your code the line woah[wumpusR][wumpusC].setPoints(-3000); must be after woah[wumpusR][wumpusC] = new WumpusWorldObject(); .
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.