Can't Get Program To Recognize Card Values - java

My program won't go inside of this block of code
if(card1.CardValue() == (int)expInput.get(0)
&& card2.CardValue() == (int)expInput.get(1)
&& card3.CardValue() == (int)expInput.get(2)
&& card4.CardValue() == (int)expInput.get(3))
{
if(express == 24){
display.setText("Correct");
}
else
display.setText("Incorrect");
}
I think it is because I am trying to get the card value of card1 when the cards that are appearing are just random cards out of my deck. What could I use to evaluate the new cards that appear? Here is my full code:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.image.ImageView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicReference;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
ArrayList<Integer> deck;
deck = new ArrayList<>();
int i = 1;
while(i < 52){
deck.add(i);
i++;
}
final AtomicReference<String> result = new AtomicReference<>("go.");
Collections.shuffle(deck);
BorderPane pane = new BorderPane();
HBox top = new HBox(10);
Label display = new Label(result.toString());
Button btShuffle = new Button("Shuffle");
top.getChildren().add(display);
top.getChildren().add(btShuffle);
HBox center = new HBox(10);
Card card1 = new Card(deck.get(0));
center.getChildren().add(card1);
Card card2 = new Card(deck.get(1));
center.getChildren().add(card2);
Card card3 = new Card(deck.get(3));
center.getChildren().add(card3);
Card card4 = new Card(deck.get(4));
center.getChildren().add(card4);
btShuffle.setOnAction(
e -> {
Collections.shuffle(deck);
center.getChildren().clear();
center.getChildren().add(new Card(deck.get(0)));
center.getChildren().add(new Card(deck.get(1)));
center.getChildren().add(new Card(deck.get(2)));
center.getChildren().add(new Card(deck.get(3)));
});
HBox bottom = new HBox(10);
Label expression = new Label("Please Enter the expression: ");
TextField tfExpress = new TextField();
ArrayList<Character> signs = new ArrayList<>();
signs.add('/');
signs.add('+');
signs.add('(');
signs.add(')');
signs.add('-');
signs.add('^');
signs.add('*');
signs.add('%');
String str = tfExpress.getText();
int express = (str != null && !"".equals(str)) ? Integer.parseInt(str) : -1;
// expInput.removeIf(p-> p.equals(signs));
Button btVerify = new Button("Verify");
bottom.getChildren().add(expression);
bottom.getChildren().add(tfExpress);
bottom.getChildren().add(btVerify);
btVerify.setOnAction(
(ActionEvent e) ->
{
LinkedList<Character> expInput = new LinkedList<Character>();
for(char c: tfExpress.getText().toCharArray()){
expInput.add(c);
}
expInput.removeIf(p-> p.equals(signs));
if(card1.CardValue() == (int)expInput.get(0)
&& card2.CardValue() == (int)expInput.get(1)
&& card3.CardValue() == (int)expInput.get(2)
&& card4.CardValue() == (int)expInput.get(3))
{
if(express == 24){
display.setText("Correct");
}
else
display.setText("Incorrect");
}
else
display.setText("The numbers in the expression don't "
+ "match the numbers in the set.");
});
pane.setTop(top);
pane.setCenter(center);
pane.setBottom(bottom);
Scene scene = new Scene(pane);
primaryStage.setTitle("24 card game");
primaryStage.setScene(scene);
primaryStage.show();
}
public class Card extends Pane {
public int cardVal;
Card(int card){
Image cardImage;
cardImage = new Image("card/"+ card +".png");
getChildren().add(new ImageView(cardImage));
cardVal = card;
}
public int CardValue(){
int card = 0;
if(cardVal <= 13){
card = cardVal;
}
else if(cardVal > 13 && cardVal <= 26){
card = cardVal - 13;
}
else if(cardVal > 26 && cardVal <= 39){
card = cardVal - 26;
}
else if(cardVal > 39 && cardVal <= 52){
card = cardVal - 39;
}
return card;
}
}
public static void main(String[] args) {
launch(args);
}
}

