How do I add the Timer of the game? - java

My friends and i are creating a gme like bejeweled. it is almost over, but we have some problems. We couldn't add Timer to game. for example, we want to that level 1 finished after 2 minutes. How can we do?
//in this class, we created game area etc.
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class Level1 extends JFrame {
private JPanel anaPanel, p1;
private JPanel grid;
public String comand;
public static JButton[] buttons;
public String imgName;
public Color c1, c2;
public String score=ButtonActionListener.str;
public Level1() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x= ((dim.width-960)/2);
int y= ((dim.height-640)/2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(x, y, 960,640);
anaPanel = new JPanel();
anaPanel.setLayout(new GridLayout(1,2));
p1=new JPanel();
JLabel background = new JLabel(new ImageIcon("img//sol.png"));
c1 = new Color(21,120,227);
c2 = new Color(250,215,1);
grid=new JPanel();
grid.setLayout(new GridLayout(8,8,5,5));
grid.setBounds(5, 5, 460, 640);
buttons = new JButton[64];
//Creating random image for buttons
ActionListener buttonActionListener = new ButtonActionListener();
for (int i = 0; i<buttons.length; i++) {
Random r = new Random();
int a = r.nextInt(7)+1;
switch(a){
case 1 : buttons[i]=new JButton(new ImageIcon("img//Cakal.png"));
break;
case 2 : buttons[i]=new JButton(new ImageIcon("img//BugsBunny.png"));
break;
case 3 : buttons[i]=new JButton(new ImageIcon("img//Pig.png"));
break;
case 4 : buttons[i]=new JButton(new ImageIcon("img//Taz.png"));
break;
case 5 : buttons[i]=new JButton(new ImageIcon("img//Sam.png"));
break;
case 6 : buttons[i]=new JButton(new ImageIcon("img//DuffyDuck.png"));
break;
case 7 : buttons[i]=new JButton(new ImageIcon("img//Tweety.png"));
break;
/*case 8 : buttons[i]=new JButton(new ImageIcon("img//Slyvester.png"));
break;
case 9 : buttons[i]=new JButton(new ImageIcon("img//RoadRunner.png"));
break;*/
}
buttons[i].setBorder(BorderFactory.createEmptyBorder());
buttons[i].setContentAreaFilled(false);
buttons[i].setFocusable(true);
buttons[i].setOpaque(true);
buttons[i].setBackground(c1);
//Adding number to find easily
comand=Integer.toString(i);
//Get ImageIcon name
imgName=((ImageIcon)buttons[i].getIcon()).toString();
buttons[i].addActionListener(buttonActionListener);
buttons[i].setActionCommand(comand);
grid.add(buttons[i]);
}
grid.setBackground(c1);
p1.add(background);
p1.setBackground(c1);
anaPanel.add(p1);
anaPanel.add(grid);
add(anaPanel);
}
static JButton[] getButton(){
return buttons;
}
public static void main(String[] args){
Level1 l=new Level1();
l.setVisible(true);
}
}
In this class, there are algorithms of game.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class ButtonActionListener implements ActionListener {
public JButton previousButton = null;
public int numP, numC;
public JButton[] buttons=Level1.getButton();
public int score=0;
public static String str;
#Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
JButton currentButton = (JButton)e.getSource();
if (previousButton == null) {
previousButton = currentButton;
return;
}
int numP=Integer.parseInt(((JButton)previousButton).getActionCommand());
int numC=Integer.parseInt(((JButton)currentButton).getActionCommand());
if (numP==(numC+1) || numP==(numC-1) || numP==(numC+8) || numP==(numC-8) ){
Icon previousIcon = previousButton.getIcon();
Icon currentIcon = currentButton.getIcon();
currentButton.setIcon(previousIcon);
previousButton.setIcon(currentIcon);
previousButton = null;
}
else
previousButton=null;
startAnimation();
}
private void startAnimation()
{
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
runAnimation();
}
});
t.start();
}
private int a;
private int b;
private int c;
private int d;
private int e;
private void runAnimation()
{
Random r = new Random();
a = r.nextInt(64);
b = r.nextInt(64);
c = r.nextInt(64);
d = r.nextInt(64);
e = r.nextInt(64);
for(int i=0; i<63; i++)
{
final int iFinal = i;
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
doAnimationStep(iFinal);
}
});
try
{
Thread.sleep(30);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
return;
}
}
}
private void doAnimationStep(int i)
{
String s0 = buttons[i].getIcon().toString();
String s1 = buttons[i+1].getIcon().toString();
String s2 = buttons[i+2].getIcon().toString();
String s3 = buttons[i+3].getIcon().toString();
String s4 = buttons[i+4].getIcon().toString();
if(s0.equals(s1) && s1.equals(s2) && s2.equals(s3) && s3.equals(s4)){
if(i > 7){
for(int j = i; j > 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[j-8].getIcon());
buttons[j+1].setIcon(buttons[j-7].getIcon());
buttons[j+2].setIcon(buttons[j-6].getIcon());
buttons[j+3].setIcon(buttons[j-5].getIcon());
buttons[j+4].setIcon(buttons[j-4].getIcon());
score+=100;
str=String.valueOf(score);
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+1].setIcon(buttons[b].getIcon());
buttons[j+2].setIcon(buttons[c].getIcon());
buttons[j+3].setIcon(buttons[d].getIcon());
buttons[j+4].setIcon(buttons[e].getIcon());
score+=100;
str=String.valueOf(score);
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+1].setIcon(buttons[b].getIcon());
buttons[i+2].setIcon(buttons[c].getIcon());
buttons[i+3].setIcon(buttons[d].getIcon());
buttons[i+4].setIcon(buttons[e].getIcon());
score+=100;
str=String.valueOf(score);
}
}else{
if(s0.equals(s1) && s1.equals(s2) && s2.equals(s3)){
if(i > 7){
for(int j = i; j > 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[j-8].getIcon());
buttons[j+1].setIcon(buttons[j-7].getIcon());
buttons[j+2].setIcon(buttons[j-6].getIcon());
buttons[j+3].setIcon(buttons[j-5].getIcon());
score+=100;
str=String.valueOf(score);
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+1].setIcon(buttons[b].getIcon());
buttons[j+2].setIcon(buttons[c].getIcon());
buttons[j+3].setIcon(buttons[d].getIcon());
score+=100;
str=String.valueOf(score);
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+1].setIcon(buttons[b].getIcon());
buttons[i+2].setIcon(buttons[c].getIcon());
buttons[i+3].setIcon(buttons[d].getIcon());
score+=100;
str=String.valueOf(score);
}
}else{
if(s0.equals(s1) && s1.equals(s2))
{
if(i > 7){
for(int j = i; j > 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[j-8].getIcon());
buttons[j+1].setIcon(buttons[j-7].getIcon());
buttons[j+2].setIcon(buttons[j-6].getIcon());
score+=100;
str=String.valueOf(score);
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+1].setIcon(buttons[b].getIcon());
buttons[j+2].setIcon(buttons[c].getIcon());
score+=100;
str=String.valueOf(score);
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+1].setIcon(buttons[b].getIcon());
buttons[i+2].setIcon(buttons[c].getIcon());
score+=100;
str=String.valueOf(score);
}
}
if(i < 48){
String v0 = buttons[i].getIcon().toString();
String v1 = buttons[i+8].getIcon().toString();
String v2 = buttons[i+16].getIcon().toString();
if(v0.equals(v1) && v1.equals(v2)) {
if(i > 23){
for(int j = i; j >= 0; j=j-8){
if(j > 23){
buttons[j].setIcon(buttons[j-24].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
score+=100;
str=String.valueOf(score);
}
else if(j > 15){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
score+=100;
str=String.valueOf(score);
}
else if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else if(i > 15){
for(int j = i; j >= 0; j=j-8){
if(j > 15){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else if(i > 7){
for(int j = i; j >= 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+8].setIcon(buttons[b].getIcon());
buttons[i+16].setIcon(buttons[c].getIcon());
}
}
}else{
String v0 = buttons[i-16].getIcon().toString();
String v1 = buttons[i-8].getIcon().toString();
String v2 = buttons[i].getIcon().toString();
if(v0.equals(v1) && v1.equals(v2)) {
if(i > 23){
for(int j = i; j >= 0; j=j-8){
if(j > 23){
buttons[j].setIcon(buttons[j-24].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else if(j > 15){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else if(i > 15){
for(int j = i; j >= 0; j=j-8){
if(j > 15){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else if(i > 7){
for(int j = i; j >= 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+8].setIcon(buttons[b].getIcon());
buttons[i+16].setIcon(buttons[c].getIcon());
}
}
}
}
}
}
public String getScore(){
return str;
}
}

Have a look into swing timers.
It's easy to implement and should be enough for your purpose.
You could make it count down the time for user, and at the end, stop the level (let the player retry etc.).
Hope this helps.

You can use the Timer class with it's schedule() method.
On callback simple call the methods to "end your level".

You could do something like this:
int counter = 0;
for (int j = 0 ; j <60 ; j++)
{
delayer (1000);
counter++;
}
if (counter == 60)
{
// put what you want to happen after 60 seconds here
}
and then have a delayer method:
private static void delayer (long milliseconds)
{
try
{
Thread.sleep (1000);
}
catch (InterruptedException ex)
{
}
}

Related

Is there a solution to prevent this recursion?

In this program, a randomly generated 2D array is populated with 1's or 0's and I attempt to find a path of 1's (no diagonal movement). I have got the program to work for smaller dimensions of the 2D array, but when the dimensions are too large, the error Exception in thread "main" java.lang.StackOverflowError occurs.
import java.util.Scanner;
import java.util.Random;
public class Daft {
private int counter = 0;
public static void main(String[] args) {
Daft punk = new Daft();
punk.run();
}
public void run() {
int ans;
int[][] array;
int[][] solvedPath;
do {
counter = 1;
array = populate(defineArray(firstDimension(),secondDimension()));
solvedPath = findPath(array);
System.out.println("Times before solvable: " + counter);
print(solvedPath);
ans = continuity();
}while(ans != 0);
}
public int[][] findPath(int[][] array) {
int r = 0, c = 0;
while(true) {
array[0][0] = 7;
if(c == 0 && r == array.length-1) { //reached the bottom left, checks right
if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else {
array[r][c] = 7;
break;
}
} else if(c == array[0].length-1 && r == array.length-1) { //reached the bottom right, checks left
if(array[r][c-1] == 1) {
array[r][c-1] = 7;
} else {
array[r][c] = 7;
break;
}
} else if(r == array.length-1) { //reached the bottom, checks left/right
if(array[r][c+1] == 1 && array[r][c-1] == 1) {
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else { //end of path
array[r][c] = 7;
break;
}
} else if(c == 0) { //reached the left, checks right/bottom
if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(c == array[0].length-1) { //reached the right, checks left/bottom
if(array[r+1][c] == 1 && array[r][c-1] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) {
array[r][c-1] = 7;
c-=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c-1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) { //checks bottom
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else {
counter++;
newPath(array);
break;
}
}
return array;
}
public int firstDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the first dimension:");
return in.nextInt();
}
public int secondDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the second dimension:");
return in.nextInt();
}
public int[][] defineArray(int firstDimension, int secondDimension) {
return new int[firstDimension][secondDimension];
}
public int[][] populate(int[][] array) {
Random rand = new Random();
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
array[i][j] = rand.nextInt(2);
}
}
return array;
}
public int continuity() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to continue (0 to quit):");
return in.nextInt();
}
public void print(int[][] array) {
for(int[] ints : array) {
for(int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
System.out.println();
}
public void newPath(int[][] array) {
findPath(populate(array));
}
}

Creating a calculator using JFrame

I am a beginner at using Java. I am trying to create a calculator using JFrame through Net beans IDE. When I run the program the build is successful but the GUI display of the calculator is blank. I made sure I put the set visible code but it is still displaying a blank calculator. What could be the problem?
Here is a copy of the code:
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new Calculator();
}
});
//TODO code application logic here
}
JPanel[] row = new JPanel[5];
JButton[] button = new JButton[19];
String[] buttonString = {"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
".", "/", "C","Sqrt",
"+/-", "=", "0"};
int[] dimW = {300,45,100,90};
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]);
boolean[] function = new boolean[4];
double[] temporary = {0, 0};
JTextArea display = new JTextArea(1,20);
Font font = new Font("Times new Roman", Font.BOLD, 12);
Calculator(){
super("Calculator");
setDesign();
setSize(400, 400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout (5,5);
setLayout(grid);
setVisible(true);
for(int i = 0; i < 19; i++)
function[i] = false;
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);
for(int i = 0; i < 5; i++)
row[i] = new JPanel();
row[0].setLayout(f1);
for(int i = 1; i < 5; i++)
row[i].setLayout(f2);
for(int i = 0; i < 19; 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.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
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);
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]);
}
public void clear() {
try {
display.setText("");
for (int i = 0; i < 4; i++)
function[i] = false;
for(int i = 0; i < 2; i++)
temporary[i] = 0;
} catch(NullPointerException e) {
}
}
public void getSqrt() {
try {
double value = Math.sqrt(Double.parseDouble(display.getText()));
display.setText(Double.toString(value));
}
catch(NumberFormatException e) {
}
}
public void getPosNeg() {
try {
double value = Double.parseDouble(display.getText());
if(value !=0) {
value = value * (-1);
display.setText(Double.toString(value));
}
else {
}
} catch(NumberFormatException e) {
}
}
public void getResult() {
double result = 0;
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 {
if(function[2] == true)
result = temporary[0] * temporary[1];
else if(function[3] == true)
result = temporary[0] / temporary[1];
else if(function[0] == true)
result = temporary[0] + temporary[1];
else if(function[1] == true)
result = temporary[0] - temporary[1];
display.setText(Double.toString(result));
for(int i = 0; i < 4; i++)
function[i] = false;
}
catch(NumberFormatException e) {
}
}
public final void setDesign(){
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0])
display.append("7");
if(ae.getSource() == button[1])
display.append("8");
if(ae.getSource() == button[2])
display.append("9");
if(ae.getSource() == button[3]) {
temporary[0] = Double.parseDouble(display.getText());
function[0] = true;
display.setText("");
}
if(ae.getSource() == button[4])
display.append("4");
if(ae.getSource() == button[5]);
display.append("5");
if(ae.getSource() == button[6])
display.append("6");
if(ae.getSource() == button[7]) {
temporary[0] = Double.parseDouble(display.getText());
function[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("1");
if(ae.getSource() == button[9]);
display.append("2");
if(ae.getSource() == button[10]);
display.append("3");
if(ae.getSource() == button[11]) {
temporary[0] = Double.parseDouble(display.getText());
function[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append(".");
if(ae.getSource() == button[13]) {
temporary[0] = Double.parseDouble(display.getText());
function[3] = true;
display.setText("");
}
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15])
getSqrt();
if(ae.getSource() == button[16])
getPosNeg();
if(ae.getSource() == button[17])
getResult();
if(ae.getSource() == button[18])
display.append("0");
}

How to fix my merge sort?

When I compile my merge sort, it compiles fines but there is no output.
This needs to be done recursively. Also, I do run my printList() function in my main, so it isn't that I am forgetting to print the list. I've been staring at this for the past 30 minutes.
public void printList(){
for(int i = 0; i < fullNames.size(); i++){
System.out.println(fullNames.get(i));
}
}
public void sort(){
fullNames = mergeSort(fullNames);
}
public ArrayList<String> extract(ArrayList<String> ex, int low, int high){
ArrayList<String> answer = new ArrayList<String>();
for(int i = low; i <= high; i++){
answer.add(ex.get(i));
}
return answer;
}
public ArrayList<String> merge(ArrayList<String> first, ArrayList<String> second){
int f = 0;
int s = 0;
ArrayList<String> answer = new ArrayList<String>();
while(first.size() > 0 || second.size() > 0){
if(s != second.size() && f != first.size()){
if(first.get(f).compareTo(second.get(s)) > 0){
answer.add(second.get(s));
s++;
}
else if(first.get(f).compareTo(second.get(s)) < 0){
answer.add(first.get(f));
f++;
}
}
else if(f == first.size()){
while(s != second.size()){
answer.add(second.get(s));
s++;
}
}
else{
while(f != first.size()){
answer.add(first.get(f));
f++;
}
}
}
return answer;
}
public ArrayList<String> mergeSort(ArrayList<String> names){
int k = names.size()-1;
if(k > 1){
ArrayList<String> first = extract(names, 0, k / 2);
ArrayList<String> second = extract(names, (k / 2) + 1, k);
mergeSort(first);
mergeSort(second);
return merge(first, second);
}
else{
return names;
}
}
The while condition in your merge will never be false because the size of first and second is never adjusted within the loop:
while(first.size() > 0 || second.size() > 0){
if(s != second.size() && f != first.size()){
if(first.get(f).compareTo(second.get(s)) > 0){
answer.add(second.get(s));
s++;
}
else if(first.get(f).compareTo(second.get(s)) < 0){
answer.add(first.get(f));
f++;
}
}
else if(f == first.size()){
while(s != second.size()){
answer.add(second.get(s));
s++;
}
}
else{
while(f != first.size()){
answer.add(first.get(f));
f++;
}
}
}

Calculator How to make a calculator that can do multiple operations

I created a calculator that can make simple calculations like 9+8 = 17 or 10*3 = 30 But I would like to make one that can do multiple operations like 9*5/2 or 9*5 *6 etc..
here is my code :
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==zero){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("0");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"0");
}
}
}
else if(e.getSource()==one){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("1");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"1");
}
}
}
else if(e.getSource()==two){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("2");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"2");
}
}
}
else if(e.getSource()==three){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("3");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"3");
}
}
}
else if(e.getSource()==four){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("4");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"4");
}
}
}
else if(e.getSource()==five){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("5");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"5");
}
}
}
else if(e.getSource()==six){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("6");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"6");
}
}
}
else if(e.getSource()==seven){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("7");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"7");
}
}
}
else if(e.getSource()==eight){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("8");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"8");
}
}
}
else if(e.getSource()==nine){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("9");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"9");
}
}
}
else if(e.getSource()== negativePositive){
if(answerField.getText().equals("")||answerField.getText().equals("-")){
answerField.setText("-");
}
else{
negativePositive1 = (Double.parseDouble(String.valueOf(answerField.getText())));
negativePositive1 *= -1;
answerField.setText(String.valueOf(negativePositive1));
}
}
else if(e.getSource()==clear){
answerField.setText("");
num1 = 0;
num2 = 0;
addClick = 0;
subClick = 0;
divClick = 0;
multiClick = 0;
}
else if(e.getSource()==decimal){
if(answerField.getText().contains(".")){
answerField.setText(answerField.getText());
}
else{
answerField.setText(answerField.getText()+".");
}
}
else if(e.getSource()==add){
if(answerField.getText()!=null){
num1 = Double.parseDouble(String.valueOf(answerField.getText()));
addClick = 1;
clearField = 1;
}
}
else if(e.getSource()==Subtract){
if(answerField.getText()!=null){
num1 = Double.parseDouble(String.valueOf(answerField.getText()));
subClick = 1;
clearField = 1;
}
}
else if(e.getSource()==multiply){
if(answerField.getText()!=null){
num1 = Double.parseDouble(String.valueOf(answerField.getText()));
multiClick = 1;
clearField = 1;
}
}
else if(e.getSource()==divide){
if(answerField!=null){
answerField.setText(answerField.getText()+"/");
}
if(answerField.getText()!=null){
num1 = Double.parseDouble(String.valueOf(answerField.getText()));
divClick = 1;
clearField = 1;
}
}
else if(e.getSource()==equal){
num2 = Double.parseDouble(String.valueOf(answerField.getText()));
answerField.setText(answerField.getText());
if(addClick ==1){
ans = num1+num2;
answerField.setText(String.valueOf(ans));
addClick = 0;
}
if(subClick ==1){
ans = num1-num2;
answerField.setText(String.valueOf(ans));
subClick = 0;
}
if(multiClick ==1){
ans = num1*num2;
answerField.setText(String.valueOf(ans));
multiClick = 0;
}
if(divClick ==1){
ans = Num1/Num2;
answerField.setText(String.valueOf(ans));
divClick = 0;
}
}
}
Anyone know how I would approach this? I know I am missing something
Consider this example you have 3 buttons: add, substract and equals
private int number = 0;
private void setNumber(int no){
this.number = no;
}
private Integer getNumber(){
return this.number;
}
private void addActionPerformed(java.awt.event.ActionEvent evt) {
int i = 1;
int newAddedNumber = this.number + i;
setNumber(newAddedNumber);
}
private void substractActionPerformed(java.awt.event.ActionEvent evt) {
int i = 1;
int newSubtractedNumber = this.number - i;
setNumber(newSubstractedNumber);
}
private void equalsActionPerformed(java.awt.event.ActionEvent evt) {
int displayCurrentNo = getNumber();
System.out.println("current Number is : " + displayCurrentNo)
}
What this should do is just add or remove 1 from current number.
Its only example and may not be necessary compile-able but this should give you an idea.

