Java: Fixing array "linking" to allow for resetting - java

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

Related

Passing Values from Constructor to a Method

My project requires me to make a game where two space ships move around on a game board. I'm not too sure on how to get my X and Y position values from my constructors to my method in my main program.
I got a bit of help from my professor and he said to pass the X and Y values into my print board method I tried to use ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos in my print board declaration but I got an error about VariableDeclaratiorId.
Here is my main as it is currently as is right now
Java
package ship;
import java.util.*;
public class ShipGame {
public static String[][] makeBoard() {
String[][] f = new String[6][22];
for (int i = 0; i < f.length; i++) {
for (int j = 0; j < f[i].length; j++) {
if (j % 2 == 0)
f[i][j] = "|";
else
f[i][j] = " ";
}
}
return f;
}
public static void printBoard(String[][] f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos) {
for (int i = 0; i < f.length; i++) {
for (int j = 0; j < f[i].length; j++) {
if(x == ship1.XPos && y == ship1.YPos){
System.out.print(ship1);
}
else if (x == ship2.XPos && y == ship2.YPos){
System.out.ptint(ship2);
}
else{
System.out.print(f[i][j]);
}
System.out.println();
}
}
}
public static void main(String[] args) {
int engine;
System.out.println("Welcome First Captian! What kind of ship would you like to create: ");
System.out.println("1. Battlecruiser");
System.out.println("2. Destroyer");
Scanner scan = new Scanner(System.in);
engine = scan.nextInt();
scan.nextLine();
String engineType;
if (engine == 1) {
engineType = "Battlecrusier";
}
else {
engineType = "Destroyer";
}
System.out.println("What would you like to name your vessel?");
String shipName1 = scan.nextLine();
Spaceship1 ship1 = new Spaceship1(shipName1, engineType);
System.out.println("Welcome Second Captian! What kind of ship would you like to create: ");
System.out.println("1. Battlecruiser");
System.out.println("2. Destroyer");
engine = scan.nextInt();
scan.nextLine();
if (engine == 1) {
engineType = "Battlecrusier";
}
else {
engineType = "Destroyer";
}
System.out.println("What would you like to name your vessel?");
String shipName2 = scan.nextLine();
Spaceship2 ship2 = new Spaceship2(shipName2, engineType);
String[][] f = makeBoard();
int count = 0;
printBoard(f);
boolean gaming = true;
while (gaming) {
if (count % 2 == 0) {
ship1.movement1(f);
}
else {
ship2.movement2(f);
}
count++;
printBoard(f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos );
gaming = false;
}
}
}
Here is my Spaceship1 constructor. It is the same as my Spaceship2 constructor so there's no need to add it
Java
package ship;
import java.util.Random;
import java.util.Scanner;
public class Spaceship1 extends ship {
private String ship1;
public Spaceship1(String shipName, String engineType) {
super(shipName, engineType);
double maxSpeed = Math.random() * 2 + 1;
int shipHealth = (int) (Math.random() * 100 + 50);
int attackPower = (int) (Math.random() * 20 + 5);
Random rand = new Random();
int newXPos = rand.nextInt(9);
int newYPos = rand.nextInt(9);
setShipHealth(shipHealth);
setMaxSpeed(maxSpeed);
setAttackPower(attackPower);
setXPos(newXPos);
setYPos(newYPos);
}
public void movement1(String[][] f) {
System.out.println("W Move Up");
System.out.println("S Move Down");
System.out.println("A Move Left");
System.out.println("D Move Right");
Scanner scan = new Scanner(System.in);
String move = scan.nextLine();
int standX = getXPos();
int standY = getYPos();
double standS = getMaxSpeed();
if(move == "W")
{
standY += standS;
setYPos(standY);
}
else if(move == "S")
{
standY += standS;
setYPos(standY);
}
else if(move == "A")
{
standY += standS;
setYPos(standY);
}
else if(move == "D")
{
standY += standS;
setYPos(standY);
}
}
}
I expect there to be the words Ship1 and Ship2 on any space on my game board that is declared as 6x22.
When you define a method, you need to define the arguments it accepts using their types and names that the method will use to refer to those arguments. For example, your code:
public static void printBoard(String[][] f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos)
should actually be written like so:
public static void printBoard(String[][] f, int ship1Xpos, int ship1Ypos, int ship2Xpos, int ship2Ypos)
The reason your code doesn't work is because you're trying to define the method using the values you want to pass into it (e.g., ship1.XPos). When you want to call the method, then you can give it the values that you want it to use, like so:
printBoard(f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos);
Keep in mind that you also have the following line of code which won't work because you're not passing a value for all of the arguments it expects:
printBoard(f);

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.

the error when i change a number in decimal base to another base

I am writing a java code to Change a number from decimal base to another base.
But I don't know why the program runs wrong. I think the error comes from function Prin_as. Can anyone tell me why ?
Below is my code,
import java.util.Scanner;
public class bai2chuyendoi {
public static void main(String[] args) {
int a, b;
System.out.println("Number in decimal base:");
a = Enter();
System.out.println("Other base :");
b = Enter();
Change_base (a, b);
}
public static int Enter() {
int n = 0;
boolean check = false;
while (!check) {
Scanner sc = new Scanner(System.in);
try {
n = sc.nextInt();
check = true;
} catch (Exception e) {
System.out.println("Enter again:");
sc.nextLine();
}
}
return n;
}
public static void Change_base(int a, int b) {
int i = 0;
int[] c = new int[8];
while (a != 0) {
c[i] = a % b;
a = a / b;
i++;
}
while (i >= 0) {
--i;
if (c[i] < 10) {
System.out.print(c[i]);
} else {
System.out.print((char) (c[i] + 55));
}
}
}
}
The error was in Change_base method in second while loop.
You need decrement 'i' and check that i >= 0, but you didn't.
while (--i >= 0) {
if (c[i] < 10) {
System.out.print(c[i]);
} else {
System.out.print((char) (c[i] + 55));
}
}

How to have a proper JTextField IP address in 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));
}
}

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.

Categories