You are comparing the character value of a number with an integer value. Those don't match. To make this visually clear:
String numbers = "0123456789";
for(char c: numbers.toCharArray()){
System.out.println( c);
}
produces
0 1 2 3 4 5 6 7 8 9
But if you cast the character value to an integer like you do in your program, you'll get this
48 49 50 51 52 53 54 55 56 57
Which are the ascii values of your characters.
In other words: For the character "1" and card value 1 you are comparing if 1 == 49.
Solution: You need to parse the characters instead of casting them to int, e. g. using
Character.getNumericValue(...)
As a general note: The easiest way to find out what's wrong with your code is to use a debugger. Alternatively a simple logging output would show you what's wrong.
Edit: fyi, you have a bug:
int i = 1;
while(i < 52){
deck.add(i);
i++;
}
will result in the last card being lost.

Related

How can I make a simple "AI" for the Matching Card Game (Memory)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I took some code from a guy around here in Java for the matching card game. The point is that i have an assignment of making it player against the bot.
Basically in the first turn the player picks 2 cards, if they are the same cards he continues otherwise the bots picks two cards.
The problem is that:
I dont know how to make a really simple AI so that the bot doesnt just pick 2 random cards.
I dont know why but the bot picks only one card. He doesnt pick 2, he picks one.
I'll leave the code here, please help me if you can.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Random;
import static javax.swing.UIManager.get;
public class Board extends JFrame{
public int pairs;
private List<Card> cards;
private Card selectedCard;
private Card c1;
private Card c2;
private Timer t;
boolean pc;
public Board(int num){
pairs = num;
List<Card> cardsList = new ArrayList<Card>();
List<Integer> cardVals = new ArrayList<Integer>();
for (int i = 0; i < pairs; i++){
cardVals.add(i);
cardVals.add(i);
}
Collections.shuffle(cardVals);
for (int val : cardVals){
Card c = new Card();
c.setId(val);
c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
selectedCard = c;
doTurn();
}
});
cardsList.add(c);
}
this.cards = cardsList;
//impostazioni timer per rigirare le carte
t = new Timer(750, new ActionListener(){
public void actionPerformed(ActionEvent ae){
pc=checkCards();
if(pc)
pcTurn(cardsList,cardVals);
}
});
t.setRepeats(false);
//impostazioni tavola
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 5));
for (Card c : cards){
pane.add(c);
}
setTitle("Memory");
}
public void doTurn(){ //per girare la carta
if (c1 == null && c2 == null){
c1 = selectedCard;
c1.setText(String.valueOf(c1.getId()));
}
if (c1 != null && c1 != selectedCard && c2 == null){
c2 = selectedCard;
c2.setText(String.valueOf(c2.getId()));
t.start();
}
}
public boolean checkCards(){ //per controllare le carte
boolean flag;
if (c1.getId() == c2.getId()){//match condition
c1.setEnabled(false); //disabilita la possibilita di cliccare altre carte mentre due sono girate
c2.setEnabled(false);
c1.setMatched(true); //setta il flag positivo se le carte sono uguali
c2.setMatched(true);
flag=false;
if (this.isGameWon()){
JOptionPane.showMessageDialog(this, "Hai vinto!");
System.exit(0);
}
}
else{
c1.setText(""); //nasconde il testo
c2.setText("");
flag=true;
}
c1 = null;
c2 = null;
return flag;
}
public boolean isGameWon(){ //controllo se la partita รจ vinta
for(Card c: this.cards){
if (c.getMatched() == false){
return false;
}
}
return true;
}
public void pcTurn(List<Card> cardsList, List<Integer> cardVals ){
Random random = new Random();
int x = random.nextInt(cardsList.size());
int y = random.nextInt(cardsList.size());
if (c1 == null && c2 == null){
c1 = cardsList.get(x);
c1.setText(String.valueOf(c1.getId()));
}
if (c1 != null && c1 != cardsList.get(x) && c2 == null){
c2 = cardsList.get(y);
c2.setText(String.valueOf(c2.getId()));
t.start();
}
}
}
You could save every card the bot took in an array with the position of the card. The PC should not choose the same card twice. If he picks up the second card of the pair he should get the position of the first card and pick them both

