Related
I'm developing a simple game where all the images are randomized. I've noticed that some of the image are repeated although I have put the random code. I'm still new to Java. I hope that someone can help me solve my problem. Below is my coding.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Random;
import javax.swing.*;
public class Task1 extends JFrame implements KeyListener,ActionListener {
JFrame frame = new JFrame("FYP");
JTextField textField = new JTextField();
JButton btnNext = new JButton("NEXT");
int sum=0;
int Error=0;int total_test = 0;
static String inputID;
static int index;
String[] imgFileHP = {"1.jpg","3.jpg","4.jpg","7.jpg","9.jpg","10.jpg","12.jpg","16.jpg","17.jpg","18.jpg"};
String[] imgNo = {"5","4","6","3","5","3","4","4","6","6"};
int randomNo;
Random rand = new Random();
public Task1(String inputID)
{
frame.setSize(2200,2500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
Task(inputID);
}
public void Task(String inputID)
{
JPanel panel = new JPanel();
JLabel labelUsername = new JLabel("");
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setBackground(Color.WHITE);
Collections.shuffle(Arrays.asList(imgFileHP));
Set<Integer> uniqueList = new HashSet<Integer>();//This would create list with the number 0 to 9
for(int count=0;count<imgFileHP.length;count++){
uniqueList.add(count);
labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[count])));
if(!uniqueList.isEmpty()){
index = (int) (Math.random() * (upper - lower)) + lower;
if(uniqueList.contains(index)){
uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
System.out.println(imgFileHP[r]);//This printf statement is just for your reference
}
}
}
textField.setText("");
textField.setColumns(10);
textField.addKeyListener(this);
btnNext.addActionListener(this);
panel.add(labelUsername);
panel.add(textField);
panel.add(btnNext);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(!textField.getText().equals("")){
total_test += 1;
if(isNumeric(textField.getText())){
//********************Correct Integer**********************
if(Integer.valueOf(imgNo[randomNo])==Integer.valueOf(textField.getText())){
//********************Correct Answer**********************
System.out.println("Correct");
sum+=1;
}else{
//********************Incorrect Answer**********************
System.out.println("Incorrect");
Error+=1;
}
refreshFrame();
}else{
//********************Incorrect Integer/Alphabet**********************
System.out.println("Invalid");
Error+=1;
refreshFrame();
}
}else{
System.out.println("Null Input");
}
//System.out.println(Integer.valueOf(imgNo[randomNo]));
}
public void refreshFrame(){
if(total_test>=10){
// add result page to see how many score
//Task2(sum, Error);
System.out.println("Correct: "+sum+" Incorrect: "+Error);
frame.dispose();
}else{
btnNext.removeActionListener(this);
frame.getContentPane().removeAll();
getContentPane().removeAll();
Task(inputID);
}
}
public static void main(String args[]) {
Task1 a = new Task1(inputID);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public static boolean isNumeric(String str)
{
try
{
Integer.valueOf(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
EDIT part (But some of the image is still repeating.)
Collections.shuffle(Arrays.asList(imgFileHP));
Set<Integer> uniqueList = new HashSet<Integer>();//This would create list with the number 0 to 9
for(int count=0;count<imgFileHP.length;count++){
uniqueList.add(count);
}
if(!uniqueList.isEmpty()){
index = (int) (Math.random() * (upper - lower)) + lower;
randomNo = index;
if(uniqueList.contains(index)){
labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[index])));
uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
System.out.println(imgFileHP[r]);//This printf statement is just for your reference
}
}
Here is how Random works. Even though you have mentioned rand.nextInt(10);but everytime it gets called, there is not pre-defined rule in java that it has to generate unique numbers and not the duplicate the previously generated ones.
For Example:
when you call -
int index = rand.nextInt(10); // Index could be 2
index = rand.nextInt(10); // Now again the value could be 2 as well
So what you need to do is you have to add an extra piece of code to check the uniqueness every time random is called.
Since you want to generate numbers between 0 to 10. Try the following code, it might help you understand.
String[] imgFileHP = {"1.jpg","3.jpg","4.jpg","7.jpg","9.jpg","10.jpg","12.jpg","16.jpg","17.jpg","18.jpg"};
int upper = imgFileHP.length;
int lower = 0;
int r=0;
int index=0;
Set<Integer> uniqueList = new HashSet<Integer>();//This would create list with the number 0 to 9
for(int count=0;count<imgFileHP.length;count++){
uniqueList.add(count);
}
if(!uniqueList.isEmpty()){
index = (int) (Math.random() * (upper - lower)) + lower;
if(uniqueList.contains(index)){
uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
System.out.println(imgFileHP[r]);//This printf statement is just for your reference
}
}
Another easier method is to use Collections.Shuffle as shown below:
Collections.shuffle(Arrays.asList(imgFileHP));
Example of Collection.shuffle().
Lets say you have an array String[] arr = {"abc","def","xyz","bla"}
when you do Collections.shuffle(Arrays.asList(arr));
then print array from index 0 to 3. Array might be shuffled something like this: {"def","bla","abc","xyz"}
**EDIT 2:**Solution based on your edit in main code:
for(int count=0;count<imgFileHP.length;count++){//first add the counters into List
uniqueList.add(count);
}
if(!uniqueList.isEmpty()){
index = (int) (Math.random() * (upper - lower)) + lower;
if(uniqueList.contains(index)){
labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[index])));
uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
System.out.println(imgFileHP[r]);//This printf statement is just for your reference
}
}
I am creating a program to take in 1 or more 8 bit binary sequences and convert them into 12 bit hamming binary sequences. The code works and achieves everything right up until it tries to put the information into the JTextField at which point it converts the 8-bit stream into 1111 1111 and converts the 12 bit stream into 0000 0000 0000 (spacing for easier reading). I have tried stepping through the code and at every point it thinks the list is correct, right until i turn it into a string. Im not sure if im incorrectly using something but hopefully someone can help.
As an example for those who dont understand hamming codes. If you put in "10101010" no spaces, the system should spit out "Your original bit-stream was: 1010 1010 Your new Hamming bit-stream is: 1010 0101 1000"
But instead it will say "Your original bit-stream was: 1111 1111 Your new Hamming bit-stream is: 0000 0000 0000"
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
#SuppressWarnings("serial")
public class MainProgram extends JPanel {
private static final String INITIAL_TITLE = "Please enter your next 8 bits. "
+ "Do not enter more than 8 bits.\n"
+ "Press Enter when done";
private static final String ARE_YOU_FINISHED = "Are you finished entering streams?";
private static final String CALCULATING = "Just one moment while the code is generated...";
private static final String YES = "YES";
private static final String ENTER = "ENTER";
private static final String NO = "NO";
private static final String CONTINUE = "CONTINUE";
private static int GAP = 12;
private static final int COLUMNS = 35;
private static int TEMP_STREAM = 0;
static int numberOfStreams = 0;
static int counter = 0;
static String OriBuild;
static String NewBuild;
// this is a JTextArea built to look like a JLabel
private JTextArea topTextArea = new JTextArea(2, COLUMNS);
private JTextField dataEntryField = new JTextField(COLUMNS);
private JTextArea dataPrinter = new JTextArea(2,2);
private JButton yesEnterButton = new JButton(ENTER);
private JButton noButton = new JButton(NO);
private JButton contButton = new JButton(CONTINUE);
private boolean enteringData = true;
private boolean dataValidYet = false;
java.util.List<Integer> streamSplit = new ArrayList<>();
java.util.List<Integer> tempEight = new ArrayList<>();
java.util.List<Integer> finalStream = new ArrayList<>();
public MainProgram(){
yesEnterButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
yesEnterButtonActionPerfromed(e);
}
});
noButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
noButtonActionPerfromed(e);
}
});
contButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
contButtonActionPerfromed(e);
}
});
topTextArea.setWrapStyleWord(true);
topTextArea.setLineWrap(true);
topTextArea.setFocusable(false);
topTextArea.setEditable(false);
topTextArea.setOpaque(false);
topTextArea.setText(INITIAL_TITLE);
JPanel innerButtonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
innerButtonPanel.add(yesEnterButton);
innerButtonPanel.add(contButton);
innerButtonPanel.add(noButton);
contButton.setVisible(false);
noButton.setVisible(false);
JPanel outerButtonPanel = new JPanel();
outerButtonPanel.add(innerButtonPanel);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(topTextArea, BorderLayout.PAGE_START);
add(dataEntryField, BorderLayout.LINE_END);
dataPrinter.setVisible(false);
add(dataPrinter, BorderLayout.LINE_START);
add(outerButtonPanel, BorderLayout.PAGE_END);
}
protected void noButtonActionPerfromed(ActionEvent e) {
if(!dataValidYet){
enteringData = true;
topTextArea.setText(INITIAL_TITLE);
noButton.setVisible(false);
dataEntryField.setVisible(true);
return;
}
// Pressing no allows more entry
}
private void yesEnterButtonActionPerfromed(ActionEvent e) {
if (enteringData) {
topTextArea.setText(ARE_YOU_FINISHED);
yesEnterButton.setText(YES);
yesEnterButton.setActionCommand(YES);
noButton.setVisible(true);
TEMP_STREAM = checkInput();
enteringData = false;
dataEntryField.setText("");
dataEntryField.setVisible(false);
streamAdd();//This function adds the stream (example: 10101010) to a list creating individual digits of 1,0,1,0,1,0,1,0
return;
}//pressing enter takes the value in box. Pressing yes causes the system to move on
else{
dataValidYet = true;
yesEnterButton.setVisible(false);
noButton.setVisible(false);
logicLaunch();//converts the 8 digit binary into a 12 digit hamming code
contButton.setVisible(true);
}
}
private void contButtonActionPerfromed(ActionEvent e) {
//This groups the 8 original individual digits, that were seperated into a list, back into a string for printing purposes
if(counter < numberOfStreams) {
dataPrinter.setVisible(true);
dataEntryField.setVisible(false);
OriBuild = ("Your original bit-stream was: "
+ streamSplit.get(counter * 0)
+ streamSplit.get(counter * 1)
+ streamSplit.get(counter * 2)
+ streamSplit.get(counter * 3) + " "
+ streamSplit.get(counter * 4)
+ streamSplit.get(counter * 5)
+ streamSplit.get(counter * 6)
+ streamSplit.get(counter * 7));
NewBuild = ("Your new Hamming bit-stream is: "
//This groups the 12 new individual digits, that were seperated into a list, back into a string for printing purposes
+ finalStream.get(counter * 0)
+ finalStream.get(counter * 1)
+ finalStream.get(counter * 2)
+ finalStream.get(counter * 3) + " "
+ finalStream.get(counter * 4)
+ finalStream.get(counter * 5)
+ finalStream.get(counter * 6)
+ finalStream.get(counter * 7) + " "
+ finalStream.get(counter * 8)
+ finalStream.get(counter * 9)
+ finalStream.get(counter * 10)
+ finalStream.get(counter * 11));
System.out.println(OriBuild + " " + NewBuild);
dataPrinter.setText(OriBuild + "\n" + NewBuild);
counter++;
//Prints the strings to the screen so that the user can retrieve wanted information. Then adds 1 to the counter incase more than 1 stream was entered to cycle
} else {
dataPrinter.setText("Program complete. Close and relaunch to re-use");
contButton.setVisible(false);
//Once out of streams program finishes on this informing user that its reached the end of its usefulness and require re-launching.
}
}
private static void createAndShowGui() {
MainProgram mainPanel = new MainProgram();
JFrame frame = new JFrame("HammingCode");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public int checkInput()
{
String temp1 = dataEntryField.getText();
int temp = Integer.parseInt(temp1);
return temp;
}
public void streamAdd(){
do {
streamSplit.add(TEMP_STREAM % 10);
TEMP_STREAM /= 10;
} while (TEMP_STREAM != 0);
}
public void logicLaunch(){
topTextArea.setText(CALCULATING);
int arrayLength = streamSplit.size();
int bufferLength = 8 - arrayLength % 8;
if (bufferLength != 8)
{
numberOfStreams = arrayLength / 8 + 1;
} else
{
numberOfStreams = arrayLength / 8;
}
int tempStreams = numberOfStreams;
System.out.println(numberOfStreams + "<Streams Buffer>" + bufferLength);
while (bufferLength > 0 && bufferLength != 8)
{
streamSplit.add(0);
bufferLength--;
}
while (tempStreams > 0)
{
for (int i = 0; i < 8; i++)
{
tempEight.add(streamSplit.get(i));
}
if ((tempEight.get(0) + tempEight.get(1) + tempEight.get(3) + tempEight.get(4) + tempEight.get(6)) % 2 == 0)
{
tempEight.add(0, 0);
} else
{
tempEight.add(0, 1);
}
if ((tempEight.get(1) + tempEight.get(3) + tempEight.get(4) + tempEight.get(6) + tempEight.get(7)) % 2 == 0)
{
tempEight.add(1, 0);
} else
{
tempEight.add(1, 1);
}
if ((tempEight.get(3) + tempEight.get(4) + tempEight.get(5) + tempEight.get(9)) % 2 == 0)
{
tempEight.add(3, 0);
} else
{
tempEight.add(3, 1);
}
if ((tempEight.get(7) + tempEight.get(8) + tempEight.get(9) + tempEight.get(10)) % 2 == 0)
{
tempEight.add(7, 0);
} else
{
tempEight.add(7, 1);
}
tempStreams--;
for (int i = 0; i < 12; i++)
{
finalStream.add(tempEight.get(0));
tempEight.remove(0);
}
}
Collections.reverse(streamSplit);
}//Runs all the logic to generate the 12 bit code, this part is working fine. Reverse is for formatting purposes
}
I haven't figured out the code entirely, but it appears your use of counter in contButtonActionPerfromed is incorrect. When counter is 0, it will get element 0 every time; when 1 it will get 0, 1, 2, etc.; when 2 it will get 0, 2, 4, etc. Then there's something about exiting the program after the first time, so maybe you don't go through it a second time (and a third time would likely generate an error attempting to access a non-existent element).
You really ought to be able to debug that method...
The title is not my entire question. I know HOW to organize code, theoretically, but i would like some specific, USEFUL, pointers. Please read on before griping.
I'm a beginner to java and OOP (object oriented programming) and I would really like to learn how to better organize my code! Over the course of a month or two, I made a calculator program with little functions I thought of here and there with a few small jokes built into it. After looking at it a second time I realized that it is extremely poorly formatted and almost incomprehensible.If I may, I would like to ask some more experienced programmers to point me in the right direction on what I should do to fix it (for example, what things can I turn into objects, Where can I compartmentalize, etc).
Please note that this is my FIRST time posting on a forum like this so if i need to clarify something for you to help me, I've done something wrong, I'm asking for too much, please tell me so i can resolve it and i can get help. Please dont just mark this as invalid and file it away to oblivion (as often happens in stackoverflow). Also, before anyone asks, NO this is NOT homework, it is the product of my own crack at teaching myself java (probably why its not working too well).
Here is the source code:
// This is the original Calculator code without objects in a single class. not really efficient...
package randomClasses;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
#SuppressWarnings("serial")
public class CalcClass
extends JFrame
implements ActionListener {
JPanel[] row = new JPanel[6];
JButton[] button = new JButton[21];
String[] buttonString = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "/", "C", "v", "+/-", "=", "0", "Parabola", "x^y"};
int[] dimW = {300, 45, 100, 90, 180};
int[] dimH = {35, 40};
Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);
Dimension parabolaDimension = new Dimension(dimW[4], dimH[0]);
//formatting variables
int var = 0;
double x = 0;
String stor = "";
boolean initial = true;
//variables for Parabola function
int countEquals_parab = 0;
double Angle = 0;
double Vi = 0;
double Vx = 0;
double Vy = 0;
double T_max = 0;
double Y_displ = 0;
double X_displ = 0;
double h = 0;
double k = 0;
double a_parab = 0;
boolean parabComplete = true;
boolean parabola = false;
DecimalFormat df = new DecimalFormat("#######.#####");
//variables for addressing illegal typing issues
boolean typeNum = true;
boolean typeDot = true;
JFrame frame; //for parabolaInstructions
//original calculator variables
boolean[] function = new boolean[5];
double[] temporary = {0, 0}; //store on screen values
double result = 0; //store result
public JTextArea display = new JTextArea(1, 20);
Font font = new Font("Times new Roman", Font.BOLD, 14);
CalcClass() {
super("CalcClass");
setDesign();
setSize(380, 300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(6, 5);
setLayout(grid);
for(int i = 0; i < 5; i++) {
function[i] = false;
}
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER, 1, 1);
for(int i = 0; i < 6; i++) {
row[i] = new JPanel();
}
row[0].setLayout(f1);
for(int i = 1; i < 6; i++) {
row[i].setLayout(f2);
}
for(int i = 0; i < 21; i++) {
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 14; i++) {
button[i].setPreferredSize(regularDimension);
}
for(int i = 14; i < 18; i++) {
button[i].setPreferredSize(rColumnDimension);
}
button[18].setPreferredSize(zeroButDimension);
button[19].setPreferredSize(parabolaDimension);
button[20].setPreferredSize(rColumnDimension);
row[0].add(display);
add(row[0]);
for(int i = 0; i < 4; i++) {
row[1].add(button[i]);
}
row[1].add(button[14]);
add(row[1]);
for(int i = 4; i < 8; i++) {
row[2].add(button[i]);
}
row[2].add(button[15]);
add(row[2]);
for(int i = 8; i < 12; i++) {
row[3].add(button[i]);
}
row[3].add(button[16]);
add(row[3]);
row[4].add(button[18]);
for(int i = 12; i < 14; i++) {
row[4].add(button[i]);
}
row[4].add(button[17]);
add(row[4]);
row[5].add(button[19]);
row[5].add(button[20]);
add(row[5]);
setVisible(true);
}
public void getSqrt() {
stor = "";
initial = true;
try {
double value = Double.parseDouble(display.getText());
if(value == -100) {
format("John's Girlfriend");
} else {
value = Math.sqrt(Double.parseDouble(display.getText())); //create a value for variable, and use Maths square root to find the value
format(Double.toString(value)); //Sets display to new value
}
} catch(NumberFormatException e) {
}
typeDot = false;
typeNum = false;
}
public void getPosNeg() {
stor = "";
initial = true;
try {
double value = Double.parseDouble(display.getText()); //again creating a variable for current value
if(value != 0) { //if value is not equal to zero
value = (-1) * value; //multiplied by -1 to change the sign
format(Double.toString(value)); //Sets display to new value
} else {
}
} catch(NumberFormatException e) {
}
}
public void getResult() {
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp00 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp00[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp11 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp11[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
functions();
clear();
format(Double.toString(result));//display has a result
for(int i = 0; i < 5; i++) {
function[i] = false; //set all functions to false
}
} catch(NumberFormatException e) {
}
typeNum = false;
}
public void functions() {
if(function[2] == true) { //multiplication
result = temporary[0] * temporary[1];
} else if(function[3] == true) { //division
result = temporary[0] / temporary[1];
} else if(function[0] == true) { //addition
result = temporary[0] + temporary[1];
} else if(function[1] == true) { //subtraction;
result = temporary[0] - temporary[1];
} else if(function[4] == true) {
result = Math.pow(temporary[0], temporary[1]);
} else {
result = temporary[1];
}
}
double a_quadratic = 0;
double b = 0;
double c = 0;
double x1 = 0;
double x2 = 0;
double discr = 0;
int countEquals_quadratic = 0;
public void quadraticFormula() {
if(countEquals_parab == 0) {
a_quadratic = Double.parseDouble(display.getText());
clear();
display.setText("b = ");
}
if(countEquals_parab == 1) {
b = Double.parseDouble(display.getText());
display.setText("c = ");
}
if(countEquals_parab == 2) {
c = Double.parseDouble(display.getText());
discr = (Math.pow(b, 2) - 4 * a_quadratic * c); //stores the value of the discriminant
if(discr >= 0) {
x1 = (-b + Math.sqrt(b * b - 4 * a_quadratic * c)) / (2 * a_quadratic);
x2 = (-b - Math.sqrt(b * b - 4 * a_quadratic * c)) / (2 * a_quadratic);
}
}
}
public void parabolaButton() {
double G = 9.81;
if(countEquals_parab == 0) {
Vi = Double.parseDouble(display.getText());
clear();
display.setText("Angle of release: ");
}
if(countEquals_parab == 1) {
Angle = Double.parseDouble(display.getText());
if((Angle > 90.0) || (Angle < 0.0)) {
display.setText("Sorry, not a valid angle");
countEquals_parab = 3;
} else {
Angle = (Math.PI / 180.0) * Angle; //converting degrees into radians
Vx = Vi * Math.cos(Angle); //Calculating x component
Vy = Vi * Math.sin(Angle); //Calculating y component
//Finding time
T_max = Vy / G; //time to max height
//Calculating vertex coordinates
Y_displ = (Vy * Vy / (2 * G));
X_displ = Vx * T_max;
//finding a
a_parab = (-Y_displ) / (X_displ * X_displ);
display.setText("The equation of the parabola is \ny = " + df.format(a_parab) + "(x - " + df
.format(h) + ")^2 + " + df.format(k));
}
}
if(countEquals_parab == 2) {
display.setText("Time to get to max height = " + df.format(T_max));
}
if(countEquals_parab == 3) {
clearFunction();
countEquals_parab = -1;
parabola = false;
parabComplete = true;
}
countEquals_parab++;
}
public void var() {
var++;
if(var > 8) {
var = 1;
}
if(var == 1) {
format("x");
}
}
public final void setDesign() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
public void format(String get) {
//get stores the incoming values temporarily
//get is transferred to a new value for permanent storage
//print the permanent storage value
//new number is added, stored temporarily in get
//get is added to permanent storage
//print permanent storage value
double spaceFix = 0;
if(initial == true) {
stor = get;
initial = false;
} else if(initial == false) {
stor = stor + get;
}
spaceFix = stor.length() / 4;
int numberOfSpaces = 56 - stor.length() + (int) spaceFix;
String format = String.format("%" + numberOfSpaces + "s", stor);
display.setText(format);
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0]) {
numberButtons("7");
}
if(ae.getSource() == button[1]) {
numberButtons("8");
}
if(ae.getSource() == button[2]) {
numberButtons("9");
}
if(ae.getSource() == button[3]) {
operatorButtons(0); //add function[0]
}
if(ae.getSource() == button[4]) {
numberButtons("4");
}
if(ae.getSource() == button[5]) {
numberButtons("5");
}
if(ae.getSource() == button[6]) {
numberButtons("6");
}
if(ae.getSource() == button[7]) {
operatorButtons(1); //subtract function[1]
}
if(ae.getSource() == button[8]) {
numberButtons("1");
}
if(ae.getSource() == button[9]) {
numberButtons("2");
}
if(ae.getSource() == button[10]) {
numberButtons("3");
}
if(ae.getSource() == button[11]) {
operatorButtons(2); //multiplication function[2]
}
if(ae.getSource() == button[12]) {
if(typeDot == false) {
} else {
numberButtons(".");
typeDot = false;
}
}
if(ae.getSource() == button[13]) {
operatorButtons(3); //divide function[3]
}
if(ae.getSource() == button[14]) {
clearFunction();
parabola = false;
parabComplete = true;
}
if(ae.getSource() == button[15]) {
getSqrt();
}
if(ae.getSource() == button[16]) {
getPosNeg();
}
if((ae.getSource() == button[17]) && display.getText().equals("")) {
} else if((ae.getSource() == button[17]) && (parabola == false)) {
getResult();
} else if((ae.getSource() == button[17]) && (parabola == true)) {
parabolaButton();
}
if(ae.getSource() == button[18]) {
numberButtons("0");
}
if(ae.getSource() == button[19]) {
clearFunction();
parabolaInstructions();
parabola = true;
parabComplete = false;
display.setText("Initial velocity: ");
}
if(ae.getSource() == button[20]) {
operatorButtons(4);//powerFunction();
}
}
public void parabolaInstructions() {
//Create the dialog.
final JDialog dialog = new JDialog(frame, "How to use the Parabola function");
//Add contents to it. It must have a close button,
//since some L&Fs (notably Java/Metal) don't provide one
//in the window decorations for dialogs.
JLabel label = new JLabel("<html><p align=center>" + "Step 1: Type in the initial velocity and press the \"=\" button<br>" + "Step 2: Type in the angle of Release (make sure that it is between 0 and 90)<br>" + "Step 3: Press the \"=\" button to scroll through the results<br>" + "Step 4: Profit");
label.setHorizontalAlignment(JLabel.CENTER);
Font font = label.getFont();
label.setFont(label.getFont().deriveFont(font.PLAIN, 14.0f));
JButton closeButton = new JButton("Ok");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
JPanel closePanel = new JPanel();
closePanel.setLayout(new BoxLayout(closePanel, BoxLayout.LINE_AXIS));
closePanel.add(Box.createHorizontalGlue());
closePanel.add(closeButton);
closePanel.setBorder(BorderFactory.
createEmptyBorder(0, 0, 5, 5));
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(label, BorderLayout.CENTER);
contentPane.add(closePanel, BorderLayout.PAGE_END);
contentPane.setOpaque(true);
dialog.setContentPane(contentPane);
//Show it.
dialog.setSize(new Dimension(400, 200));
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
public void numberButtons(String i) {
if(typeNum == false) {
display.setText("");
format(i);
} else {
format(i);
}
typeNum = true;
}
public void operatorButtons(int funct) {
if(display.getText().equals("")) {
} else {
temporary[0] = Double.parseDouble(display.getText());
function[funct] = true;
clear();
}
}
public void clearFunction() {
clear();
try {
for(int i = 0; i < 5; i++) {
function[i] = false;
}
for(int i = 0; i < 2; i++) {
temporary[i] = 0;
}
} catch(NullPointerException e) {
}
//For parabola()
Vi = 0;
Vx = 0;
Vy = 0;
T_max = 0;
Y_displ = 0;
X_displ = 0;
h = 0;
k = 0;
a_parab = 0;
}
public void clear() {
display.setText("");
stor = "";
typeDot = true;
initial = true;
}
public static void main(String[] arguments) {
CalcClass c = new CalcClass();
}
}
Ok so now you've seen my mess... I sort-of know what I should do and YES I did some research but I feel it would be much easier to learn organization through example or a nice push than it would be from reading articles that tell you ultra-hypothetical or loosely-analogous examples of what objects are. Note: I tried using methods to organize and my class looks much better than what it did (I also made the whole thing an object to be called upon at the bottom which is pretty much useless).
If you use eclipse, try:
Window > Prefferences > Java > Editor > Save Actions
Check "perform the selected actions on save", "Additional Actions" and click "Configure".
Using eclipse's Save Actions can be really useful in real life coding, but you will probably learn some neat java tricks going through the Save Actions wizard.
Java is an Object Oriented language. You need to take advantage of that fact.
Use classes to separate your code into different logical / structural components. Learn how to use OOP. Follow SOLID design and use design patterns.
Another important thing is to know your language. Start by reading basic classes javadocs and relevant sections of the java spec. I would begin with deeply understanding the different types of java (class, interface, enum and inner / nested / anonymous types) and the different modifiers (private, public, protected, static, abstract, final, default).
Some other eclipse's short cuts:
CTRL-A, CTRL-I ("indentation") will fix your code indentation.
CTRL-SHIFT-O ("organize imports") will omit redundant imports.
You might consider taking a look at Code Complete, which deals with the issues that you're concerned with here, and otherwise is just a classic in our field that every serious developer should read.
In general, when you're organizing code you should do so with a few things in mind: readability and atomicity. These two factors apply to code on every level of an application, from variable naming, routines, methods, classes, packages, and so on.
Readability is a simple idea: can a human being read this code and understand it? To gauge the readability of the code all you have to do is read it! Do variable names help the reader understand what something is? Are routines and classes properly formatted and not needlessly complex? Have you removed all code that isn't being used? Is your code written in a logical progression?
Atomicity is the idea that everything should have one purpose. A function or method should (usually) do one thing and one thing only. A class should usually be a logical grouping of related methods and fields serving some type of unique purpose, and NOT a mish-mash of unrelated stuff. A package should also contain a set of related files. Same with a project, and so on.
The main benefit of atomicity is that once you get into more involved applications it's actually much easier to debug and isolate issues in your code because you know where stuff is. For instance: I have a database access error! Good thing I have a package that's specifically defined for my database access objects.
I know when I was just getting started in the field this was something that threw me off too. It might not be until you do a lot of coding within more significant apps that you really start to understand best practices and why people build stuff a certain way.
Thanks to everyone who contributed to my problem, I completely scrapped this garbage and made it 1000 times better. I knew from the beginning it was poorly made and I wanted to fix it, I just didn't know where to start. After reading all the advice that was given, watching a few tutorials and brushing up on some simple java concepts (modifiers, jswing, etc), I ended up making a new one that is in MVC format (Yay, order and efficiency). Now all my new variables are actually meaningful (Thanks #maaartinus for helping me realize that many of my variables were poorly named and made my whole program unnecessarily complicated). Also, I tried to work on SRP (Not 100% sure if I completely did it but with the program organized it will be easy to change things) and I plan on adding units later for good practice (Thank you, #Robert Snyder). This new GUI is ugly but that can always be changed later and since It is now in MVC format the job will be easier.
Here is what I did (not finished and far from perfect but a step in the right direction):
CalcGui.java
package com.Calculator;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CalcGui extends JFrame {
private static final long serialVersionUID = 1L;
private String[] operatorsList = { "+", "-", "*", "/", "^" };
// Row 1
private JTextField firstNumber = new JTextField(10);
private JComboBox<String> operator = new JComboBox<>(operatorsList);
private JTextField secondNumber = new JTextField(10);
private JButton calculateButton = new JButton("Calculate");
private JTextField calcSolution = new JTextField(20);
// Row 2
private JLabel sqrtSymbol = new JLabel("√");
private JTextField sqrtNumber = new JTextField(10);
private JButton sqrtCalcButton = new JButton("Calculate");
private JTextField sqrtCalcSolution = new JTextField(20);
// Row 3
private JLabel quadraticLabel1 = new JLabel("A = ");
private JTextField quadraticFirstNumber = new JTextField(5);
private JLabel quadraticLabel2 = new JLabel("B = ");
private JTextField quadraticSecondNumber = new JTextField(5);
private JLabel quadraticLabel3 = new JLabel("C = ");
private JTextField quadraticThirdNumber = new JTextField(5);
private JButton quadraticCalcButton = new JButton("Calculate");
private JLabel quadraticTextBefore = new JLabel("x =");
private JTextField firstQuadraticCalcSolution = new JTextField(3);
private JLabel quadraticTextMiddle = new JLabel("and x =");
private JTextField secondQuadraticCalcSolution = new JTextField(3);
CalcGui() {
JPanel calcPanel = new JPanel(new BorderLayout());
FlowLayout Default = new FlowLayout(FlowLayout.LEFT);
JPanel row1 = new JPanel(Default);
JPanel row2 = new JPanel(Default);
JPanel row3 = new JPanel(Default);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(650, 150);
row1.add(firstNumber);
row1.add(operator);
row1.add(secondNumber);
row1.add(calculateButton);
row1.add(calcSolution);
row2.add(sqrtSymbol);
row2.add(sqrtNumber);
row2.add(sqrtCalcButton);
row2.add(sqrtCalcSolution);
row3.add(quadraticLabel1);
row3.add(quadraticFirstNumber);
row3.add(quadraticLabel2);
row3.add(quadraticSecondNumber);
row3.add(quadraticLabel3);
row3.add(quadraticThirdNumber);
row3.add(quadraticCalcButton);
row3.add(quadraticTextBefore);
row3.add(firstQuadraticCalcSolution);
row3.add(quadraticTextMiddle);
row3.add(secondQuadraticCalcSolution);
calcPanel.add(row1, BorderLayout.NORTH);
calcPanel.add(row2, BorderLayout.CENTER);
calcPanel.add(row3, BorderLayout.SOUTH);
this.add(calcPanel);
}
// basic calculations methods
public double getFirstNumber() {
return Double.parseDouble(firstNumber.getText());
}
public String getOperator() {
return (String) operator.getSelectedItem();
}
public double getSecondNumber() {
return Double.parseDouble(secondNumber.getText());
}
public void setCalcSolution(double solution) {
calcSolution.setText(Double.toString(solution));
}
void addCalculateListener(ActionListener listenForCalcButton) {
calculateButton.addActionListener(listenForCalcButton);
}
void displayErrorMessage(String errorMessage) {
JOptionPane.showMessageDialog(this, errorMessage);
}
// Square root function methods
public double getSqrtNumber() {
return Double.parseDouble(sqrtNumber.getText());
}
public void setSqrtCalcSolution(double solution) {
sqrtCalcSolution.setText(Double.toString(solution));
}
void addSqrtCalcListener(ActionListener listenForSqrtCalcButton) {
sqrtCalcButton.addActionListener(listenForSqrtCalcButton);
}
// Quadratic formula Methods
public double getQuadraticFirstNumber() {
return Double.parseDouble(quadraticFirstNumber.getText());
}
public double getQuadraticSecondNumber() {
return Double.parseDouble(quadraticSecondNumber.getText());
}
public double getQuadraticThirdNumber() {
return Double.parseDouble(quadraticThirdNumber.getText());
}
public void setFirstQuadraticCalcSolution(double solution) {
firstQuadraticCalcSolution.setText(Double.toString(solution));
}
public void setSecondQuadraticCalcSolution(double solution) {
secondQuadraticCalcSolution.setText(Double.toString(solution));
}
void addQuadraticCalcListener(ActionListener listenForQuadraticCalcButton) {
quadraticCalcButton.addActionListener(listenForQuadraticCalcButton);
}
}
CalcModel.java
package com.Calculator;
public class CalcModel {
private double calcValue;
public void calculate(double firstNumber, double secondNumber,
String operator) {
if (operator.equals("+")) {
calcValue = firstNumber + secondNumber;
}
if (operator.equals("-")) {
calcValue = firstNumber - secondNumber;
}
if (operator.equals("*")) {
calcValue = firstNumber * secondNumber;
}
if (operator.equals("/")) {
calcValue = firstNumber / secondNumber;
}
if (operator.equals("^")) {
calcValue = Math.pow(firstNumber, secondNumber);
}
}
public double getCalcValue() {
return calcValue;
}
}
SqrtCalcModel.java
package com.Calculator;
public class SqrtCalcModel {
private double sqrtCalcValue;
public void sqrt(double number) {
sqrtCalcValue = Math.sqrt(number);
}
public double getSqrtCalcValue() {
return sqrtCalcValue;
}
}
QuadraticCalcModel.java
package com.Calculator;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class QuadraticCalcModel {
private double firstQuadraticCalcValue;
private double secondQuadraticCalcValue;
public void quadraticFormula(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);
if (discriminant >= 0) {
firstQuadraticCalcValue = (Math.sqrt((b * b) - (4 * a * c)) + (-b))
/ (2 * a);
secondQuadraticCalcValue = (Math.sqrt((b * b) - (4 * a * c)) - (-b))
/ (2 * a);
}
else {
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent,
"This function has no real roots.");
}
}
public double getFirstQuadraticValue() {
return firstQuadraticCalcValue;
}
public double getSecondQuadraticValue() {
return secondQuadraticCalcValue;
}
}
CalculatorControler.java
package com.Calculator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorController {
private CalcGui theGui;
private CalcModel theCalcModel;
private SqrtCalcModel theSqrtCalcModel;
private QuadraticCalcModel theQuadraticCalcModel;
public CalculatorController(CalcGui theGui, CalcModel theCalcModel,
SqrtCalcModel theSqrtCalcModel,
QuadraticCalcModel theQuadraticCalcModel) {
this.theGui = theGui;
this.theCalcModel = theCalcModel;
this.theSqrtCalcModel = theSqrtCalcModel;
this.theQuadraticCalcModel = theQuadraticCalcModel;
this.theGui.addCalculateListener(new CalcListener());
this.theGui.addSqrtCalcListener(new SqrtCalcListener());
this.theGui.addQuadraticCalcListener(new QuadraticCalcListener());
}
class CalcListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double firstNumber, secondNumber = 0;
String operator;
try {
firstNumber = theGui.getFirstNumber();
operator = theGui.getOperator();
secondNumber = theGui.getSecondNumber();
theCalcModel.calculate(firstNumber, secondNumber, operator);
theGui.setCalcSolution(theCalcModel.getCalcValue());
}
catch (NumberFormatException ex) {
System.out.println(ex);
theGui.displayErrorMessage("You Need to Enter 2 Numbers");
}
}
}
class SqrtCalcListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double number = 0;
try {
number = theGui.getSqrtNumber();
theSqrtCalcModel.sqrt(number);
theGui.setSqrtCalcSolution(theSqrtCalcModel.getSqrtCalcValue());
}
catch (NumberFormatException ex) {
System.out.println(ex);
theGui.displayErrorMessage("You Need to enter a Number");
}
}
}
class QuadraticCalcListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double a, b, c = 0;
try {
a = theGui.getQuadraticFirstNumber();
b = theGui.getQuadraticSecondNumber();
c = theGui.getQuadraticThirdNumber();
theQuadraticCalcModel.quadraticFormula(a, b, c);
theGui.setFirstQuadraticCalcSolution(theQuadraticCalcModel
.getFirstQuadraticValue());
theGui.setSecondQuadraticCalcSolution(theQuadraticCalcModel
.getSecondQuadraticValue());
}
catch (NumberFormatException ex) {
System.out.println(ex);
theGui.displayErrorMessage("You need to enter 3 numbers.");
}
}
}
}
MVCCalculator.java
package com.Calculator;
public class MVCCalculator {
public static void main(String[] args) {
CalcGui theGui = new CalcGui();
CalcModel theCalcModel = new CalcModel();
SqrtCalcModel theSqrtCalcModel = new SqrtCalcModel();
QuadraticCalcModel theQuadraticCalcModel = new QuadraticCalcModel();
new CalculatorController(theGui, theCalcModel, theSqrtCalcModel,
theQuadraticCalcModel);
theGui.setVisible(true);
}
}
For a school project, I created the following program:
BlckJckUI.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class BlckJckUI {
public static void main(String args[])
{
JFrame GUI = new JFrame("Blackjack Advisor");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(800,800);
GUI.setVisible(true);
ImageIcon Ace = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\Ace.jpg");
JButton ace = new JButton(Ace);
ace.setSize(300, 100);
ace.setLocation(100, 100);
ace.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
if (array.playerhandtotal <= 21)
{
math.cardvalue = 11;
}
else
{
math.cardvalue = 1;
}
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(ace);
ImageIcon Two = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\2.jpg");
JButton two = new JButton(Two);
two.setSize(300, 100);
two.setLocation(100, 200);
two.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 2;
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(two);
ImageIcon Three = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\3.jpg");
JButton three = new JButton(Three);
three.setSize(300, 100);
three.setLocation(100, 300);
three.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 3;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(three);
ImageIcon Four = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\4.jpg");
JButton four = new JButton(Four);
four.setSize(300, 100);
four.setLocation(100, 400);
four.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 4;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(four);
ImageIcon Five = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\5.jpg");
JButton five = new JButton(Five);
five.setSize(300, 100);
five.setLocation(100, 500);
five.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 5;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(five);
ImageIcon Six = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\6.jpg");
JButton six = new JButton(Six);
six.setSize(300, 100);
six.setLocation(900, 100);
six.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 6;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(six);
ImageIcon Seven = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\7.jpg");
JButton seven = new JButton(Seven);
seven.setSize(300, 100);
seven.setLocation(900, 200);
seven.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 7;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(seven);
ImageIcon Eight = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\8.jpg");
JButton eight = new JButton(Eight);
eight.setSize(300, 100);
eight.setLocation(900, 300);
eight.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 8;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(eight);
ImageIcon Nine = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\9.jpg");
JButton nine = new JButton(Nine);
nine.setSize(300, 100);
nine.setLocation(900, 400 );
nine.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 9;
array.clicktracker++;
;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(nine);
ImageIcon Ten = new ImageIcon("C:\\Users\\Hieu Vo\\workspace\\Deck-2014-01-03\\Deck\\ten.jpg");
JButton ten = new JButton(Ten);
ten.setSize(300, 100);
ten.setLocation(900, 500);
ten.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Arrays array = new Arrays();
Math math = new Math();
math.cardvalue = 10;
array.clicktracker++;
JOptionPane.showMessageDialog(null,array.result);
}
});
GUI.add(ten);
JButton start = new JButton("Start/Reset");
start.setSize(300, 100);
start.setLocation(500,500);
start.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
;
Arrays array = new Arrays();
array.playerhand.clear();
array.dealer = 0;
array.clicktracker = 0;
array.playerhandtotal = 0;
array.result = null;
JOptionPane.showMessageDialog(null,"Please select the card \nthat the dealer is showing :)");
}
});
GUI.add(start);
GUI.setLayout(null);
GUI.pack();
//start.setSize(somethinghere);
//start.setLocation(Somethinghere);
}
}
Math.java
public class Math
{
public int cardvalue;
public Math()
{
Arrays array = new Arrays();
if (array.clicktracker == 1)
{
array.dealer = cardvalue;
array.result = "Please select the first card you have :)";
}
else if (array.clicktracker == 2)
{
array.playerhand.add(cardvalue);
array.result = "Please select the second card you have :)";
}
else if (array.clicktracker >= 3)
{
array.playerhand.add(cardvalue);
if (array.playerhandtotal <= 8)
{
// array.result = result statement
array.result = "You should just hit until you're safe. If the dealer 6 or below,\n"
+ " the chances are that he'll bust and if not, remain low above 17.\n"
+ " As long as you can pull a 17 or higher, you should be safe. Pick \n"
+ "another card or reset.";
}
else if (array.playerhandtotal == 9)
{
if (3 <= array.dealer && array.dealer <= 6)
{
array.result = "Double down. The chances of him busting is high,\n"
+ "chances of him not having a high total is high as well. \n"
+ "Chances you'll get a 10 is high as well. Pick another card or reset.";
}
else
{
array.result = "Your best option is to Hit, and it's a luck thing from there. The dealer has some room with a 2; it's highly likely for him to get right below 21 and well above 16, and given that you'll have to beat him in the end, you have to hit until you're high. With 7 plus, he's set: He gets a 10 and he can stop, and again in the end, you'll have to beat his score. May the Goddess of Luck favor you, because you'll need it. Pick another card or reset.";
}
}
else if (array.playerhandtotal == 10)
{
if (2 <= array.dealer && array.dealer <= 9)
{
array.result = "Double down, since Assumption Rule wins out in your favor, if you have a 10, you're golden. The dealer has very little chance of beating you: chances are that he busts or loses to your almighty 20. Even if you bust, the chance that he busts is sufficiently high as well. Very unlikely for him to get 21. Pick another card or reset.";
}
else
{
array.result = "Hit. Dealer is in green zone, Assumption Rule states that he'll get a 20 or 21. Gotta beat him, no way around it. Hope for the best. A double will never cut it, since you're gambling on 1 card to get 20-21. Better safe than sorry. Pick another card or reset.";
}
}
else if (array.playerhandtotal == 11)
{
if (2 <= array.dealer && array.dealer <= 10)
{
array.result = "Double down, since Assumption Rule wins out in your favor, if you have a 10, you're golden. The dealer has very little chance of beating you: chances are that he busts ors loses to your almighty 21. Even if you bust, the chance that he busts is sufficiently high as well. Pick another card or reset.";
}
else
{
array.result = "Hit. He's going to have a 10 due to Assumption Rule. You may as well, but remember, you're less likely to. Thus, hit to be safe. You have to beat to win, and if you Double Down, you lock yourself into a position where the chances of you beating the dealer is slim. (At least, slimmer than hitting.) Pick another card or reset.";
}
}
else if (array.playerhandtotal == 12)
{
if ((array.dealer == 2 || array.dealer == 3) || (array.dealer >= 7))
{
array.result = "Hit. You're likely to lose anyways, per the Assumption Rule. However, there's always a chance that you won't. Doubling makes no sense, and it will reduce your chance of winning. The dealer has some room with a 2; it's highly likely for him to get right below 21 and well above 16, and given that you'll have to beat him in the end, you have to hit until you're high. With 7 plus, he's set: He gets a 10 and he can stop, and again in the end, you'll have to beat his score. Pick another card or reset.";
}
else
{
array.result = "Stand. You have a high chance of bust, but the dealer does as well. If you stay, chances are, dealer will bust. Pick another card or reset.";
}
}
else if (13 <= array.playerhandtotal && array.playerhandtotal <= 16)
{
if (array.dealer >= 7)
{
array.result = "Hit. Might as well. Chances are against you severely, but you still have to play on chance. Hitting is the safest option. Pick another card or reset.";
}
else
{
array.result = "Stand. Dealer may bust; ride on that chance. Pick another card or reset.";
}
}
else if (17 <= array.playerhandtotal && array.playerhandtotal <= 21)
{
array.result = "Stand. You're golden. Just hope for the best and let Lady Luck work her magic. Rest please.";
}
else if (array.playerhandtotal >= 22)
{
array.result = " Oi. You've busted. Reset please.";
}
}
}
}
Arrays.java
import java.util.*;
public class Arrays
{
public String result;
ArrayList<Integer> playerhand = new ArrayList<Integer>();
public int dealer = 0;
public int clicktracker = 0;
public int playerhandtotal = 0;
{
for (int element: playerhand)
{
playerhandtotal = element + playerhandtotal;
}
}
}
The program is supposed to be a Black Jack Advisory tool, and when you click "start/reset" it should ask you to click 1 card (which is the card that the dealer shows.) When you click a card , it then asks you to click the first card you have. When you click that, it then asks for your second card, etc. etc.
When you click start, it works fine, however, when you click ANY of the number cards, the JOptionPanel doesn't say anything.
I'm pretty sure this is because the value of the string its supposed to put out is "null," which I don't want it to be.
How do I make it so that it takes the value of array.result in the if-else statements?
Check your Arrays class. Your missing a method definition around your for statement. And my best guess is to give your result variable a default empty value ->
public String result = "";
Trying to get the final part of this game to work. Its a hangman game, I just need it to display correct guesses where they are in the word.
This is the snippet of code of when a correct guess is given
else
{
int alreadyGuessed = guesses.indexOf(guess);
if (alreadyGuessed == -1)
{
guesses = guesses + guess + "";
jlbWord.setText("Word: " + charWord[currentGuess]);
}
else{}
}
Right now it simply shows each letter. I can also set it, so it shows each one as they are typed in but its not in the right order, which makes it much more difficult for the user to guess what the word is.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.Dimension;
public class RightPanel extends JPanel implements KeyListener
{
JLabel jlbMissed, jlbWord, jlbTimer;
Color btnColor;
JComboBox jcbDifficulty;
JButton jbtStart, jbtQuit;
String[] difficulties = {"Easy", "Medium", "Hard"};
String[] words = {"First", "Next", "Hello", "World"};
char guess;
String word, guesses = "";
char[] charWord;
public static int incorrectGuesses = 0;
boolean clockIsRunning = false;
boolean gameInPlay = false;
int sec = 0;
int min = 0;
public RightPanel()
{
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
Random ran = new Random(); //
int rand = ran.nextInt(4); // Generates random number then selects word from words array
word = words[rand]; //
charWord = word.toCharArray();
ActionHandler actionHandler = new ActionHandler();
jlbMissed = new JLabel("Missed: ");
jlbWord = new JLabel("Word: ");
jlbTimer = new JLabel("Time: " + "0:00");
jbtStart = new JButton("Start");
jbtQuit = new JButton("Quit");
jcbDifficulty = new JComboBox();
jbtStart.addActionListener(actionHandler);
jbtQuit.addActionListener(actionHandler);
jcbDifficulty.addKeyListener(this);
jbtStart.addKeyListener(this);
for (int i = 0; i < 3; i++)
{
jcbDifficulty.addItem(difficulties[i]); // Creates Difficutly ComboBox
}
this.add(jcbDifficulty, getConstraints(0,0,1,1, GridBagConstraints.WEST));
this.add(jlbMissed, getConstraints(0,1,1,1, GridBagConstraints.WEST));
this.add(jlbWord, getConstraints(0,2,1,1, GridBagConstraints.WEST));
this.add(jlbTimer, getConstraints(0,4,1,1, GridBagConstraints.WEST));
this.add(jbtStart, getConstraints(0,6,1,1, GridBagConstraints.WEST));
this.add(jbtQuit, getConstraints(0,7,1,1, GridBagConstraints.WEST));
}
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e)
{
guess = e.getKeyChar();
if (gameInPlay == false)
{
JOptionPane.showMessageDialog(this, "You have not started the game yet!", "Game has not Started", JOptionPane.ERROR_MESSAGE);
System.out.println("Game Not in Play");
}
else
{
if (Character.isLetter(guess))
{
if (incorrectGuesses > 11)
{
clockIsRunning = false;
gameInPlay = false;
JOptionPane.showMessageDialog(this, "You Killed Him! \nThe word was " + word, "He Ceases to Exist", JOptionPane.ERROR_MESSAGE);
jbtStart.setText("Retry?");
jbtStart.setBackground(Color.RED);
}
else
{
int currentGuess = word.indexOf(guess);
if (currentGuess == -1)
{
int alreadyGuessed = guesses.indexOf(guess);
if (alreadyGuessed == -1)
{
guesses = guesses + guess + "";
System.out.println(alreadyGuessed);
System.out.println(guesses);
String temp = jlbMissed.getText();
jlbMissed.setText(temp + guess + ", ");
incorrectGuesses++;
leftPanel.hangmanPic.setIcon(leftPanel.image[RightPanel.incorrectGuesses]);
}
else {}
}
else
{
int alreadyGuessed = guesses.indexOf(guess);
if (alreadyGuessed == -1)
{
guesses = guesses + guess + "";
jlbWord.setText("Word: " + charWord[currentGuess]);
}
else{}
}
}
}
else
JOptionPane.showMessageDialog(this, "That is not a valid guess!\n Please enter a character from A-Z", "Invalid Guess", JOptionPane.ERROR_MESSAGE);
}
}
private GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth, int gridheight, int anchor)
{
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5,5,5,5);
c.ipadx = 0;
c.ipady = 0;
c.gridx = gridx;
c.gridy = gridy;
c.gridwidth = gridwidth;
c.gridheight = gridheight;
c.anchor = anchor;
return c;
}
class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == jbtStart)
{
if (clockIsRunning == true){}
else
{
if (jbtStart.getText() == "Start")
{
btnColor = jbtStart.getBackground();
clockIsRunning = true;
MyTimer timer = new MyTimer();
timer.start();
gameInPlay = true;
}
else if (jbtStart.getText() == "Retry?")
{
jbtStart.setText("Start");
jbtStart.setBackground(btnColor);
jlbTimer.setText("Time: " + "0:00");
sec = 0;
min = 0;
MyTimer timer = new MyTimer();
timer.start();
clockIsRunning = true;
gameInPlay = true;
incorrectGuesses = 0;
guesses = "";
jlbMissed.setText("Missed: ");
jlbWord.setText("Word: ");
leftPanel.hangmanPic.setIcon(leftPanel.image[RightPanel.incorrectGuesses]);
Random ran = new Random();
int rand = ran.nextInt(4);
word = words[rand];
}
}
}
else if (source == jbtQuit)
{
System.exit(0);
}
}
}
class MyTimer extends Thread
{
public void run()
{
while(true)
{
if(!clockIsRunning)
break;
try
{
Thread.sleep(1000);
}
catch (InterruptedException ecp)
{
}
if (sec == 59)
{
min++;
sec = 0;
}
else
sec++;
if(sec < 10)
jlbTimer.setText("Time:" + min+":0"+sec);
else
jlbTimer.setText("Time:" + min+":"+sec);
}
}
}
}
Yikes.
You should refactor your code and keep the guesses in a TreeSet<Character> data structure. It assures, that each character is stored only once and that an iterator returns all stored chars in ascending order.
Snippet:
Set<Character> guesses = new HashSet<Character>();
// add a guess
guesses.add('e');
guesses.add('r');
guesses.add('a');
guesses.add('e'); // will not be added, already in the set
// test
if (guesses.contains('e')) { ... }
// test if a word is "guessed"
boolean foundIt = true;
for (char c:word.toCharArray()) {
if (!guesses.contains(c)) {
foundIt = false;
break;
}
}
// foundIt is true if all chars of word have been guessed
// print
for (char c:guesses)
System.out.print(c); // prints: aer