I am trying to develop a program to generate 10 prime numbers each time a button is pressed but I am struggling. The code to identify the primes is correct but I get the error NullPointerException probably because I am handling the Label Array badly. I'll paste the code below, thanks for any tip on what's going wrong.
public class PrimeGenerator extends Application {
Button generate;
Label listNumbers;
int i;
int multiple = 2;
int number = 2;
int z = 1;
int t = 0;
Label[] primeList;
#Override
public void start(Stage primaryStage) throws Exception {
VBox root = new VBox();
generate = new Button("Generate 10 more primes!");
generate.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
primeList = new Label[10];
while (i < primeList.length) {
multiple = 2;
while (multiple < number) {
t = number % multiple;
if ((t == 0)) {
z = 0;
}
multiple++;
}
// Here I'd like to add the prime number to the array while also adding the Label to the Vbox
if ((z == 1)) {
primeList[i].setText(Integer.toString(number));
root.getChildren().add(primeList[i]);
i++;
}
z = 1;
number++;
}
}
});
root.getChildren().add(generate);
Scene scene = new Scene(root);
primaryStage.setTitle("Prime Numbers Generator");
primaryStage.setScene(scene);
primaryStage.show();
}
}
I think you forgot to initialize the array element
....
primeList[i] = new Label();
primeList[i].setText(Integer.toString(number));
....
You can also in one line
primeList[i] = new Label(Integer.toString(number));
For example
if ((z == 1)) {
primeList[i] = new Label();
primeList[i].setText(Integer.toString(number));
root.getChildren().add(primeList[i]);
i++;
}
Alternatively, you can pre-create elements in advance:
...
#Override
public void handle(ActionEvent e) {
primeList = new Label[10];
for(int labelIdx=0; labelIdx<primeList.length; labelIdx++)
primeList[labelIdx] = new Label();
while (i < primeList.length) {
...
Related
I am now wondering how to automatically highlight the text within a text area. I have researched further and found a method to do so however I am not sure how it can still highlight a String automatically after the user enters search.
Note: Ignore the radio buttons
Here is the method I tried within the action event when clicking the search button
#FXML
private void searchButton(ActionEvent actionEvent){
String key = keyField.getText();
String field = textField.getText();
System.out.println(key);
System.out.println(field);
textField.getText();
if (textField.getText().equals(key)) {
textField.setStyle("-fx-highlight-fill: yellow; -fx-highlight-text-fill: black; -fx-font-size: 12px; ");
textField.setEditable(false);
textField.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
t.consume();
}
});
Platform.runLater(new Runnable() {
#Override
public void run() {
textField.selectRange(13, 18);
}
});
}
ToggleGroup group = new ToggleGroup();
rabinKarpp.setToggleGroup(group);
kmp.setToggleGroup(group);
naive.setToggleGroup(group);
ArrayList indexes = new ArrayList();
if (rabinKarpp.isSelected()){
indexes = RabinKarp.process(field, key);
}
else if (kmp.isSelected()){
indexes = KMPAlgo.process(field, key);
}
else if (naive.isSelected()){
indexes = NaiveAlgo.process(field, key);
}
else if(!naive.isSelected() && !kmp.isSelected() && !rabinKarpp.isSelected()) {
Alert alert = new Alert(Alert.AlertType.WARNING, "Select an algorithm first before proceeding.",ButtonType.OK);
alert.showAndWait();
}
}
the expected output should be the "hello" from "hello everyone" to be highlighted but I'm still stumped on how to do so.
EDIT:
The code now looks like this but still the highlights will not turn up sadly.
#FXML
protected void searchButton(ActionEvent actionEvent){
String key = keyField.getText();
String field = textField.getText();
System.out.println(key);
System.out.println(field);
ToggleGroup group = new ToggleGroup();
rabinKarpp.setToggleGroup(group);
kmp.setToggleGroup(group);
naive.setToggleGroup(group);
ArrayList indexes = new ArrayList();
if (rabinKarpp.isSelected()){
indexes = RabinKarp.process(field, key);
}
else if (kmp.isSelected()){
indexes = KMPAlgo.process(field, key);
}
else if (naive.isSelected()){
indexes = NaiveAlgo.process(field, key);
}
else if(!naive.isSelected() && !kmp.isSelected() && !rabinKarpp.isSelected()) {
Alert alert = new Alert(Alert.AlertType.WARNING, "Select an algorithm first before proceeding.",ButtonType.OK);
alert.showAndWait();
}
}
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
List<List<Integer>> locations = new ArrayList();
keyField.textProperty().addListener((o, oldValue, newValue) -> {
Pattern pattern = Pattern.compile(newValue);
Matcher matcher = pattern.matcher(textField.getText());
locations.clear();
if (newValue.isEmpty()) {
// no highlighting for the empty search string
textField.deselect();
} else {
int index = textField.getText().indexOf(newValue);
if (index < 0) {
// text not found
textField.deselect();
} else {
while(matcher.find())
{
List<Integer> tempList = new ArrayList<>();
tempList.add(matcher.start());
tempList.add(matcher.end());
locations.add(tempList);
}
}
}
});
AtomicInteger currentIndex = new AtomicInteger(-1);
downButton.setOnAction((t) -> {
if(currentIndex.get() >= -1 && currentIndex.get() < locations.size() - 1)
{
textField.selectRange(locations.get(currentIndex.incrementAndGet()).get(0), locations.get(currentIndex.get()).get(1));
}
});
upButton.setOnAction((t) -> {
if(currentIndex.get() > 0 && currentIndex.get() <= locations.size())
{
textField.selectRange(locations.get(currentIndex.decrementAndGet()).get(0), locations.get(currentIndex.get()).get(1));
}
});
}
Simply listen to the text property of the TextField for this purpose. Note that you can only select a single range using TextArea. If you need to highlight multiple occurances you may want to use a TextFlow and it's rangeShape method as suggested by #Slaw.
#Override
public void start(Stage stage) throws IOException {
TextArea textArea = new TextArea();
VBox.setVgrow(textArea, Priority.ALWAYS);
Random random = new Random();
for (int l = 0; l < 10; l++) {
for (int i = 0; i < 300; i++) {
textArea.appendText(Character.toString('a' + random.nextInt('z'- 'a' + 1)));
}
textArea.appendText("\n");
}
TextField textField = new TextField();
textField.textProperty().addListener((o, oldValue, newValue) -> {
if (newValue.isEmpty()) {
// no highlighting for the empty search string
textArea.deselect();
} else {
int index = textArea.getText().indexOf(newValue);
if (index < 0) {
// text not found
textArea.deselect();
} else {
// select first occurance
textArea.selectRange(index, index + newValue.length());
}
}
});
Scene scene = new Scene(new VBox(textArea, textField));
stage.setScene(scene);
stage.show();
}
Using fxml the proper place to register a listener like this would be the initialize method.
I would like to add on to #fabian's answer. If you want to find multiple occurrences one at a time, you can find all the matches in the string and save their indexes to a list. The list can be used to step through each occurrence.
I have added 4 occurrences of hello to fabian's original string. You can type hello into the TextField and hit up and then down, to reach each occurrence.
TextArea textArea = new TextArea();
VBox.setVgrow(textArea, Priority.ALWAYS);
Random random = new Random();
for (int l = 0; l < 10; l++) {
for (int i = 0; i < 300; i++) {
textArea.appendText(Character.toString('a' + random.nextInt('z'- 'a' + 1)));
}
textArea.appendText("\n");
}
textArea.replaceText(0, 5, "hello");
textArea.replaceText(20, 25, "hello");
textArea.replaceText(30, 35, "hello");
textArea.replaceText(textArea.getText().length() - 6, textArea.getText().length() -1, "hello");
TextField textField = new TextField();
List<List<Integer>> locations = new ArrayList();
textField.textProperty().addListener((o, oldValue, newValue) -> {
Pattern pattern = Pattern.compile(newValue);
Matcher matcher = pattern.matcher(textArea.getText());
locations.clear();
if (newValue.isEmpty()) {
// no highlighting for the empty search string
textArea.deselect();
} else {
int index = textArea.getText().indexOf(newValue);
if (index < 0) {
// text not found
textArea.deselect();
} else {
while(matcher.find())
{
List<Integer> tempList = new ArrayList<>();
tempList.add(matcher.start());
tempList.add(matcher.end());
locations.add(tempList);
}
}
}
});
AtomicInteger currentIndex = new AtomicInteger(-1);
Button btnDown = new Button("Down");
btnDown.setOnAction((t) -> {
if(currentIndex.get() >= -1 && currentIndex.get() < locations.size() - 1)
{
textArea.selectRange(locations.get(currentIndex.incrementAndGet()).get(0), locations.get(currentIndex.get()).get(1));
}
});
Button btnUp = new Button("Up");
btnUp.setOnAction((t) -> {
if(currentIndex.get() > 0 && currentIndex.get() <= locations.size())
{
textArea.selectRange(locations.get(currentIndex.decrementAndGet()).get(0), locations.get(currentIndex.get()).get(1));
}
});
Scene scene = new Scene(new VBox(textArea, textField, new HBox(btnDown, btnUp)));
stage.setScene(scene);
stage.show();
I normally don't go on sites like these but I got a serious nooby question and can't really find out how to fix this.
So I have a simple dice that rolls when you hit a button. It prints out all the dice numbers in the console. Now I want to save the last int so I can do calculations etc with it. Now the problem is I have serious no idea how to get the last int of the dice and print it out in the console. Does anyone have experience in this and can help me? Here is my code:
btn.setText("Roll Die");
btn.setOnAction((ActionEvent event) -> {
btn.setDisable(true);//Disable Button
Random random = new Random();
int gekozen = Integer.parseInt(tf3.getText());
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(.3), (actionEvent) -> {
int tempRandom = random.nextInt(6) + 1;
System.out.println(tempRandom);
die.setDieFace(tempRandom);
}));
timeline.setCycleCount(random.nextInt(20) + 1);
timeline.play();
timeline.setOnFinished(actionEvent -> {
btn.setDisable(false);//Enable Button
});
});
The best option is just to store the values somewhere. Your Die class (or whatever the class die is from) seems like a good candidate for that. In a well designed class, if you pass a value to a set method, say setXyz(x), then calling getXyz(), with no operations on the same object in the meantime, will return the same value x. So if you have designed your class following standard Java patterns, you can just do
timeline.setCycleCount(random.nextInt(20) + 1);
timeline.play();
timeline.setOnFinished(actionEvent -> {
btn.setDisable(false);//Enable Button
int dieValue = die.getDieFace();
System.out.println(dieValue);
});
Another option is to compute all the temporary die values ahead of time:
btn.setText("Roll Die");
btn.setOnAction((ActionEvent event) -> {
btn.setDisable(true);//Disable Button
Random random = new Random();
int gekozen = Integer.parseInt(tf3.getText());
int numTempValues = random.nextInt(20) + 1 ;
int[] tempValues = random.ints(1, 7).limit(numTempValues).toArray();
int finalDieValue = tempValues[numTempValues - 1];
Timeline timeline = new Timeline() ;
for (int i = 0 ; i < tempValues.length ; i++) {
KeyFrame keyFrame = new KeyFrame(Duration.seconds(0.3).multiply(i+1), actionEvent -> {
System.out.println(tempValues[i]);
die.setDieFace(tempValues[i]);
});
timeline.getKeyFrames().add(keyFrame);
}
timeline.setOnFinished(actionEvent -> {
btn.setDisable(false);//Enable Button
System.out.println("You rolled: "+finalDieValue);
});
timeline.play();
});
You can add an int variable to the Die class.
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/**
*
* #author blj0011
*/
public class Die
{
ImageView dieFace;
Image[] images;
int dieValue;
public Die(Image[] images)
{
this.images = images;
dieFace = new ImageView(this.images[0]);//set default to image 0
dieValue = 1;
}
public Die(Image[] images, int dieFaceValue)
{
//Need to catch for values less than 1 and greater than 6!
this.images = images;
dieFace = new ImageView(this.images[dieFaceValue - 1]);
dieValue = dieFaceValue;
}
public ImageView getdieFace()
{
return dieFace;
}
public int getDieValue()
{
return dieValue;
}
public void setDieFace(int dieFaceValue)
{
//Need to catch for values less than 1 and greater than 6!
dieFace.setImage(this.images[dieFaceValue - 1]);
dieValue = dieFaceValue;
}
}
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)
I have an assignment where I am to create a chutes and ladder game using JavaFX.
What I am currently stuck on is once the user selects how many players they want, the method I run pushes an error.
I have run it through the debugger and I know what line is the problem, but I have no idea where to go from here.
The exception is:
Exception in thread "JavaFX Application Thread"
java.lang.ArrayIndexOutOfBoundsException: 0
I found that if I change the zero in private Players [] players = new Players[0]; to a 4, it works. However, I get another error if I try to change the 0 in private Circle [] c = new Circle[0];
public class Main extends Application {
private final int BOARD_DIM = 10;
private Players [] players = new Players[0];
private Circle [] c = new Circle[0];
public static void main(String[]args){
launch();
}
public void start(Stage pStage) throws Exception{
//ROOT PANE
BorderPane root = new BorderPane();
//MENUBAR
//BOARD CREATION
//PLAYER SELECTION/RESUME PREVIOUS GAME
//Drop down menu
HBox players = new HBox();
Label intro = new Label("Select # of players");
ChoiceBox<String> p = new ChoiceBox<>();
p.getItems().addAll("2","3","4");
p.setPadding(new Insets(6));
//Button to start new game
Button startGame = new Button("Start Game");
startGame.setOnAction(e -> getChoice(p));
startGame.setPadding(new Insets(10));
players.getChildren().addAll(intro,p,startGame);
root.setRight(players);
Scene scene = new Scene(root, 900, 650);
pStage.setTitle("Chutes and Ladders");
pStage.setScene(scene);
pStage.show();
}
private void getChoice(ChoiceBox<String> p) {
int numOfPlayers = Integer.parseInt(p.getValue());
for(int i = 0; i < numOfPlayers; i++){
players[i] = new Players("p"+(i+1),9,0, false);
c[i] = new Circle(25);
}
c[0].setFill(Color.GREEN);
c[1].setFill(Color.YELLOW);
if(numOfPlayers >= 3){
c[2].setFill(Color.RED);
}
if(numOfPlayers == 4){
c[3].setFill(Color.BLACK);
}
}
You are initalizing players and c as arrays with length 0. And in the loop you are iterating over the elements from 0 to numOfPlayers. That's what is causing the exception.
First just declare your arrays:
private Players [] players;
private Circle [] c;
Then in the your method, initalize the arrays with the length you need (If you need to alter the length later I would suggest to switch to ArrayLists).
private void getChoice(ChoiceBox<String> p) {
int numOfPlayers = Integer.parseInt(p.getValue());
c = new Circle[numOfPlayers]; //add these lines
players = new Players[numOfPlayers]; //add these lines
for(int i = 0; i < numOfPlayers; i++){
players[i] = new Players("p"+(i+1),9,0, false);
c[i] = new Circle(25);
}
...
}
I have coded a simple memory game. Card values are added to two arrays and after that, a compare function is called. But there is a problem with the logic of the compare function.
The specific problem seems related to the fact that the compare function is called on the third button click. So on first click it adds first value to first array , on second click second value to second array. But I must click for yet a third time to call the compare function to compare the match of two arrays.
The main problem is that after all cards are inverted (10 matches in 5x4 memory game), it does not show the result.
I have uploaded full code here : http://uloz.to/xcsJkYUK/memory-game-rar .
public class PEXESO5x4 extends JFrame implements ActionListener {
private JButton[] aHracieTlactika = new JButton[20];
private ArrayList<Integer> aHodnoty = new ArrayList<Integer>();
private int aPocitadlo = 1;
private int[] aTlacitkoIden = new int[2];
private int[] aHodnotaTlac = new int[2];
private JButton aTlacitkoExit;
private JButton aTlacitkoReplay;
private JButton[] aHracieTlacitko = new JButton[20];
private int aPocetTahov = 0;
public void vkladanieHodnot() {
for (int i = 0; i < 2; i++) {
for (int j = 1; j < (this.aHracieTlactika.length / 2) + 1; j++) {
this.aHodnoty.add(j);
}
}
Collections.shuffle(this.aHodnoty);
}
public boolean zhoda() {
if (this.aHodnotaTlac[0] == this.aHodnotaTlac[1]) {
return true;
}
return false;
}
public void zapisCislaDoSuboru() {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Semestralka.txt", true)))) {
out.println("haha");
//more code
out.println("hahahahha");
//more code
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
public void actionPerformed(ActionEvent e) {
int match = 0;
if (this.aTlacitkoExit == e.getSource()) {
System.exit(0);
}
if (this.aTlacitkoReplay == e.getSource()) {
}
for (int i = 0; i < this.aHracieTlactika.length; i++) {
if (this.aHracieTlactika[i] == e.getSource()) {
this.aHracieTlactika[i].setText("" + this.aHodnoty.get(i));
this.aHracieTlactika[i].setEnabled(false);
this.aPocitadlo++;
this.aPocetTahov += 1;
if (this.aPocitadlo == 3) {
if (this.zhoda()) {
match+=1;
if (match==10)
{
System.out.println("You win");
}
this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(false);
this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(false);
} else {
this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(true);
this.aHracieTlactika[this.aTlacitkoIden[0]].setText("");
this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(true);
this.aHracieTlactika[this.aTlacitkoIden[1]].setText("");
}
this.aPocitadlo = 1;
}
if (this.aPocitadlo == 1) {
this.aTlacitkoIden[0] = i;
this.aHodnotaTlac[0] = this.aHodnoty.get(i);
}
if (this.aPocitadlo == 2) {
this.aTlacitkoIden[1] = i;
this.aHodnotaTlac[1] = this.aHodnoty.get(i);
}
}
}
}
}