JavaFX NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Can someone explain why I'm getting this error and how to solve it? Also try to keep it simple. I'm new to coding. (Also i know the answer to the question exists, but i don't know how to implement it to my code)
It gives NullPointerException error when rows are deleted. Also when the blocks move down, the blocks are still counted as 0 so new blocks go through them. (i guess its only the top row, other rows are working as intended) But the actual error is more important: (but i'd be happy if you help to solve this too)
package application;
import java.util.*;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.input.*;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Tetris extends Application {
public static final int MOVE_AMOUNT = 25;
public static final int SIZE = 25;
public static int XLIMIT = SIZE * 10;
public static int YLIMIT = SIZE * 24;
public static int[][] GRID = new int[XLIMIT/SIZE][YLIMIT/SIZE];
private static Pane group = new Pane();
private static Shape object;
private static Scene scene = new Scene(group, XLIMIT, YLIMIT);
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) throws Exception {
for(int[] a: GRID){
Arrays.fill(a, 0);
}
for(int i = 0; i <= XLIMIT; i+= SIZE){
Line a = new Line(i, 0, i, YLIMIT);
group.getChildren().add(a);
}
for(int i = 0; i <= YLIMIT; i+= SIZE){
Line a = new Line(0, i, XLIMIT, i);
group.getChildren().add(a);
}
for(int i = 0; i <= YLIMIT; i+= SIZE){
Text a = new Text("" + i);
a.setY(i);
group.getChildren().add(a);
}
for(int i = SIZE; i < XLIMIT; i+= SIZE){
Text a = new Text("" + i);
a.setY(10);
a.setX(i);
group.getChildren().add(a);
}
Shape a = TetrisHolder.createRect();
group.getChildren().addAll(a.a, a.b, a.c, a.d);
moveOnKeyPress(scene, a.a, a.b, a.c, a.d);
object = a;
stage.setScene(scene);
stage.show();
Timer myTimer=new Timer();
TimerTask task =new TimerTask() {
#Override
public void run() {
Platform.runLater(new Runnable(){
public void run(){
CheckDown(object);
}
});
}
};
myTimer.schedule(task,0,300);
}
private void moveOnKeyPress(Scene scene, Rectangle rect, Rectangle rect2, Rectangle rect3, Rectangle rect4) {
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override public void handle(KeyEvent event) {
Shape shape = new Shape(rect, rect2, rect3, rect4);
switch (event.getCode()) {
case RIGHT:
TetrisHolder.CheckRight(shape);
break;
case DOWN:
CheckDown(shape);
break;
case LEFT:
TetrisHolder.CheckLeft(shape);
break;
case UP:
//TetrisHolder.CheckTurn(shape);
break;
}
}
});
}
private void CheckTurn(Shape shape){
}
private void DeleteRows(Pane pane){
ArrayList<Node> rects = new ArrayList<Node>();
ArrayList<Integer> lines = new ArrayList<Integer>();
int full = 0;
for(int i = 0; i < GRID[0].length; i++){
for(int j = 0; j < GRID.length; j++){
if(GRID[j][i] == 1)
full++;
}
if(full == GRID.length)
lines.add(i/*+lines.size()*/);
full = 0;
}
for(Node node: pane.getChildren()) {
if(node instanceof Rectangle) {
rects.add(node);
}
}
if(lines.size() > 0)
do{
for(Node node: rects){
Rectangle a = (Rectangle)node;
if(a.getY() == lines.get(0)*SIZE){
GRID[(int)a.getX()/SIZE][(int)a.getY()/SIZE] = 0;
pane.getChildren().remove(node);
}
if(a.getY() < lines.get(0)*SIZE){
GRID[(int)a.getX()/SIZE][(int)a.getY()/SIZE] = 0;
a.setY(a.getY() + SIZE);
GRID[(int)a.getX()/SIZE][(int)a.getY()/SIZE] = 1;
}
}
lines.remove(0);
rects.clear();
for(Node node: pane.getChildren()) {
if(node instanceof Rectangle) {
rects.add(node);
}
}
} while(lines.size() > 0);
}
private void CheckDown(Shape shape){
if((shape.c.getY() == YLIMIT - SIZE) || checkA(shape) || checkB(shape) || checkC(shape) || checkD(shape)){
GRID[(int)shape.a.getX()/SIZE][(int)shape.a.getY()/SIZE] = 1;
GRID[(int)shape.b.getX()/SIZE][(int)shape.b.getY()/SIZE] = 1;
GRID[(int)shape.c.getX()/SIZE][(int)shape.c.getY()/SIZE] = 1;
GRID[(int)shape.d.getX()/SIZE][(int)shape.d.getY()/SIZE] = 1;
DeleteRows(group);
Shape a = TetrisHolder.createRect();
object = a;
group.getChildren().addAll(a.a, a.b, a.c, a.d);
moveOnKeyPress(shape.a.getScene(), a.a, a.b, a.c, a.d);
}
if(shape.c.getY() + MOVE_AMOUNT < YLIMIT){
int checka = GRID[(int)shape.a.getX()/SIZE][((int)shape.a.getY()/SIZE) + 1];
int checkb = GRID[(int)shape.b.getX()/SIZE][((int)shape.b.getY()/SIZE) + 1];
int checkc = GRID[(int)shape.c.getX()/SIZE][((int)shape.c.getY()/SIZE) + 1];
int checkd = GRID[(int)shape.d.getX()/SIZE][((int)shape.d.getY()/SIZE) + 1];
if(checka == 0 && checka == checkb && checkb == checkc && checkc == checkd){
shape.a.setY(shape.a.getY() + MOVE_AMOUNT);
shape.b.setY(shape.b.getY() + MOVE_AMOUNT);
shape.c.setY(shape.c.getY() + MOVE_AMOUNT);
shape.d.setY(shape.d.getY() + MOVE_AMOUNT);
}
}
}
private boolean checkA(Shape shape){
return (GRID[(int)shape.a.getX()/SIZE][((int)shape.a.getY()/SIZE) + 1] == 1);
}
private boolean checkB(Shape shape){
return (GRID[(int)shape.b.getX()/SIZE][((int)shape.b.getY()/SIZE) + 1] == 1);
}
private boolean checkC(Shape shape){
return (GRID[(int)shape.c.getX()/SIZE][((int)shape.c.getY()/SIZE) + 1] == 1);
}
private boolean checkD(Shape shape){
return (GRID[(int)shape.d.getX()/SIZE][((int)shape.d.getY()/SIZE) + 1] == 1);
}
}
The error:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at application.Tetris.moveOnKeyPress(Tetris.java:70)
at application.Tetris.CheckDown(Tetris.java:147)
at application.Tetris.access$1(Tetris.java:137)
at application.Tetris$1$1.run(Tetris.java:60)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Why are you getting the scene from a shape if you still have a reference to a static scene at the top?
I'd say try switching the following out at line 70:
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
to this:
this.scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
You are trying to access a shape which is null.
In your case, if you look at line 70, you are trying to perform scene.setOnKeyPressed, but scene is null.
You are calling in 2 places the moveOnKeyPress method.
Where your problem is calling this method at line 147, where you do shape.a.getScene(). That call to getScene() is null.
Furthermore, if you look where you call CheckDown, you have them in 2 places, but your problematic call is at line 60.
Not sure what you do at line 48 (Shape a = TetrisHolder.createRect();), but I suspect there might be something wrong with setting up the scene
What I did here is translate your stacktrace:
at application.Tetris.moveOnKeyPress(Tetris.java:70)
at application.Tetris.CheckDown(Tetris.java:147)
at application.Tetris.access$1(Tetris.java:137)
at application.Tetris$1$1.run(Tetris.java:60)