Knight's Tour recursive algorithm

Okay everybody, I know the knight's tour problem is popular for all cs students and I am having trouble getting mine to work. I use this recursive algorithm to progress through the moves, however, once I get to around move 50 I have to backtrack since no moves are available and I end up never completing the tour. I pass a ChessNode (holds things like if node has been visited, move it was visited, etc...), next row, next column, and previous node's move count.
private int moveRecur(ChessNode current, int row, int column, int moveV){
current.moveVisited = moveV+1;
if(current.moveVisited > 63){
return 0;
}
if(current.position==13 && aboard[row-1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column+2], row-1, column+2, current.moveVisited);
}
else if(current.position==22 && aboard[row-2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column+1], row-2, column+1, current.moveVisited);
}
else if(current.position == 50 && aboard[row+1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column-2], row+1, column-2, current.moveVisited);
}
else if(current.position == 41 && aboard[row+2][column-1].visited != 1){
current.visited =1;
moveRecur(aboard[row+2][column-1], row+2, column-1, current.moveVisited);
}
else if(current.position == 46 && aboard[row+2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column+1], row+2, column+1, current.moveVisited);
}
else if(current.position == 53 && aboard[row+1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column+2], row+1, column+2, current.moveVisited);
}
else if(current.position == 10 && aboard[row-1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column-2], row-1, column-2, current.moveVisited);
}
else if (current.position == 17 && aboard[row-2][column-1].visited != 1){
current.visited =1;
moveRecur(aboard[row-2][column-1], row-2, column-2, current.moveVisited);
}
if(row+1>=0 && row+1<8 && column+2>=0 && column+2<8){
if(aboard[row+1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column+2], row+1, column+2, current.moveVisited);
}
}
if(row+2>=0 && row+2<8 && column+1>=0 && column+1<8){
if(aboard[row+2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column+1], row+2, column+1, current.moveVisited);
}
}
if(row-1>=0 && row-1<8 && column-2>=0 && column-2<8){
if(aboard[row-1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column-2], row-1, column-2, current.moveVisited);
}
}
if(row-2>=0 && row-2<8 && column-1>=0 && column-1<8){
if(aboard[row-2][column-1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column-1], row-2, column-1, current.moveVisited);
}
}
if(row+1>=0 && row+1<8 && column-2>=0 && column-2<8){
if(aboard[row+1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column-2], row+1, column-2, current.moveVisited);
}
}
if(row+2>=0 && row+2<8 && column-1>=0 && column-1<8){
if(aboard[row+2][column-1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column-1], row+2, column-1, current.moveVisited);
}
}
if(row-1>=0 && row-1<8 && column+2>=0 && column+2<8){
if(aboard[row-1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column+2], row-1, column+2, current.moveVisited);
}
}
if(row-2>=0 && row-2<8 && column+1>=0 && column+1<8){
if(aboard[row-2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column+1], row-2, column+1, current.moveVisited);
}
}
//System.out.println(current.position + " "+current.moveVisited);
current.visited = 0;
return 0;
}
So, initially I check for the spots that can move to the corner board positions, and then I just make recursive calls based on available moves. So I guess my main question is am I doing something wrong? or is there another condition I can used to make the tour a little more intuitive?
Thanks in advance!
This is the Knight's tour code in java and has a brilliant layout. I did this using backtracking using recursion. This was my class assignment. Do contact me if you have any problem understanding or running this code.
package knights.tour;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.*;
import javax.swing.*;
public class KnightsTour extends JFrame implements ActionListener{
//All the static variables used between action listeners and functions.
public static String path;
public static int btnPressed = 0;
public static int rowSelected;
public static String[] pathArray;
public static int[][] coordinatesArray;
public static int columnSelected;
public static int flag =0;
public static int increment = 0;
public static JPanel panel1 = new JPanel();
public static JPanel panel3 ;
public static JButton btnStart = new JButton("Start Animation");
public static JButton btnClear = new JButton("Clear");
public static JTextArea lblPath = new JTextArea();
public static JLabel lblStartRow = new JLabel();
public static JLabel lblStartColumn = new JLabel();
public static JButton[][] button;
public static int variableForIncrement=0;
static int row ;
static int column ;
static int[][] array = new int[row][column];
public static int count = 1;
KnightsTour(){
//Setting layout of the frame in the constructor and adding buttons to the panel and the frame.
getContentPane().setLayout(new GridLayout(2,1));
lblPath.setLineWrap(true);
lblPath.setColumns(10);
lblPath.setSize(700, 100);
lblPath.setEditable(false);
panel1.add(btnStart);
panel1.add(btnClear);
panel1.add(lblStartRow);
panel1.add(lblStartColumn);
panel1.add(lblPath);
panel3 = new JPanel(new GridLayout(row,column));
// Initializing Array of buttons for the user to click on the chess board.
button= new JButton[row][column];
array = new int[row][column];
coordinatesArray = new int[row*column][2]; // This array stores the coordinates as the Knight
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
button[i][j] = new JButton();
}
}
//Setting background of the buttons to black and white for chessboard layout.
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(i%2 ==j%2){
button[i][j].setBackground(Color.BLACK);
button[i][j].setForeground(Color.WHITE);
}
else{
button[i][j].setBackground(Color.WHITE);
}
panel3.add(button[i][j]);
button[i][j].addActionListener(this);
}
}
btnClear.addActionListener(this);
btnStart.addActionListener(this);
add(panel3);
add(panel1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO code application logic here
String input =JOptionPane.showInputDialog("Enter the rows and columns in the format (row,column)");
String[] ar = input.split(",");
row = Integer.parseInt(ar[0]); // Finding out row and column from the user input.
column = Integer.parseInt(ar[1]);
pathArray = new String[row*column]; // This array is kept to store the path of the knight.
JFrame frame = new KnightsTour();
frame.setVisible(true);
frame.setSize(700,700);
}
//All the computation takes place in this function. It checks the neighbour and recursively calls itself.
public static void neighbourRecursion(int a,int b){
pathArray[increment] = Integer.toString(a) + "," + Integer.toString(b); // Storing the path of the Knight
increment++;
array[a][b] = count; //Stroing value of count.
button[a][b].setText(String.valueOf(count));
coordinatesArray[variableForIncrement][0] = button[a][b].getX(); //Finding coordinates of buttons to show animation
coordinatesArray[variableForIncrement][1] = button[a][b].getY();
count++;
variableForIncrement++;
//Checking for valid neighbours and calling itself recursively.
if(a <= row-3 && b<=column-2){
if(alreadyVisited(a+2,b+1)){
neighbourRecursion(a+2,b+1);
}
}
if(a<=row-3 && b>=1){
if(alreadyVisited(a+2,b-1)){
neighbourRecursion(a+2,b-1);
}
}
if(a>=2 && b<=column-2){
if(alreadyVisited(a-2,b+1)){
neighbourRecursion(a-2,b+1);
}
}
if(a>=2 && b>=1){
if(alreadyVisited(a-2,b-1)){
neighbourRecursion(a-2,b-1);
}
}
if(a<=row-2 && b>=2){
if(alreadyVisited(a+1,b-2)){
neighbourRecursion(a+1,b-2);
}
}
if(a<=row-2 && b<=column-3){
if(alreadyVisited(a+1,b+2)){
neighbourRecursion(a+1,b+2);
}
}
if(a>=1 && b>=2){
if(alreadyVisited(a-1,b-2)){
neighbourRecursion(a-1,b-2);
}
}
if(a>=1 && b <=column-3){
if(alreadyVisited(a-1,b+2)){
neighbourRecursion(a-1,b+2);
}
}
//Breaking condition of the function.
if(count == (row*column)+1){
}
// Backtracking condition if there is no neighbour.
else{
button[a][b].setText("");
array[a][b]=0;
count--;
variableForIncrement--;
if(increment >0){
increment--;
}
return ;
}
}
//This function checks if the neighbour is already visited.
public static boolean alreadyVisited(int a,int b){
if(array[a][b] != 0){
return false;
}
else{
return true;
}
}
#Override
public void actionPerformed(ActionEvent e) {
//when clear is pressed all arrays and global variables are set to initial conditon.
if(e.getSource() == btnClear){
for(int i =0;i<row;i++){
for(int j=0;j<column;j++){
array[i][j] = 0;
button[i][j].setText("");
count = 1;
lblPath.setText("");
lblStartRow.setText("");
lblStartColumn.setText("");
flag =0;
variableForIncrement=0;
increment =0;
path =" ";
}
}
}
//If start animation button is pressed animation is started.
else if(e.getSource() == btnStart){
animate();
}
// When the button is pressed.
else{
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(e.getSource() == button[i][j]){
if(flag == 1){
lblPath.setText(" Please press clear before clicking again"); // Button pressed twice without reset.
}
else{
rowSelected = i;
columnSelected =j;
// If odd * odd board and selected postion is odd then No path is possible.
if(row%2 ==1 && column%2 == 1 && rowSelected%2 ==0 && columnSelected%2 == 1 || row%2 ==1 && column%2 == 1 && rowSelected%2 ==1 && columnSelected%2 == 0){
lblPath.setText(" Path not possible from this point");
}
else{
int count;
lblStartRow.setText("Starting Row : "+String.valueOf(rowSelected + 1));
lblStartColumn.setText("Starting Column : "+String.valueOf(columnSelected + 1));
count = 1;
flag = 1;
startTour(); //Start tour function called.
for(int q=0;q<row;q++){
for(int w=0;w<column;w++){
if(array[i][j] == 0){
count++;
}
}
}
if(count > 2){
lblPath.setText(" No Path found");
}
//Printing path of the knight here.
else{
for(int k=0;k<pathArray.length;k++){
path = path+"->"+ pathArray[k];
}
lblPath.setText(" Path : \n"+ path.substring(5));
}
btnPressed = 1;
break;
}
}
}
}
}
} }
//Function for the animation.
void animate(){
if(btnPressed == 1){
btnPressed =0;
Graphics g = getGraphics();
for(int i=0;i<(row*column)-1;i++){
try {
Thread.sleep(600); // this function slows down drawing of lines.
} catch (InterruptedException ex) {
}
g.setColor(Color.RED); // setting colour or line to red.
g.drawLine((coordinatesArray[i][0]+65),(coordinatesArray[i][1]+50),(coordinatesArray[i+1] [0]+65),(coordinatesArray[i+1][1]+50));
}
}
else{
lblPath.setText(" Please clear, select a button to see the animation again"); //Animate button pressed twice without clear.
}
}
//This function calls the neighbour function with the selected row and column by the user.
static void startTour(){
neighbourRecursion(rowSelected,columnSelected);
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
I have an implementation of this program in C#. You can find it here:
http://github.com/danieltian/KnightBoard
It will only find the first solution though. I'm not saying to copy it, but you can take a look at it and see if it helps.

Categories

Resources