I got this program here and I combined the two classes into one for practice purposes. (Thanks to sir who helped me.) However, I got an error and that is "No enclosing instance of type QuineMcCluskey is accessible. Must qualify the allocation with an enclosing instance of type QuineMcCluskey." in the method initTerm.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class QuineMcCluskey extends JFrame implements ActionListener, WindowListener{
private final long serialVersionUID = 1L;
static ArrayList<Term>[][] table=new ArrayList[5][5]; // SERVES AS OUR STORAGE FOR ARRANGING TERMS AND TO OUR RESULTING TERMS THAT ARE BEING COMPARED.
static Vector<String> inputTerm= new Vector <String>(); // STORES OUR ORIGINAL INPUT/NUMBERS
static Vector<String> resultingTerms= new Vector <String>(); // STORES RESULTING TERMS FOR EACH SET OF COMPARISON
static int var=0; //NUMBER OF VARIABLE
static int numbers=0; //NUMBER OF INPUTS
final static int maxTerms=1000; //MAXIMUM NUMBER OF TERMS WITH SAME NUMBER OF 1'S
static TextField result = new TextField(" ",50);
static TextField text;
static TextField text1;
static QuineMcCluskey qWindow;
static String finalT = "";
public static void main(String[] args){
qWindow = new QuineMcCluskey("Quine-McCluskey Simulator"); //creates a window
qWindow.setSize(400,250); //sets the size of the window
qWindow.setVisible(true); //makes the window visible
qWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //CLOSES THE WINDOW WHEN CLOSING OR CLICKING THE X BUTTON
JOptionPane.showMessageDialog(null, "Welcome to my Quine-McCluskey Simulator!"); //DISPLAYS MESSAGE
}//end main
public static int count_one(String temp){ //COUNT 1'S FROM EACH TERM
int count=0;
char[] tempArray=temp.toCharArray();
int i=0;
while(i<temp.length()){
if(tempArray[i]=='1'){
count++;
}
i++;
}//end while
return count;
}//end one
public static void getPrimeImplicants(){ // PAIRS TERMS UNTIL NOTHING TO PAIR, END TERMS ARE OUR PRIME IMPLICANTS
table=createTermTable(inputTerm);
printTermTable();
createPairing();
}
public static ArrayList<Term>[][] createTermTable(Vector <String> input){ // CREATE TABLE, ARRANGES TERMS BASED ON THE NUMBER OF 1'S IN
//EACH TERM USING count_one,therefore, row 1 contains terms with 1 1 bit.
Term temp;
int one=0;
int element=0;
ArrayList[][] arrayLists = new ArrayList[var+1][maxTerms+1]; //CREATES AN ARRAY WITH VAR ROWS CORRESPONDING TO POSSIBLE NUMBER OF
// 1 FOR EACH TERM AND 1000 COLUMNS
ArrayList<Term> [][]tempTable = arrayLists;
for(int x=0;x<=var;x++){ //?
for(int y=0;y<=maxTerms;y++){
tempTable[x][y]= new ArrayList<Term>();
}//end y
}//end for x
for(int i=0;i<input.size();i++){
one=count_one(input.get(i)); //COUNT 1'S FROM EACH TERM
temp=initTerm(input.get(i),false); // INITIALIZE PROPERTIES OF THAT TERM
while(!tempTable[one][element].isEmpty()){
element++;
}//end while
tempTable[one][element].add(temp);
element=0;
} //end for
return tempTable;
}//end createTermTable
public static Term initTerm(String n,boolean u){ //INITIALIZE USED and NUM PROPERTY OF THE TERM
Term term=new Term();
term.used=u; // TO INDICATE IF THE TERM IS ALREADY PAIRED
term.num=n; // THE TERM ITSELF
return term;
}//end initTerm
public static void printTermTable(){ // PRINTS THE COMPUTATION/TABLES
System.out.println("\nCOMPUTING:");
for(int i=0;i<var+1;i++){
System.out.print(i);
System.out.println(" --------------------------------------------");
for(int j=0;!table[i][j].isEmpty();j++){ //PRINTS TERM ON EACH ROW WHILE TERM IS NOT EMPTY
System.out.println(table[i][j].get(0).num);
}//end for j
}//end for i
}
public static void createPairing(){ //PAIRS A TERM TO EACH TERM ON THE NEXT ROW
int finalterms=0;
String term_num="";
int found=0;
Vector<String> preResult= new Vector<String>();
for(int x=0;x<=var-1;x++){ // REPEATS PAIRING OF A TERMS OF THE TABLE VAR TIMES TO MAKE SURE WHAT ARE LEFT ARE PRIME IMPLICANTS
preResult=new Vector<String>(); // STORES THE RESULTING TERMS FOR EACH SET OF PAIRING
for(int i=0;i<=var;i++){ //COMPARES A ROW WITH EACH TERMS ON THE NEXT ROW
//Vector <String> rowResult= new Vector<String>(); //STORES RESULTING TERMS ON THAT PARTICULAR TERM OF THE ROW. THIS IS TO AVOID REPETITIONS
for(int j=0;!table[i][j].isEmpty();j++){ // TERM ON THE ROW BEING COMPARED WITH EACH TERM ON NEXT ROW
if(i+1!=var+1) // MAKES SURE THAT THE PROCESS NOT EXCEEDS THE ARRAYBOUND
for(int k=0;!table[i+1][k].isEmpty();k++){ //TERM ON THE NEXT ROW THAT IS BEING COMPARED WITH TERM ON THE CURRENT ROW.
term_num=pair(table[i][j].get(0).num,table[i+1][k].get(0).num); //ASSIGNS RESULT OF PAIRING TO term_num
if(term_num!=null){ // IF PAIRING IS SUCCESSFUL
table[i+1][k].get(0).used=true; // TERM IS PAIRED/USED
/*if(!rowResult.contains(term_num)){ //MAKES SURE THAT TERM IS NOT REPEATE
rowResult.add(term_num);
found=1;
}
*/
if(!preResult.contains(term_num)){ // MAKES SURE THAT TERM IS NOT REPEATED
preResult.add(term_num);
found=1;
finalterms++; // COUNTS THE FINAL/RESULTING TERMS FOR THIS SET OF PAIRING
}//end if !resultingTerms
found=1;
}//end if term_num!=null
}//end for k
if(found==0){ // IF TERM IS NOT SUCCESSFULLY PAIRED/USED, ADD TO THE RESULTING TERMS FOR THIS SET
if(table[i][j].get(0).used!=true){
preResult.add(table[i][j].get(0).num);
}
}
found=0;
}//end for j
}//end for i
table=createTermTable(preResult); // CREATE ANOTHER TABLE FOR NEXT SET. THE NEW TABLE CONTAINS THE RESULTING TERMS OF THIS SET
if(preResult.size()!=0)
resultingTerms=preResult; //IF THE ARE RESULTING TERMS, THEN PRINT AND ASSIGN TO resultingterms. THE END VALUE OF resultingterms WILL BE SIMPLIFIED
printTermTable();
}//end for x
}//end createPairing
public static String pair(String a,String b){
int difference=-1;
char []array1 = new char[a.length()];
char []array2;
for(int i=0;i<var;i++){
array1=a.toCharArray(); //CONVERTS TERMS OF TYPE STRING TO TERMS OF TYPE CHAR
array2=b.toCharArray();
if(array1[i]!=array2[i]){ // IF NOT EQUAL FOR A PARTICULAR CHARACTER FOR THE FIRST TIME, THEN GET THE INDEX CORRESPONDING TO THAT CHARACTER.
if(difference==-1)
difference=i;
else //IF NOT NOT EQUAL FOR THE FIRST TIME, THEN THE TERMS DIFFER IN MORE THAN 1 PLACE
return null;
}//end if
}//end for
if(difference==-1) //THE TERMS ARE INDENTICAL, RETURN NULL, PAIRING UNSUCCESSFUL
return null;
char[] result= a.toCharArray(); //CHARACTER CORRESPONDING TO THE INDEX WHERE TERMS DIFFER ONLY ONCE WILL BE CHANGED TO '-'
result[difference]='-';
String resulTerm= new String(result);
return resulTerm; //RETURNS THE MODIFIED TERM, PAIRING SUCCESSFUL
}//end pair
public static void simplifymore(){ //SIMPLIFY THE RESULTINGTERMS
int primes=resultingTerms.size(); // RESULTING TERMS CORRESPOND TO OUR PRIME IMPLICANTS
int[][] s_table= new int[primes][numbers]; //CREATES A TABLE WITH ROWS EQUAL TO NUMBER OF PRIME IMPLICANTS AND COLUMNS EQUAL TO THE NUMBER OF THE ORIGINAL INPUT
for(int i=0;i<primes;i++){
for(int j=0;j<numbers;j++){
s_table[i][j]=implies(resultingTerms.get(i),inputTerm.get(j));
}//end for j
}//end for i
Vector <String> finalTerms= new Vector<String>(); // STORES THE FINALTERMS
int finished=0;
int index=0;
while(finished==0){ //UNTIL ALL ELEMENTS ARE NOW TURNED TO 0
index=essentialImplicant(s_table);
if(index!=-1)
finalTerms.add(resultingTerms.get(index)); // IF RESULTING TERM IS THE ONLY ONE IMPLYING THE CURRENT ORIGINAL TERM, THEN ADD TO FINAL TERMS
else{ // THOSE THAT HAVE MORE THAN ONE IMPLICATION FOR A PARTICULAR ORIGINAL TERM
index=largestImplicant(s_table);
if(index!=-1)
finalTerms.add(resultingTerms.get(index)); //ADD TO FINAL TERMS IF LARGEST IMPLICANT(ONE WHICH HAS MORE NUMBER OF 1'S. SEE COMMENTS ON largestImplicant.
else
finished=1; //IF INDEX IS -1 THEN ALL ELEMENTS HAVE ALREADY BEEN DELETED OR HAVE MADE VALUE 0
}//end else
}//end while finished
System.out.println("Final Terms :");
for(int x=0;x<finalTerms.size();x++) //PRINTS THE FINAL TERMS IN BINARY FORMAT
System.out.println(finalTerms.get(x));
printSimplified(finalTerms);
}//end simplifymore
public static void printSimplified(Vector <String> finalTerms){
String temp="";
char[] tempArray;
char variables[]= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; //basis for our variables to printed
int index=0;
int i=0;
int j=0;
System.out.print("F = ");
while(i<finalTerms.size()){ //until all final terms are printed in algebraic form.
temp=finalTerms.get(i); //assigns current final term to temp
tempArray=temp.toCharArray(); //CONVERTS TEMP TO ARRAY
while(j<var){
if(tempArray[j]=='-'){ //IGNORES -
index++;
}
else if (tempArray[j]=='0'){
finalT+=variables[26-var+index]+"'"; // PRINTS THE CORRESPONDING LETTER.IF CHARACTER IS 0 THEN APPEND ' AFTER THE VARIABLE
index++;
}
else if (tempArray[j]=='1'){
finalT+=variables[26-var+index]; // PRINTS CORRESPONDING LETTER
index++;
}
else{};
j++;
}//end while
if(i<finalTerms.size()-1)
finalT+=" + "; // APPENDS +
i++;
temp="";
j=0;
index=0;
}//end while
System.out.println(finalT);
}//print simplified
public static int essentialImplicant(int[][] s_table){ // CHECKS EACH RESULTING TERM IMPLYING A PARTICULAR ORIGINAL TERM
for(int i=0;i<s_table[0].length;i++){ //
int lastImplFound=-1;
for(int impl=0;impl<s_table.length;impl++){
if(s_table[impl][i]==1){ //IF RESULTING TERM IMPLIES ORIGINAL TERM
if(lastImplFound==-1){
lastImplFound=impl;
}else{ // IF MORE THAN ONE IMPLICATION,THEN IT IS NOT AN ESSENTIAL PRIME IMPLICANT.GO TO NEXT ORIGINAL TERM
lastImplFound=-1;
break;
}//end else
}
}
if(lastImplFound!=-1){ // ONE IMPLICATION FOR THE ORIGINAL TERM. THIS IS AN ESSENTIAL PRIME IMPLICANT
implicant(s_table,lastImplFound);
return lastImplFound;
}
}//end for impl
return -1;
}
public static void implicant(int [][] s_table,int impA){ // DELETE OR MAKE VALUE 0 THE ROW WHERE THE ESSENTIAL PRIME IMPLICANT IS AND THE COLUMNS OF ALL THE ORIGINAL TERMS IMPLIED BY IT
for(int i=0;i<s_table[0].length;i++){
if(s_table[impA][i]==1)
for(int impB=0;impB<s_table.length;impB++){
s_table[impB][i]=0;
}
}
}//end implicant
public static int largestImplicant(int[][] s_table){
int maxImp=-1;
int max=0;
for(int imp=0;imp<s_table.length;imp++){ // LOCATES WHICH HAS MORE NUMBER OF 1'C IN EACH PRIME
int num=0;
for(int i=0;i<s_table[0].length;i++){
if(s_table[imp][i]==1)
num++;
}//end for i
if(num>max){ // TERM WITH MORE 1'S AT THE END OF THE LOOP WILL BE ADDED TO THE FINAL TERMS
max=num;
maxImp=imp;
}//end if num>max
}//end for imp
if(maxImp!=-1){ // IF WE HAVE SUCCESSFULLY LOCATED A PRIME IMPLICANT
implicant(s_table,maxImp); // DELETE OR MAKE VALUE 0 THE ROW WHERE THE ESSENTIAL PRIME IMPLICANT IS AND THE COLUMNS OF ALL THE ORIGINAL TERMS IMPLIED BY IT
return maxImp;
}//end if maxImp!=-1
return -1;
}
public static int implies(String term1, String term2){ // RETURNS 1 IF RESULTING TERM IMPLIES THE ORIGINAL TERM, 0 OTHERWISE
char[] term1Array=term1.toCharArray();
char[] term2Array=term2.toCharArray();
//EX. ORG TERM IS 100100, RES TERM IS 1--10- ,RESULTING TERM IMPLIES THE ORIGINAL TERM. SINCE - HERE IS TREATED AS 0 OR 1
for(int i=0;i<var;i++){
if(term1Array[i]!=term2Array[i] && term1Array[i]!='-')
return 0;
}
return 1;
}
//end class
public QuineMcCluskey (String name){
super(name); //ASSIGNS LABEL OF THE WINDOW
setLayout(new GridLayout(1, 1)); //SETS THE LAYOUT
setLocation(350,200); //SETS THE LOCATION OF THE WINDOW ON THE SCREEN
GridBagLayout gridbag = new GridBagLayout(); //used to align buttons
GridBagConstraints constraints = new GridBagConstraints();//to specify the size and position for the gridbaglayout
setLayout(gridbag);
constraints.weighty = 1; //distributes spaces among columns
constraints.weightx = 1; //distributes spaces among rows
constraints.gridwidth = GridBagConstraints.REMAINDER; //to specify that the component be the last one in its column
Label label1 = new Label(" How many variables does the function have?"); //CREATES A LABEL
label1.setVisible(true); //MAKES THE LABEL VISIBLE, ASSIGNS NEW FONT AND COLOR THEN ADD TO THE WINDOW
label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
text1= new TextField("",10);
gridbag.setConstraints(text1,constraints); //applies constraints to text
text1.setEditable(true); //SO THAT WE COULD STILL HAVE AN UNLIMITED LENGTH OF INPUT
text1.setForeground(Color.black);
text1.setBackground(Color.white);
text1.setVisible(true);
text1.addActionListener(this); //ACTIVATES ACTIONLISTENER FOR THIS FIELD
add(text1);
label1 = new Label(" Please list all the minterms that evaluates to 1:");//CREATES LABEL
gridbag.setConstraints(label1,constraints);
label1.setVisible(true); //MAKES THE LABEL VISIBLE, ASSIGNS NEW FONT AND COLOR THEN ADD TO THE WINDOW
label1.setBackground(Color.green);label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
text = new TextField("Enter your numbers here separated by a comma",50);
gridbag.setConstraints(text,constraints); //applies constraints to text
text.setEditable(true); //ENABLES UNLIMITED LENGTH OF INPUT
text.setForeground(Color.black);
text.setBackground(Color.white);
text.setVisible(true);
text.addActionListener(this); //ACTIVATES ACTIONLISTENER FOR THIS FIELD
text.setForeground(Color.blue);
add(text);
JButton enter = new JButton ("Enter"); // CREATES BUTTON NAMED Enter
enter.setVisible(true); //MAKES IT VISIBLE, APPLIES THE CONSTRAINTS, AND ADD TO THE WINDOW
add(enter);
enter.setBackground(Color.green);
enter.addActionListener(this); //ACTIVATES ACTIONLISTENER
gridbag.setConstraints(enter,constraints);
JButton reset = new JButton ("Reset"); // CREATES BUTTON NAMED Reset
reset.setVisible(true); //MAKES IT VISIBLE, APPLIES THE CONSTRAINTS, AND ADD TO THE WINDOW
gridbag.setConstraints(reset,constraints);
reset.setBackground(Color.green);
add(reset);
reset.addActionListener(this);
label1 = new Label(" Result:");
gridbag.setConstraints(label1,constraints);
label1.setVisible(true);
label1.setBackground(Color.cyan);
label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
result = new TextField(" ",50);
gridbag.setConstraints(result,constraints); //applies constraints to text
result.setEditable(true);
result.setForeground(Color.black);
result.setBackground(Color.white);
result.setVisible(true);
add(result);
}
public void actionPerformed(ActionEvent e) {
String stringInput="";
String numOfVar="";
String temp="";
String temp1="";
int num=0;
if(e.getActionCommand() == "Enter"){ // IF Enter BUTTON IS CLICKED
stringInput = text.getText(); // GETS STRING INPUT FROM TEXT(MINTERMS)
numOfVar = text1.getText(); //GETS STRING INPUT FROM TEXT1(VARIABLES)
var = Integer.parseInt(numOfVar); //CONVERTS numOfVar TO INTEGER
StringTokenizer token= new StringTokenizer(stringInput," ,"); //TOKENIZE INPUT. ELIMINATE ALL COMMAS AND SPACES
while(token.hasMoreTokens()){ //WHILE THERE ARE MORE TOKENS
temp1=token.nextToken(); //GETS TOKEN
numbers++; //COUNTS THE NUMBER OF INPUTS
num=Integer.parseInt(temp1); //CONVERT INPUT TO INTEGER
temp=Integer.toBinaryString(num); //CONVERTS INTEGER FORM OF INPUT TO BINARY IN ITS PROPER LENGTH BASED ON THE NUMBER OF VARIABLES GIVEN
if(temp.length()!=var){
while(temp.length()!=var){
temp="0"+temp;
}
}
inputTerm.add(temp); //ADDS RESULT(BINARY FORM) TO inputTerm
}//end while
getPrimeImplicants(); //GET PRIMEIMPLICANTS
simplifymore(); // SIMPLIFY MORE
result.setText(finalT); // DISPLAYS THE RESULT (SIMPLIFIED) TO RESULT TEXTFIELD
}//end if
if(e.getActionCommand()== "Reset"){ //RESETS THE VALUES FOR NEXT SET OF INPUTS
var=0;
table=new ArrayList[5][5]; // SERVES AS OUR STORAGE FOR ARRANGING TERMS AND TO OUR RESULTING TERMS THAT ARE BEING COMPARED.
inputTerm= new Vector <String>(); // STORES OUR ORIGINAL INPUT/NUMBERS
resultingTerms= new Vector <String>(); //STORES THE RESULTING TERMS FOR EACH COMPUTATION
finalT=""; //STORES THE FINAL TERMS IN THEIR ALGEBRAIC FORM
numbers=0; //COUNTS THE NUMBER OF INPUTS FROM THE USER
text.setText(""); //ERASE THE TEXTS DISPLAYED ON THE TEXT FIELDS
text1.setText("");
result.setText("");
}
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {qWindow.setVisible(false);} //CLOSES THE WINDOW AFTER PROGRAMS STOPS RUNNING
public void windowClosing(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public class Term {
public String num;
public boolean used;
}
}//end class
I was told that I must remove the keyword static so I did and this one error happened. Can you please help me manipulate the code? I'm practicing OOP and I want to learn more about these static modifiers. Thank you very much!
When you use static you are saying there is no implied object I am using here. However you have not define Term as static, you you are saying it needs to b in an Object.
In your case the simplest thing to do is to make Term static as it doesn't appear to need to be non-static.
static class Term {
String num;
boolean used;
}
In general I would make nested classes static wherever possible. Partly for performance but mostly for clarity.
I must remove the keyword static
You must not remove the keyword static on the declaration of serialVersionUID.
You haven't confided in us which line of code gets that compile error, but clearly something around it also must be static.
Never just follow advice blindly. Always ask what it means and whether it really applies to everything you have done. There's a lot of cut-and-paste, programming-by-rote, and cargo-cult programming in this business. Don't be part of it, no matter where it comes from. Sadly a fair proportion of it is going to come from your colleagues and superiors. You have to learn how to deal with that.
Term is inner class so you create instance of inner class like below
Term term = qWindow.new Term();
More help available here
Related
I'm creating a code for Basic operations with sets of numbers the intention is for the user to input the maximum amount of elements posible in two sets of numbers then the code generates the amount of Jtext blank spaces necessary for the given maximum number in each set.
Then I requested the system to print the numbers given by the user and now I want to be able to create a Button for the user that can compare both arrays already given by printing something like "Both Sets are equal".
So how do I compare the arrays already inputed in this case?
Thanks in advance ยก
public void actionPerformed(ActionEvent e1) {
if(e1.getSource()==cubo){
try{
//Graphics g=getGraphics();
op = Integer.parseInt(operando.getText());
a = new JTextField [op];
int i;
for(i=0;i<op;i++){
a[i]=new JTextField(2);
panel1.add(a[i]);
a[i].setBounds(300,40+i*30, 50,20);
a[i].setText("");
}
}catch(NumberFormatException ex){
operando.setText("error");
}
}
if(e1.getSource()==leer){
h=new int [op];
int i;
for(i=0;i<op;i++){
int x = Integer.parseInt(a[i].getText());
h[i]=x;
}
for(i=0;i<op;i++){
System.out.println(h[i]);
}
}
////////////////////////////
if(e1.getSource()==cubo1){
try{
//Graphics g=getGraphics();
op1 = Integer.parseInt(operando.getText());
a1 = new JTextField [op1];
int i;
for(i=0;i<op1;i++){
a1[i]=new JTextField(2);
panel1.add(a1[i]);
a1[i].setBounds(350,40+i*30, 100,20);
a1[i].setText("");
}
}catch(NumberFormatException ex){
operando.setText("error");
}
}
if(e1.getSource()==leer1){
h1=new int [op1];
int i;
for(i=0;i<op1;i++){
int x = Integer.parseInt(a1[i].getText());
h1[i]=x;
}
for(i=0;i<op1;i++){
System.out.println(h1[i]);
}
}
One of the options is to convert both of the arrays to Set and and compare them using the equals() method,
new HashSet<int[]>(Arrays.asList(h)).equals(new HashSet<int[]>(Arrays.asList(h1)));
I wrote this java -fx program and it works perfectly without the recursive implementations. I wrote the button onAction lambda to ensure the program works correctly before converting to recursion. I've spent the last few hours trying to figure out the two required recursives and how to call them with the button.onAction lambda expression, but need a push in the right direction. Here's what I have.
static TextField textField = new TextField ();
static String text = textField.getText();
static TextArea textArea = new TextArea();
static Button btSubmit = new Button ("Submit");
#Override
public void start(Stage primaryStage){
Label label1 = new Label("Enter letters and I will "
+ "count the capitals.\t"); //Create textfield label.
textArea.setEditable(false);
textArea.setMaxWidth(450);
textArea.setMaxHeight(100);
HBox hbox = new HBox(); //Create hbox.
hbox.setAlignment(Pos.BASELINE_CENTER); //Set hbox to center.
hbox.getChildren().addAll(label1, textArea, textField,
btSubmit); //Add children to hbox.
BorderPane pane = new BorderPane(); //Create pane.
pane.setTop(hbox); //Set hbox to top of pane.
pane.setCenter(textArea); //Set text area to center.
Scene scene = new Scene (pane, 450, 200); //Create scene.
primaryStage.setTitle("Count Capital Letters");
primaryStage.setScene(scene);
primaryStage.show();
btSubmit.setOnAction(e -> {
String text = textField.getText();
int upperCase = 0;
for (int i = 0; i < text.length(); i++){
if (Character.isUpperCase(text.charAt(i))) upperCase++;
}
String numCaps = String.valueOf(upperCase);
textArea.appendText("Number of capitals: " + numCaps);
});
}
public static int count(char[] chars) {
String text = textField.getText();
chars = text.toCharArray();
if (chars.length == 0);
return 0;
}
public static int count(char[] chars, int high) {
high = 0;
String text = textField.getText();
chars = text.toCharArray();
for (int i = 0; i < chars.length; i++){
if (Character.isUpperCase(chars[i])) {
high++;
}
}
return high;
}
public static void main(String[] args){
launch(args);
}}
What I'm trying to do is have the button action call the recursive methods, but I'm confused on how to replace my current action with a call to the recursives.
After sleeping on it, here's what I've come up with for the two recursive methods. I knew I had two separate methods last night and that a recursive is supposed to call itself. Here's what I've changed so far.
Instead of the two separate methods:
public static int count(char[] chars, int high) {
int count = 0;
if (high < chars.length) {
if (Character.isUpperCase(chars[high])) {
return 1 + count;
}
else {
return count(chars, high+1);
}
}
return 0;
}
Am I at least on the right track? Being required to use the two recursive methods (original and its helper) is throwing me off.
It's not clear from your code what high is supposed to be. I would assume it's supposed to be the index of the last character in the character array you are going to examine (probably exclusive).
So your recursive step would really need to reduce high, not increase it, and you just examine chars[high-1] directly. You also need a termination step, which is when there are no more characters to look at.
So I would implement this as
private int count(char[] chars, int high) {
// if high==0 we are looking at zero characters, so there are no upper-case characters:
if (high == 0) {
return 0 ;
}
if (Character.isUpperCase(chars[high-1])) {
// if the last character we look at is upper-case, then the total
// for this set of characters is one more than the total for the
// set of characters omitting the last one:
return 1 + count(chars, high-1);
} else {
// otherwise (the last character is not upper-case), the total
// for this set of characters is the same as the total for the
// set of characters omitting the last one:
return count(chars, high-1);
}
}
For convenience, you could also implement
public int count(String text) {
return count(text.getChars(), text.length());
}
and then your event handler just needs to call
label1.setText("Number of upper case: "+count(textField.getText()));
(Why on earth you made everything static is a whole other discussion.)
I am creating a hangman game and I was having trouble getting the jlabel that contained each character of the word to update after the right letter button has been clicked. I have been having trouble with this as I am relatively new to working with Java Guis. Below is the action listener for the letter buttons.
private class LetterHandler implements ActionListener{
private char letterVal;
public LetterHandler(char lv){
letterVal = lv;
}
//checks if clicked button has the correct value as word char
public void actionPerformed(ActionEvent e){
for(int x = 1; x <= selectedWord.wordLength; x++){
if(selectedWord.wordValue.charAt(x - 1) == letterVal){
// JLabel letterValLabel = new JLabel(String.valueOf(letterVal));
wordSpacesArray.get(x-1).setName(String.valueOf(letterVal));
wordSpacesArray.get(x-1).revalidate();
continue;
}
else{
continue;
}
}
checkWin();
triesLeft--;
triesLeftLabel.revalidate();
}
//finds if all jlabels are complete or not
public void checkWin(){
for(int x = 1; x <= wordSpacesArray.size(); x++){
String charVal;
charVal = String.valueOf(wordSpacesArray.get(x-1));
if(charVal != "?"){
System.out.println("youWon");
System.exit(0);
}
else{
break;
}
charVal = null;
}
}
}
Any help is appreciated. Let me know if you need for of the programs code Thanks :)
There are some issues with the code. However, I'll first try to focus on your current problem:
I assume that wordSpacesArray is a list that contains the JLabels of individual letters of the word.
When this ActionListener will be notified, you try to update the labels in wordSpacesArray with the letter that corresponds to this button. However, in order to update the text that is shown on a JLabel, you have to call JLabel#setText(String) and not JLabel#setName(String). So the line should be
wordSpacesArray.get(x-1).setText(String.valueOf(letterVal));
// ^ Use setText here!
Now, concerning the other issues:
As pointed out in the comments, you should use 0-based indexing
The calls to revalidate are not necessary
The use of continue in its current for is not necessary
You should not compare strings with ==, but with equals
// if(charVal != "?") { ... } // Don't do this!
if(!charVal.equals("?")){ ... } // Use this instead
But the charVal in this case will be wrong anyhow: It will be the string representation of the label, and not its contents. So you should instead obtain the text from the label like this:
// String charVal = String.valueOf(wordSpacesArray.get(x-1)); // NO!
String charVal = wordSpacesArray.get(x-1).getText(); // Yes!
The triesLeftLabel will not be updated as long as you don't call setText on it
I think the logic of the checkWin method is flawed. You print "You won" when you find the first letter that is not a question mark. I think it should print "You won" when no letter is a question mark.
You should not call System.exit(0). That's a bad practice. Let your application end normally. (In this case, maybe by just disposing the main frame, although that would also be questionable for a game...)
So in summary, the class could probably look like this:
private class LetterHandler implements ActionListener
{
private char letterVal;
public LetterHandler(char lv)
{
letterVal = lv;
}
// checks if clicked button has the correct value as word char
#Override
public void actionPerformed(ActionEvent e)
{
for (int x = 0; x < selectedWord.wordLength; x++)
{
if (selectedWord.wordValue.charAt(x) == letterVal)
{
wordSpacesArray.get(x).setText(String.valueOf(letterVal));
}
}
checkWin();
triesLeft--;
triesLeftLabel.setText(String.valueOf(triesLeft));
}
// finds if all jlabels are complete or not
public void checkWin()
{
for (int x = 0; x < wordSpacesArray.size(); x++)
{
String charVal = wordSpacesArray.get(x).getText();
if (charVal.equals("?"))
{
// There is still an incomplete label
return;
}
}
// When it reaches this line, no incomplete label was found
System.out.println("You won");
}
}
I have a method that returns an arraylist which i am calling via a buttonListener. I need to be able to store each pushes resulting arraylist in another arraylist. How do I do this? Each time i try, it copies over the existing elements in the arraylist I'm using to keep track of push results.
private class ButtonListener implements ActionListener{
public void actionPerformed (ActionEvent e){
numCounter++;
String reqVal1 = requestor.getText();
int reqVal = Integer.parseInt(reqVal1);
request = reqVal;
requestsArray.get(3).set(0,0);
if(numCounter == 1){//---------------------------numCounter == 1 beginning-------- -------------------------
workingVar = memSize/2;
if(request>workingVar){
requestsArray.get(3).set(0,1);
}
else{
reqCounter++;
while (workingVar>=request){
workingVar = workingVar/2;
holes2.add(workingVar);
}
if(workingVar<request){
workingVar=workingVar*2;
holes2.add(workingVar);
holes2.remove(holes2.size()-2);
holes2.remove(holes2.size()-1);
}
}
e1=workingVar;
}//-----------------------------------------------end of numCounter == 1 section-------------------------------------
if(numCounter > 1){
for (int y = 0; y<requestsArray.get(0).size();y++){
if(requestsArray.get(1).get(y).equals("H")){
holes.add((Integer)requestsArray.get(0).get(y));
}
}
//BubbleSort of holes ArrayList
int in, out;
for(out= holes.size()-1; out>0;out--)
for(in =0; in<out;in++)
if(holes.get(in)<holes.get(in+1)){
int temp1 = holes.get(in+1);
int temp2 = holes.get(in);
holes.set(in, temp1);
holes.set(in+1, temp2);
}
//calculates the value of e1 using holes array
if(holes.isEmpty()){
requestsArray.get(3).set(0, 1);
}
else{
for(element=holes.size()-1;element>-1;element--){//starts at end of holes array loops backwards
e1 = holes.get(element); //assigns value of each element to e1
if(e1>=request) //if value e1 is greater than request stop looping
break;
}
workingVar=e1; //assign the value of e1 to workingVar
if (request>e1){
requestsArray.get(3).set(0, 1);
}
else{
//---------------------code for populating holes2 array---------------------------
reqCounter++;
if(workingVar!=request && workingVar/2>=request){
while (workingVar/2>=request){
workingVar = workingVar/2;
holes2.add(workingVar);
}
if(workingVar<request){
workingVar=workingVar*2;
holes2.add(workingVar);
}
}
}
}
}
//Sort of Holes2 ArrayList - reorder's holes2 for initial set up and subsequent inserts
int in, out;
for(out= holes2.size()-1; out>0;out--)
for(in =0; in<out;in++)
if(holes2.get(in)>holes2.get(in+1)){
int temp1 = holes2.get(in+1);
int temp2 = holes2.get(in);
holes2.set(in, temp1);
holes2.set(in+1, temp2);
}
//-------------------------------requestsArray Setups----------------------------------------------------
//Initial setup of requestsArray
if(numCounter == 1){
if(requestsArray.get(3).get(0).equals(0)){
requestsArray.get(0).set(0,e1);
requestsArray.get(1).set(0,"R");
requestsArray.get(2).set(0, reqCounter);;
for(int i = 0; i<holes2.size();i++){
requestsArray.get(0).add(holes2.get(i));
requestsArray.get(1).add("H");
requestsArray.get(2).add(0);
}
}
else{
requestsArray.get(0).set(0,e1);
requestsArray.get(1).set(0, "H");
requestsArray.get(2).set(0,0);
}
}
//Subsequent setup of requestsArray
int element2;
if(numCounter >1 && requestsArray.get(3).get(0).equals(0)){
for(element2 = 0; element2< requestsArray.get(0).size(); element2++){
if((Integer)requestsArray.get(0).get(element2)==e1 &&requestsArray.get(1).get(element2).equals("H") ){
break;
}
}
if(holes2.isEmpty()){
requestsArray.get(1).set(element2, "R");
requestsArray.get(2).set(element2, reqCounter);
}
else{ //holes2 is not empty
requestsArray.get(0).add(element2, workingVar);
requestsArray.get(2).add(element2,reqCounter);
requestsArray.get(1).add(element2, "R");
requestsArray.get(0).remove(element2+1);
requestsArray.get(2).remove(element2+1);
requestsArray.get(1).remove(element2+1);
for(int i = 1; i<holes2.size()+1;i++){
requestsArray.get(0).add(element2+i,holes2.get(i-1));
requestsArray.get(1).add(element2+i,"H");
requestsArray.get(2).add(element2+i,0);
}
}
}
//-----------------End Section for populating requestsArraywhen numCounter > 1---------------------------
//remove all values from holes1 and holes2
holes.clear();
holes2.clear();
System.out.println(results1);
ok. I have written a similar program that is simpler and easier to understand. Each time the button is pressed, the result is saved as an arrayList to another arrayList. Problem is it's appending it to the previous element. I need to be able to add the results of each press as a separate element. For example:
first press:
[5, 3, 5, 2, 6, 5]
second press would display:
[5, 3, 5, 2, 6, 5][2, 1, 4, 1, 4, 1]
This way I can loop through and get each array result separately. How do I do this?
public class mainClass{
public static void main(String[] args){
JFrame frame1 = new JFrame("testButton");
frame1.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);
buttonExample b1 = new buttonExample();
frame1.getContentPane().add(b1);
frame1.pack();
frame1.setVisible(true);
}
}
public class Example {
private int rand1;
private ArrayList<ArrayList> count;
private ArrayList<Integer> count2;
private Random rnd;
private int counter1;
private ArrayList<ArrayList>count3;
public Example(){
count = new ArrayList<ArrayList>();
count2 = new ArrayList<Integer>();
rnd = new Random();
count3 = new ArrayList<ArrayList>();
}
private void addCount2(){
for(int x = 0; x<6;x++){
rand1 = rnd.nextInt(6)+1;
count2.add(rand1);// count2 == Integers
}
}
public void addCount(){
addCount2();
count.add(count2);// count == count3
}
public ArrayList<ArrayList> displayCount(){
return count;
}
}
public class buttonExample extends JPanel {
private JButton button1;
private Example example1;
public buttonExample(){
button1 = new JButton("Submit");
add(button1);
button1.addActionListener(new ButtonListener());
example1 = new Example();
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
example1.addCount();
System.out.println(example1.displayCount().get(0));;
}
}
}
I would think about at least two solutions...
create a List<...> list which will last (global variable or something similar, depends on your needs) and use list.addAll() method
create a Map<String, List<...> map and than you can log your lists separately, your key might be a timestamp for example
Well, now when you posted the code you will have to start with a different thing - refactoring. Your code is very long, difficult to read and error prone. You have to think about it a little bit a rewrite it. And trust me, the more effort you put into your code at the beginning the better it will be at the end. Otherwise you may end up with an unmanagable code full of bugs...
I've just started learning Java, so I apologize if this question is somewhat basic, and I'm sure my code is not as clean as it could be. I've been trying to write a small quiz program that will input a list of German verbs from a txt file (verblist.txt). Each line of the text file contains five strings: the German verb (verbger), the English translation (verbeng), the praeteritum and perfekt conjugations conjugations (verbprae and verbperf) and whether it uses haben or sein as the auxiliary verb (H or S, stored as verbhaben). The verb set is chosen by generating a random number and selecting the "row" of the two dimensional array. The GUI then displays the first two variables, and the user has to input the last three. If the last three match the values in the txt file, the user gets it correct and moves on to another verb.
I'm at the point where the code is working the way I want it to - for one verb. The way I've been organizing it is in two classes. One, VerbTable, imports the text file as a two dimensional array, and the other, RunVerb, generates the GUI and uses an ActionListener to compare the user input to the array. What I can't figure out now is how, after the user gets one verb set correct, I can then loop through the entire set of verbs.
I was thinking of creating a for loop that loops through the number of rows in the text file (saved in the code as height), generating a new random number each time to select a different verb set (or "row" in the two dimensional array.) Essentially, I'd like to get a loop to run through the entire VerbRun class, and pause for the ActionListener, until all of the verb sets have been displayed.
Here is the VerbTable class, which generates the array and random number to select the row:
package looptest;
import java.io.*;
import java.util.*;
public class VerbTable {
public int width;
public int height;
public int randnum;
public String verbger = new String("");
public String verbeng = new String("");
public String verbprae = new String("");
public String verbperf = new String("");
public String verbhaben = new String("");
public VerbTable() {
File file = new File("verblist.txt");
try {
/* For array height and width */
Scanner scanner1 = new Scanner(file).useDelimiter("\n");
int height = 0;
int width = 0;
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
height++;
String[] line3 = line.split("\t");
width = line3.length;
}
System.out.println("Height: " + height);
System.out.println("Width: " + width);
this.width = width;
this.height = height;
/* Array height/width end */
/* random number generator */
int randnum1 = 1 + (int)(Math.random() * (height-1));
this.randnum = randnum1;
/* random number generator end */
Scanner scanner = new Scanner(file).useDelimiter("\n");
String verbtable[][];
verbtable = new String[width][height];
int j = 0;
while (scanner.hasNextLine()){
String verblist2 = scanner.next();
String[] verblist1 = verblist2.split("\t");
System.out.println(verblist2);
verbtable[0][j] = verblist1[0];
verbtable[1][j] = verblist1[1];
verbtable[2][j] = verblist1[2];
verbtable[3][j] = verblist1[3];
verbtable[4][j] = verblist1[4];
j++;
}
this.verbger = verbtable[0][randnum];
this.verbeng = verbtable[1][randnum];
this.verbprae = verbtable[2][randnum];
this.verbperf = verbtable[3][randnum];
this.verbhaben = verbtable[4][randnum];
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
public int getRand(){
return this.randnum;
}
public int getWidth(){
return this.width;
}
public int getHeight(){
return this.height;
}
public String getVerbger(){
return this.verbger;
}
public String getVerbeng(){
return this.verbeng;
}
public String getVerbprae(){
return this.verbprae;
}
public String getVerbperf(){
return this.verbperf;
}
public String getVerbhaben(){
return this.verbhaben;
}
public static void main(String[] args) throws IOException {
}
}
And here is the RunVerb class:
package looptest;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RunVerb extends JFrame {
VerbTable dimensions = new VerbTable();
int width = dimensions.getWidth();
int height = dimensions.getHeight();
int randnum = dimensions.getRand();
String verbgerin = dimensions.getVerbger();
String verbengin = dimensions.getVerbeng();
String verbpraein = dimensions.getVerbprae();
String verbperfin = dimensions.getVerbperf();
String verbhabenin = dimensions.getVerbhaben();
String HabenSeinSelect = new String("");
public JTextField prae = new JTextField("",8);
public JTextField perf = new JTextField("",8);
public JLabel verbger = new JLabel(verbgerin);
public JLabel verbeng = new JLabel(verbengin);
public JRadioButton haben = new JRadioButton("Haben");
public JRadioButton sein = new JRadioButton("Sein");
public RunVerb() {
JButton enter = new JButton("Enter");
enter.addActionListener(new ConvertBtnListener());
prae.addActionListener(new ConvertBtnListener());
perf.addActionListener(new ConvertBtnListener());
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(verbger);
verbger.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20));
content.add(verbeng);
verbeng.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 40));
content.add(new JLabel("Praeteritum:"));
content.add(prae);
content.add(new JLabel("Perfekt:"));
content.add(perf);
content.add(haben);
haben.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 10));
haben.setSelected(true);
content.add(sein);
sein.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
ButtonGroup bg = new ButtonGroup();
bg.add(haben);
bg.add(sein);
content.add(enter);
setContentPane(content);
pack();
setTitle("Verben");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class ConvertBtnListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String outprae = prae.getText();
int praenum = 0;
if (outprae.equals(verbpraein)){
praenum = 1;
}
String outperf = perf.getText();
int perfnum = 0;
if (outperf.equals(verbperfin)){
perfnum = 1;
}
boolean habenselect = haben.isSelected();
boolean seinselect = sein.isSelected();
if (habenselect == true){
HabenSeinSelect = "H";
}
else {
HabenSeinSelect = "S";
}
int habennum = 0;
if (HabenSeinSelect.equals(verbhabenin)) {
habennum = 1;
}
int numtot = praenum + perfnum + habennum;
if (numtot == 3){
System.out.println("Correct.");
}
else{
System.out.println("Incorrect.");
}
numtot = 0;
}
}
public static void main(String[] args) {
window.setVisible(true);
}
}
So what would be the best way to cycle through the entire verbtable array until all of the rows have been displayed? Should I create a for loop, and if so, where should it go? Should I make a new class that contains the loop and references the VerbRun class? If so, what would be the best way to go about it?
I hope this makes sense! Thank you!
To go through all the verbs exactly in a random order, you may not want to generate random numbers each time, as the random number can repeat. You have to create a random permutation of verbs, one way to do it is Collections.shuffle
see http://download.oracle.com/javase/6/docs/api/java/util/Collections.html
Also You dont have to create a new RunVerb Object, instead create once, and use setters to change the UI, and the functionality of Action Listeners. So pseudo code would be
Collections.shuffle(verbsList);
for(verb : verbsList)
{
setLabel1(verb[0]);
setLabel2(verb[1]);...
}
I would have a method like getNextRandomVerb() in then VerbTable class that generates the next verb to be shown. It will keep track of the verbs that have been shown ( for a given user-session ofcourse ) already and ensure the next one picked is not a repeat. Your RunVerb class seems to more responsible for managing the GUI , so this is not the place to define how to get the next verb to display.