Main method in different class can't detect button press

I'm making a program for practice and it's basically simulating winning/losing Powerball tickets. Anyways, the main class is in launchPowerBall.java and the button that I am trying to detect when clicked is in PowerBallGUI.java. The button works by itself, however, the main in launchPowerBall.java isn't able to detect it even though I set up myself a few setters and getters. Any clue what alternative I can do instead? Because it seems as though even though I run it through a while(true) loop and I keep pressing the button, there seems to be no detection from the main method.
Here's the action listener for the JButton:
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
Here's what I'm trying to do for the main method:
public static void main(String[] args) throws InterruptedException {
// Build the GUI object
PowerBallGUI GUI = new PowerBallGUI();
GUI.buildGUI();
//GUI.setTextArea("banana");
// Build the PowerBall object
PowerBall roll = new PowerBall();
while(true) {
if (GUI.getJButton().getModel().isPressed()) {
System.out.println("TEST");
}
}
}
Here's the three files if you need to see my code:
1) https://gist.github.com/anonymous/e5950413470202cd1ac6d24e238ff693
2) https://gist.github.com/anonymous/773e4e4454a79c057da78eed038fade1
3) https://gist.github.com/anonymous/82335e634c1f84607d3021b4d683cc65
Powerball...
public class PowerBall {
private int[] numbers = {0, 0, 0, 0, 0};
private int[] lotteryNumbers = {0, 0, 0, 0, 0};
private int powerBall;
private int lotteryPowerBall;
private double balance;
private double winnings;
/*** Constructor Methods ***/
public PowerBall() {
powerBall = 0;
balance = 1000;
winnings = 0;
}
/*** Mutator Methods ***/
public void randomize() {
int i;
int highestNumber = 59;
int highestPowerball = 32;
int temp = 0;
for (i = 0; i < numbers.length; i++) {
// Choose a random number
temp = (int)(Math.random() * highestNumber);
numbers[i] = temp;
}
// Choose a random Powerball number
powerBall = (int)(Math.random() * highestPowerball);
// Choose the lottery numbers
for (i = 0; i < lotteryNumbers.length; i++) {
temp = (int)(Math.random() * highestNumber);
lotteryNumbers[i] = temp;
}
lotteryPowerBall = (int)(Math.random() * highestPowerball);
}
public void calculate() {
int matches = 0;
int powerballMatches = 0;
if (balance > 0) {
// Check to see if there are any matches between the two sets of numbers
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < lotteryNumbers.length; j++) {
if (numbers[i] == lotteryNumbers[j]) {
matches++;
}
}
}
// Check to see if the two different powerball numbers match
if (powerBall == lotteryPowerBall) {
powerballMatches = 1;
}
// Calculate the balance/winnings if there were any matches
if (matches == 0 && powerballMatches == 0) {
balance = balance - 2;
winnings = winnings - 2;
} else if (matches == 0 && powerballMatches == 1) {
balance = balance + 4;
winnings = winnings + 4;
} else if (matches == 0 && powerballMatches == 0 || matches == 1 && powerballMatches == 0) {
balance = balance - 2;
winnings = winnings - 2;
} else if (matches == 2 && powerballMatches == 1) {
balance = balance + 7;
winnings = winnings + 7;
} else if (matches == 3 && powerballMatches == 0) {
balance = balance + 7;
winnings = winnings + 7;
} else if (matches == 3 && powerballMatches == 1) {
balance = balance + 100;
winnings = winnings + 100;
} else if (matches == 4 && powerballMatches == 0) {
balance = balance + 100;
winnings = winnings + 100;
} else if (matches == 4 && powerballMatches == 1) {
balance = balance + 50000;
winnings = winnings + 50000;
} else if (matches == 5 && powerballMatches == 0) {
balance = balance + 1000000;
winnings = winnings + 1000000;
} else if (matches == 5 && powerballMatches == 1) {
balance = balance + 10000000;
winnings = winnings + 10000000;
}
//System.out.println("There is currently " + matches + " number matches.");
//System.out.println("There is currently " + powerballMatches + " powerball number matches.\n");
} else {
System.out.println("YOU ARE BROKE!");
}
}
/*** Accessor/Observor Methods ***/
public void displayBalance() {
System.out.print("Your balance is at: $");
System.out.printf("%.2f", balance);
}
public void displayWinnings() {
System.out.print("\nYou have currently won: $");
System.out.printf("%.2f", winnings);
System.out.println("\n");
}
public String toString() {
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
if (numbers.length == lotteryNumbers.length) {
for (int i = 0; i < numbers.length; i++) {
if (i < numbers.length - 1) {
builder.append(numbers[i] + ", ");
builder2.append(lotteryNumbers[i] + ", ");
} else {
builder.append(numbers[i] + " + ");
builder2.append(lotteryNumbers[i] + " + ");
}
}
} else {
return "ERROR: Numbers max set of numbers doesn't match Lottery Numbers max set of numbers!\n";
}
return "Your set of numbers were: " + builder + Integer.toString(powerBall) +
"\nThe powerball numbers were: " + builder2 + lotteryPowerBall;
}
}
Launcher
public class launchPowerBall {
public static void main(String[] args) throws InterruptedException {
// Build the GUI object
PowerBallGUI GUI = new PowerBallGUI();
GUI.buildGUI();
//GUI.setTextArea("banana");
// Build the PowerBall object
PowerBall roll = new PowerBall();
while(true) {
if (GUI.getJButton().getModel().isPressed()) {
System.out.println("TEST");
}
}
//System.out.println("TOO LATE!");
//while (true) {
/*roll.randomize();
System.out.println(roll.toString());
roll.calculate();
roll.displayBalance();
roll.displayWinnings();
Thread.sleep(500); */
//}
}
}
GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PowerBallGUI {
private JButton start = new JButton("Launch the Powerball!");
private boolean buttonPressed = false;
private String outText;
/*** Constructor Methods ***/
public PowerBallGUI() {
#SuppressWarnings("unused")
JTextArea outputText = new JTextArea("Press the 'Launch the Powerball' button to start!");
}
/*** Setters ***/
/*** Sets the JTextArea object ***/
public void setTextArea (String str) {
this.outText = str;
}
public void setButtonPressed (Boolean bool) {
this.buttonPressed = bool;
}
/*** Getters ***/
public Boolean getButtonPressed() {
return this.buttonPressed;
}
public JButton getJButton() {
return this.start;
}
/*** Builds the GUI ***/
public void buildGUI() {
// Create the Java Frame itself
JFrame frame = new JFrame("Can YOU win the Powerball? v1.0 (Programmed by: Josh Yang)");
// Sets the default close operation of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the size of the frame
frame.setSize(800, 500);
// Sets the location of the frame
centerGUI(frame);
// Allows the frame to be seen
frame.setVisible(true);
// Disables frame resizing
//frame.setResizable(false);
// Create the Java Panel itself
JPanel panel = new JPanel();
JPanel contentPanel = new JPanel();
JPanel launchPanel = new JPanel();
// Sets the sides of the Java panels
panel.setSize(800, 150);
// Set the panel background color
panel.setBackground(Color.YELLOW);
contentPanel.setBackground(Color.YELLOW);
launchPanel.setBackground(Color.PINK);
// Add the panel onto the frame
frame.add(panel, "North");
frame.add(contentPanel, BorderLayout.CENTER);
frame.add(launchPanel, BorderLayout.SOUTH);
// Set top panel's preferred size dimensions
panel.setPreferredSize(new Dimension(800, 100));
// Adds components onto the panel
JLabel title = new JLabel("Can YOU win the lottery? v1.0", SwingConstants.CENTER);
title.setFont(new Font("Serif", Font.BOLD, 25));
panel.add(title);
String text = "Basically, we start you off at $1000 and buy tickets in increments of $2 until you win big (if you do, that is)!";
JLabel description = new JLabel();
description.setText(text);
description.setFont(new Font("Serif", Font.PLAIN, 16));
panel.add(description);
// ContentPanel area
JLabel cDescription = new JLabel("Output: ");
contentPanel.add(cDescription);
JTextArea outputText = new JTextArea(17, 60);
outputText.setBackground(Color.PINK);
outputText.setEditable(false);
outputText.setText("Press the 'Launch the Powerball' button to start!");
contentPanel.add(outputText);
start.setLocation(100, 100);
launchPanel.add(start);
// Add an action listener to the JButton
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
frame.revalidate();
//frame.pack();
}
/*** Centers the GUI based on screen size ***/
public static void centerGUI(Window frame) {
// Gets the size of the screen
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
// Set the frame location based on x and y
frame.setLocation(x, y);
}
}
The simple solution is to take the functionality you're "trying" to execute in the main method and put in the ActionListener...
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
PowerBall roll = new PowerBall();
roll.randomize();
System.out.println(roll.toString());
roll.calculate();
roll.displayBalance();
roll.displayWinnings();
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
If you "really" want to do more work in the main, you will need to generate some kind of observer pattern which can notified when something occurs.
You could put one on Powerball so it could notify you of a status change or on the GUI which notify you that the start button was pressed

I try to create a vocabulary loop in android

I am trying to make an app that alike vocabulary card.
I have an Answer array(array size = 4).
I am creating random an english word then I am adding true value of english word in answer array and I am removing true value of english word in turkish array in order to not use again in random.I am doing same things to other answer array include wrong value.
Problem is that array size is going to 0.for example my total array 20 .when I remove true value,array size is going to 19-18-17... per click then program close.
Here is my code:
package de.murattekinlive.pwords;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class WordsActivity extends AppCompatActivity {
TextView textView;
TextView deneme;
DataBase dataBase;
Button btn_r1,btn_r2,btn_r3,btn_r4;
String [] TR_WORDS;
String [] EN_WORDS;
String [] Answer;
int control_id = 0;
int random ;
Random control;
Random rnd;
int tr,en;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_words);
textView = (TextView) findViewById(R.id.textView);
deneme = (TextView) findViewById(R.id.textView3);
dataBase = new DataBase(getApplicationContext());
rnd= new Random();
btn_r1 = (Button)findViewById(R.id.button_random1);
btn_r1.setOnClickListener(new myClickListener());
btn_r2 = (Button)findViewById(R.id.button_random2);
btn_r2.setOnClickListener(new myClickListener());
btn_r3 = (Button)findViewById(R.id.button_random3);
btn_r3.setOnClickListener(new myClickListener());
btn_r4 = (Button)findViewById(R.id.button_random4);
btn_r4.setOnClickListener(new myClickListener());
ArrayList<Words> enWordlist = (ArrayList<Words>) dataBase.allEnWords();
ArrayList<Words> trWordlist =(ArrayList<Words>) dataBase.allTrWords();
TR_WORDS = new String[trWordlist.size()];
EN_WORDS = new String[enWordlist.size()];
for(int i=0;i<enWordlist.size();i++){
EN_WORDS[i] =enWordlist.get(i).getWORD().toString();
TR_WORDS[i] =trWordlist.get(i).getTR1().toString();
}
tr = new Random().nextInt(TR_WORDS.length);
/*btn_r1.setText(TR_WORDS[en]);
btn_r2.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r3.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r4.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);*/
ReStart();
}
private class myClickListener implements View.OnClickListener{
public void onClick(View v){
switch ( v.getId() ) {
case R.id.button_random1:
break;
case R.id.button_random2:
break;
case R.id.button_random3:
break;
case R.id.button_random4:
break;
default:
break;
}
WordsActivity.this.ReStart();
}
}
public void ReStart(){
Answer = new String[4];
control = new Random();
control_id = control.nextInt(4);
en = new Random().nextInt(EN_WORDS.length);
final List<String> newTRList = new ArrayList<>();
textView.setText(EN_WORDS[en]);
final int sayi1,sayi2;
sayi1 = TR_WORDS.length;
Collections.addAll(newTRList,TR_WORDS);
// I added true turkish word in answer array
for(int i=0;i<TR_WORDS.length;i++){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
TR_WORDS = newTRList.toArray(new String[newTRList.size()]);
//I added another values in answer array and I want to remove values that is used because
//I dont want to see same value in answer array.
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
sayi2 =TR_WORDS.length;
deneme.setText(sayi1+"/"+sayi2);
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
for(int j=0;j<=3;j++){
if(j==0){
btn_r1.setText(Answer[j].toString());
}
else if(j==1){
btn_r2.setText(Answer[j].toString());
}
else if(j==2){
btn_r3.setText(Answer[j].toString());
}
else if(j==3){
btn_r4.setText(Answer[j].toString());
}
}
}
}
Change your for loop to:
for(int i=TR_WORDS.length; i >=0 ;i--){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
And all the other ones that include a remove in a similar a fashion.

Cannot Find Symbol Error with event handler

I am having trouble trying to initialize a variable correctly. Earlier I was getting a Number Format Exception because I was parsing an integer inside of an empty text field. Now I have created an if statement that checks first to see if the field is empty, then parses an integer inside of it. The problem i'm having now is that my event handler can't recognize the variable, because it is inside the if statement. I tried declaring it outside of the if statement but that didn't work either. Any tips to point me in the right direction? Here is my code:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicReference;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
ArrayList<Integer> deck;
deck = new ArrayList<>();
int i = 1;
while(i < 52){
deck.add(i);
i++;
}
final AtomicReference<String> result = new AtomicReference<>("go.");
Collections.shuffle(deck);
BorderPane pane = new BorderPane();
HBox top = new HBox(10);
Label display = new Label(result.toString());
Button btShuffle = new Button("Shuffle");
btShuffle.setOnAction(
e -> {
Collections.shuffle(deck);
});
top.getChildren().add(display);
top.getChildren().add(btShuffle);
HBox center = new HBox(10);
Card card1 = new Card(deck.get(0));
center.getChildren().add(card1);
Card card2 = new Card(deck.get(1));
center.getChildren().add(card2);
Card card3 = new Card(deck.get(2));
center.getChildren().add(card3);
Card card4 = new Card(deck.get(3));
center.getChildren().add(card4);
HBox bottom = new HBox(10);
Label expression = new Label("Please Enter the expression: ");
TextField tfExpress = new TextField();
LinkedList<Object> expInput = new LinkedList<>();
ArrayList<Character> signs = new ArrayList<>();
signs.add('/');
signs.add('+');
signs.add('(');
signs.add(')');
signs.add('-');
signs.add('^');
signs.add('*');
signs.add('%');
String str = tfExpress.getText();
char tempStor[] = str.toCharArray();
for(char c: tempStor){
expInput.add(c);
}
if(tfExpress.getText() != null && tfExpress.getText().equals(""))
{
int express = Integer.parseInt(str);
}
expInput.removeIf(p-> p.equals(signs));
Button btVerify = new Button("Verify");
btVerify.setOnAction(
(ActionEvent e) -> {
if(card1.CardValue() == (int)expInput.get(0)
&& card2.CardValue() == (int)expInput.get(1)
&& card3.CardValue() == (int)expInput.get(2)
&& card4.CardValue() == (int)expInput.get(3)){
if(express == 24){
result.set("Correct");
}
else
result.set("Incorrect");
}
else
result.set("The numbers in the expression don't "
+ "match the numbers in the set.");
});
pane.setTop(top);
pane.setCenter(center);
pane.setBottom(bottom);
Scene scene = new Scene(pane);
primaryStage.setTitle("24 card game");
primaryStage.setScene(scene);
primaryStage.show();
}
public class Card extends Pane {
public int cardVal;
Card(int card){
Image cardImage;
cardImage = new Image("card/"+ card +".png");
cardVal = card;
}
public int CardValue(){
int card = 0;
if(cardVal <= 13){
card = cardVal;
}
else if(cardVal > 13 && cardVal <= 26){
card = cardVal - 13;
}
else if(cardVal > 26 && cardVal <= 39){
card = cardVal - 26;
}
else if(cardVal > 39 && cardVal <= 52){
card = cardVal - 39;
}
return card;
}
}
public static void main(String[] args) {
launch(args);
}
}
If str being empty is an acceptable behavior for your code, you need to define a default value for express if that is the case. If the default value were -1, for example, you would do:
int express = (str != null && !"".equals(str)) ? Integer.parseInt(str) : -1;
And then later, you should treat the -1 case accordingly.
You need to initialize express like this, so it is effectively final and can be used in the lambda expression.
Instead of
if(tfExpress.getText() != null && tfExpress.getText().equals(""))
{
int express = Integer.parseInt(str);
}
try
final int express = (tfExpress.getText() != null && !tfExpress.getText().equals("")) : Integer.parseInt(str) : 0;

Categories