Print String character one by one using threads - java

I am trying to print characters one by one on the animated banner, but i can't get the desired result.
I am getting the result with my code but not the one I am looking for. I am getting the banner and result of characters also.
But those characters are overlapping one another.
Please check below code
import java.awt.*;
import java.io.*;
//Banner class
class Banner extends Frame implements Runnable
{
boolean stop=false;
String str="Sreedhar Practice seassion";
//constructor
public Banner()
{
setLayout(null);
setBackground(Color.cyan);
setForeground(Color.blue);
}//end of constructor
//image paint settings methosd
public void paint(Graphics g)
{
Font f=new Font("Courier",Font.BOLD,40);
g.setFont(f);
for (int i=0;i<=str.length() ;i++ )
{
char ch=str.charAt(i);
String c=String.valueOf(ch);
g.drawString("\t"+c,10,100);
try
{
Thread.sleep(100);
}
catch (InterruptedException ie)
{
}
//char ch=str.carAt(0);
//str=str.substring(1,str.length());
//str=str+ch;
if (stop)
{
return;
}
}
}//image paint settings methosd end
//start of run method
public void run()
{
if (stop)
{
return;
}
}
}//end of run method
//main method starting
public static void main(String[] args)throws IOException
{
Banner b=new Banner();
b.setSize(400,400);
b.setTitle("Sreedhar Banner");
b.setVisible(true);
Thread t=new Thread(b);
t.start();
System.in.read();
b.stop=true;
}//end of main method
}//end of class Banner
This is my code, but am not getting the desired result what i want.

few bugs over here
first:
}//end of run method
one curly brace is redundant
second:
for (int i=0;i<=str.length() ;i++ )
should be:
for (int i=0; i < str.length(); i++)
third:
g.drawString("\t" + c, 10 + PRINT_FACTOR * i, 100);
where PRINT_FACTOR should be counted or choosed by expirement

It seems like in your call to g.drawString("\t"+c,10,100); the coordinates remain the same. Looks like it should somehow move along x axis depending on letter number. Try this:
int xLetterDifference = 6;
g.drawString("\t"+c, 10 + xLetterDifference * i ,100);
And alter value of xLetterDifference to adjust distance between letters

Related

How to get the alphanumerical token of a JLabel in a JLabel[] to pass to the method

I am trying to pass an element from jlb[] to the method new1(JLabel jl). Here is my code:
JLabel jlb[]=new JLabel[10];
for (int i = 0; i < 10; i++) {
jlb[i]=new JLabel("jlbl"+i);
}
new1(<variable name>);
new1 is a method. It has a JLabel parameter. I want call new1(). What should I place instead of <variable name> to call the method with variable from the array?
This is new1 method:
void new1(final JLabel jlbl){
new Thread(){
#Override
public void run() {
int y=10;
while (b>=150) {
for (int b=300; b > 150; b--) {
try {
Thread.sleep(10);
jlbl.setLocation(b, y);
} catch (Exception e) {
}
}
}
jLabel1.setLocation(b, y);
}
}.start();
}
As I understand you are looking for a alphanumerical token that would identify your variable like myJLabel or cuteLabelFromAnArray. Well, data stored in arrays can be accessed with special operator []. In your example this would be for example:
new1(jlb[<put index here>]);

libgdx textanimation(one letter by one)

I'm trying to make visual novel game but i'm stuck with text animation
I tried to make it on console application for example so help me with making it on libgdx.
here's my sample code
public class TestC {
private static String message = "help me with textanimation";
public static void main(String[] args) {
for (int i = 0; i < message.length(); i++) {
System.out.print(message.charAt(i));
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Thanks in advance
Why don't you try to make it work with LibGDX and then ask help? It goes basicaly the same except instead of letting the program sleep you have to count time passed.
final float letterSpawnTime = .2f;
float timer = 0;
String completeText = "The complete text."
String drawText = "";
int stringIndex = 0;
public void update(float delta) {
timer += delta;
if (timer >= letterSpawnTime) {
drawText = drawText + completeText.charAt(stringIndex);
stringIndex++;
timer -= letterSpawnTime;
}
font.draw(someFont, drawText, x, y, etc...);
}
Something like that (written out of my head). To be a bit more efficient initialize the StringBuilder in the constructor once and just keep appending a single character to it instead of creating a new StringBuilder instance each time the you need to append a letter.

Can not complete drawline on JButton [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I am making a simple tic tac toe game and ran into a problem at the last minute
I am trying to draw a line at the win location but on the final win location(index), the line gets hidden behind the JButton not entirly sure why it is doing this.
I know alot of people say do not use getGraphics(), and I am wondering if that is the source of my issues they say to override the paintComponent method but that is not working for me either
I have attached a pic of what the result is looking like and code snips of how I am trying to perform these actions
PS I am using a JFrame, if any more code is needed I will be glad to show it
if(win[i] == 264){ // if one of the the combinations equal 'X','X','X' which equals 264, then there is a winner
System.out.println("X is the winner!!!");
System.out.println("Game Over!");
number = i;
draw(); }// call draw method
private void draw(){ // drawing a line at winning location
Graphics2D g1 = (Graphics2D) GUI.getFrame().getGraphics(); // declaring graphics on our Jframe
Stroke stroke3 = new BasicStroke(12f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER); // make our strokes cap off round
if(number == 0){ // statements will determine the win location, so at win0, XXX,
g1.setStroke(stroke3); // we will add stroke to our line
g1.drawLine(0,104,500,104); // draw the line starting at the 0,104 and end it at coordinates 500,104
}
here is a more runnable code, it is alot though
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class tic implements Runnable {
final static int row = 3; // our rows
final static int col = 3; // our col
final static int sizeOfBoard = row * col;
// the size of our board is not going to change so we make it final
static JButton[] clickButton;
char[] templateOfBoard; // our board, TicTacToe field, static
char userTurn; // users turn , only one letter, tracks whether it is a X or O
int count; // keeps track of user moves
static JFrame frame; // our JFrame
int number;
public tic(JFrame frame) {
tic.frame = new JFrame("TicTacToe GAME");
clickButton = new JButton[9];
count = 0; // number of turns starts at 0;
number = 0;
setUserTurn('X'); // first turn will always be X
setTemplateOfBoard(new char[sizeOfBoard]); // size of the board we are going to make it
try{
for(int spaces=0; spaces<sizeOfBoard; spaces++){ // size of Board is in the GUI class
getTemplateOfBoard()[spaces] = ' '; // the board is being created, looping through all rows and col
//every index of the board not has a char value equal to a space
//determine if everything came out correctly
//should equal of a total of 9
// 3x3
}
System.out.println("Board template created"); // means the board now has all spaces
}
catch(Exception e){
System.out.println("Could not initalize the board to empty char");
e.printStackTrace();
}
}
public static void main(String[] args){
try{
SwingUtilities.invokeLater(new tic(frame)); // run
}
catch(Exception e){ // wanted to test to ensure that Runnable could be invoked
System.out.println("Could not excute Runnable application");
e.printStackTrace();
}
}
public void run() {
setup(); // going to run out setup method, what our game is made out of
}
public void setup() {
// setting up the Board
// board is composed of JButton
// and a 3x3 frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when the user closes the window JFrame will exit
//going to design the board now
//the dimensations of the board = sizeOfBoard
getFrame().setLayout(new GridLayout(row, col)); // this is the outline rows * col
// sizes out row * col based on what we define those numbers as
//i.e 3x3
getFrame().setBounds(0,0,500,500); // location at 0,0, size 500 x 500
Border border = new LineBorder(Color.DARK_GRAY, 2); // color of JButton border
System.out.println("Your board game is being created!");
try{
getFrame().setVisible(true); // shows the board,
// this is going to display everything to the screen
System.out.println("Board is now visable");
}
catch(Exception e){
System.out.println("Board was not displayed");
}
// 9 different buttons, for every index there will be a button
for(int i =0; i<sizeOfBoard;i++){ // going to fill the board with clickableButtons by looping through every index and placing a button there
final int move = i;
clickButton[i] = new JButton(); // at a certain index there is a new button
clickButton[i].setSize(250,250); // size of each button
clickButton[i].setBackground(Color.WHITE); // color of the JButton
getFrame().add(clickButton[i]); // we are going to add the actual the button at that index on the frame
clickButton[i].setFont(new Font("Arial", Font.BOLD, 70)); // size of the text
clickButton[i].setBorder(border); // adding border
clickButton[i].getModel().addChangeListener(new ChangeListener() { //going to overRide what happens when we rollover and press a Butotn
public void stateChanged(ChangeEvent e) {
ButtonModel button = (ButtonModel) e.getSource(); // manages the state of the button, i.e lets me control what happens to the button
if(clickButton[move] != null){ // if we do not include this argument
// the buttons are not made yet on the new game, meaning clickButton[i] = null
//so boolean(!button.isRollover()) will return true, since on the new game you can not have your mouse hovered over
// but when it returns true, it will return a null value, giving a null pointer exception
// so best thing to do, is to only run these cases below when the buttons are not null
if (button.isRollover()) { // when the mouse hovers over the index
clickButton[move].setBackground(Color.BLACK); // color will equal black
}
else if(!button.isRollover()){ // when the button is not hovered over
clickButton[move].setBackground(Color.WHITE); // color will be whte, just like our background
}
}
}
});
clickButton[i].addActionListener(new ActionListener() {
//our click events, going to override to let it know what we want to happen
//once we click on the button
public void actionPerformed(ActionEvent e) {
clickButton[move].setEnabled(false); //going to disable the button after it is clicked
//ORDER: button gets clicked first, then the test is added
mouseListener(e, move); // our mouseListenerEvent in game class
//
}
});
}
}
public static void playAgain() {
try{
System.out.println("NEW GAME");
SwingUtilities.invokeLater(new tic(frame)); // run the run(class) again
}
catch(Exception e){ // wanted to test to ensure that Runnable could be invoked
System.out.println("Could not excute Runnable application");
e.printStackTrace();
}
}
public static JFrame getFrame() {
return frame;
}
public tic userMove(int moveMade){
getTemplateOfBoard()[moveMade] = getUserTurn();
// index of the board, or in simpler terms, where the user
// inserts there turn i.e X or O, 0-8
//System.out.println(userMove);
//boolean statement to determine the turns
// So user X starts first
//if the turn is X, the nextTurn is now O,
if(getUserTurn() == 'X'){
setUserTurn('O');
}
else {
setUserTurn('X');
}
count++;
return this; // going to return the userTurn
// issue actually entering the userTurn is not giving right value, but using 'this' does
}
// for some odd reason the toString is causing some issues, keep getting #hash code
//saw online to override it like this
// will make the board out of emepty strings
// going to return a string representation of an object
public String toString(){
return new String(getTemplateOfBoard());
}
public void mouseListener(ActionEvent e, int moveMade){
// mouse click events
// what happens after a button is clicked
if(getTemplateOfBoard()[moveMade] == ' '){ // the user can only space a click, so an letter on the field if it is empty
((JButton)e.getSource()).setText(Character.toString(getUserTurn())); // when the button is clicked, we want an X placed there
if (getUserTurn() == 'X'){
UIManager.getDefaults().put("Button.disabledText",Color.RED); // when the but gets disabled the test will turn red
}
else{
UIManager.getDefaults().put("Button.disabledText",Color.BLUE);
}
//calling the method userTurn to determine who goes next
//problem is that is expects a String
//going to override the toString method
userMove(moveMade); // calling userMove in moveMade, moveMade is the index at which the user put either an X or a O
winner(); // we want to check each time to ensure there was/was not a winner
}
}
public tic winner() { // determines who is the winner
//list below defines all the possible win combinations
// the index of where a X or O can be place
// placed the locations to a int value
int win1 = templateOfBoard[0] + templateOfBoard[1] + templateOfBoard[2];
int win2 = templateOfBoard[3] + templateOfBoard[4] + templateOfBoard[5];
int win3 = templateOfBoard[6] + templateOfBoard[7] + templateOfBoard[8];
int win4 = templateOfBoard[0] + templateOfBoard[3] + templateOfBoard[6];
int win5 = templateOfBoard[1] + templateOfBoard[4] + templateOfBoard[7];
int win6 = templateOfBoard[2] + templateOfBoard[5] + templateOfBoard[8];
int win7 = templateOfBoard[0] + templateOfBoard[4] + templateOfBoard[8];
int win8 = templateOfBoard[2] + templateOfBoard[4] + templateOfBoard[6];
int[] win = new int[]{win1,win2,win3,win4,win5,win6,win7,win8};
// making a array to go through all the possibile wins
//possible total of wins is 8
for(int i = 0;i<win.length;i++){
// looping through the win possibilities
if(win[i] == 264){ // if one of the the combinations equal 'X','X','X' which equals 264, then there is a winner
System.out.println("X is the winner!!!");
System.out.println("Game Over!");
number = i;
draw(); // call draw method
return this; // if statement is true, it will return this(gameOver)
}
else if(win[i] == 237 ){ // if one of the the combinations equal 'O','O','O' which equals 234, then there is a winner
System.out.println("O is the winner!!!");
System.out.println("Game Over!");
number = i;
//draw(); // call draw method
return this;
}
if (count == 9) {
// if none of the statements above are true, it automatically comes done to here
//so if there is nine moves and no win, it is a draw
}
}
return this;
// going to return this method ;
}
private void draw(){ // drawing a line at winning location
Graphics2D g1 = (Graphics2D) getFrame().getGraphics(); // declaring graphics on our Jframe
Stroke stroke3 = new BasicStroke(12f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER); // make our strokes cap off round
if(number == 0){ // statements will determine the win location, so at win0, XXX,
g1.setStroke(stroke3); // we will add stroke to our line
g1.drawLine(0,104,500,104); // draw the line starting at the 0,104 and end it at coordinates 500,104
}
else if(number == 1){
g1.setStroke(stroke3);
g1.drawLine(0,257,500,257);
}
else if(number == 2){
g1.setStroke(stroke3);
g1.drawLine(0,411,500,411);
}
else if(number == 3){
g1.setStroke(stroke3);
g1.drawLine(88,0,88,500);
}
else if(number == 4){
g1.setStroke(stroke3);
g1.drawLine(250,0,250,500);
}
else if(number == 5){
g1.setStroke(stroke3);
g1.drawLine(411,0,411,500);
}
else if(number == 6){
g1.setStroke(stroke3);
g1.drawLine(-22,0,500,500);
}
else if(number == 7){
g1.setStroke(stroke3);
g1.drawLine(520,0,0,500);
}
}
// want to be able to access the private variables
//so we will make getter and setter methods for the ones that we need
public char getUserTurn() { // getter method for userTurn
return userTurn;
}
public void setUserTurn(char userTurn) { // setter method
this.userTurn = userTurn;
}
public char[] getTemplateOfBoard() { //getter method
return templateOfBoard;
}
public void setTemplateOfBoard(char[] templateOfBoard) { // setter method
this.templateOfBoard = templateOfBoard;
}
}
Painting over the top of components can be troublesome, you can't override the paintComponent method of the container which contains the components, because this paints in the background, you can't override the paint method of the container, as child components can be painted without the parent container been notified...
You could add a transparent component over the whole lot, but this just introduces more complexity, especially when a component already already exists ...
public class ConnectTheDots {
public static void main(String[] args) {
new ConnectTheDots();
}
public ConnectTheDots() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
PaintPane pp = new PaintPane();
JFrame frame = new JFrame("Test");
frame.setGlassPane(pp);
pp.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DotsPane(pp));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
private List<JButton[]> connections;
private JButton lastSelected;
public PaintPane() {
setOpaque(false);
connections = new ArrayList<>(25);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (lastSelected != null) {
g2d.setColor(Color.RED);
int x = lastSelected.getX() + ((lastSelected.getWidth() - 8) / 2);
int y = lastSelected.getY() + ((lastSelected.getHeight() - 8) / 2);
g2d.fillOval(x, y, 8, 8);
}
for (JButton[] group : connections) {
g2d.setColor(Color.BLUE);
Point startPoint = group[0].getLocation();
Point endPoint = group[1].getLocation();
startPoint.x += (group[0].getWidth() / 2);
startPoint.y += (group[1].getHeight()/ 2);
endPoint.x += (group[0].getWidth() / 2);
endPoint.y += (group[1].getHeight()/ 2);
g2d.draw(new Line2D.Float(startPoint, endPoint));
}
g2d.dispose();
}
protected void buttonClicked(JButton btn) {
if (lastSelected == null) {
lastSelected = btn;
} else {
connections.add(new JButton[]{lastSelected, btn});
lastSelected = null;
}
revalidate();
repaint();
}
}
public class DotsPane extends JPanel {
private PaintPane paintPane;
public DotsPane(final PaintPane pp) {
paintPane = pp;
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
paintPane.buttonClicked(btn);
}
};
setLayout(new GridLayout(6, 6));
for (int index = 0; index < 6 * 6; index++) {
JButton btn = new JButton(".");
add(btn);
btn.addActionListener(al);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Take a look at How to Use Root Panes for more details

Recursive bruteforce sudoku solver takes too long

I'm making a sudoku program, and I 'created' a recursive algorithm to solve a sudoku. The problem is, that sometimes it works perfectly and in an instant, sometimes it gets stuck and works 10s of seconds, and sometimes I just have to quit it.
Any ideas what might be causing this?
I left the code as it is, since I'm not sure how you answer the question(if you copy and try it out or just check the logic). If you want, I can just write out snippets.
Thanks!
import java.util.Random;
/**
* #Program Sudoku
*
* #date November 2013
* #hardware MacBook Pro 17", mid 2010, i7, 8GiB RAM
* #IDE eclipse SDK 4.3.1
* #purpose generates a valid 9x9 sudoku grid
*
*/
public class SudokuSolver //seems to werk !!
{
//create a validitychecker object(will be used as Sudoku.isValid();)
validityChecker Sudoku = new validityChecker();
//Create a 2D array where the full sudoku grid will be stored
private int[][] grid = new int[9][9];
//Creates a 2D array for the playable sudoku grid (with elements removed)
private int[][] playingGrid = new int[9][9];
private Random Ran = new Random();
/**
* #purpose use this construct if you wish to generate a new sudoku
* #param difficultyLevel removes amount of elements from sudoku using the equation elementToRemove=40+15*difficultyLevel
*/
SudokuSolver(int difficultyLevel)
{
//generate an empty grid
generateBaseGrid();
//populate it with a valid sudoku
solveSudoku(0,0);
//store this in a new from which elements shall be removed
for(int i = 0; i < grid.length; i++)
playingGrid[i] = grid[i].clone();
//calculate the amount of elements to be removed
int difficultyMultiplier = 15;
int baseDifficulty = 40;
int difficulty = baseDifficulty+difficultyLevel*difficultyMultiplier;
//and remove them
removeElements(difficulty);
}
/**
* #purpose use this constructor if you just want to use methods and solve
* #param the sudoku you wish to solve. values have to be within the range 1-9(inclusive), and -1 for unknown
* #note to get the solved sudoku use the fullGrid getter.
*/
SudokuSolver(int[][] pg)
{
//lets clone out the arrays - we don't want to just have references ...
for(int i = 0; i < pg.length; i++)
grid[i] = pg[i].clone();
for(int i = 0; i < grid.length; i++)
playingGrid[i] = grid[i].clone();
int coords[] = findOnes(grid);
solveSudoku(coords[0],coords[1]);
System.out.println(coords[0]+" "+coords[1]);
}
/**
* Use this if you only wish to use the internal methods
*/
SudokuSolver()
{}
//this method was implemented later, and I'm too lazy to change methods that use the procedure, but don't call the method. Maybe in next version
/**
* #purpose creates a copy of the passed array
* #param the array you wish to be copied
* #return returns a clone of the passed 2D array
*/
public int[][] cloneBoard(int[][] sudokuArray)
{
int[][] result = new int[9][9];
for(int i = 0; i < sudokuArray.length; i++)
result[i] = sudokuArray[i].clone();
return result;
}
/*
*#purpose fills the grid with -1s; This is for proper functionality during validation
*/
private void generateBaseGrid()
{
//iterates through all the values and stores -1s in it
for(int r=0;r<9;r++)
for(int c=0;c<9;c++)
grid[r][c] = -1;
//System.out.println("Base Grid Created");
}
/**
* #purpose checks if there are -1s in the grid, if so the grid is playable (its not a solution)
* #return true if its playable
*/
public boolean isGridPlayable()
{
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
if(grid[i][j]==-1)
return true;
return false;
}
/**
*
* #return the generated grid with all elements (for one without some elements use theGrid()) for generator
* #return the solved grid for solver
*/
public int[][] fullGrid()
{
return grid;
}
/**
* #purpose returns the playing grid
* #return the playable grid
*/
public int[][] theGrid()
{
return playingGrid;
}
/*
* #purpose removes "amnt" of elements from the playingGrid
* #return whether the current method was successful
* #param the amount of elements to be removed
*/
private boolean removeElements(int amnt)
{
if(amnt==0) //yay base case
return true;
for(int i=0; i<20;i++)
{
int r=Ran.nextInt(9);
int c=Ran.nextInt(9);
int element=playingGrid[r][c];
if(element!=-1)
{
playingGrid[r][c]=-1;
if(removeElements(amnt-1))
{return true;}
}else{playingGrid[r][c]=element;//removed as per suggestioni--;}
}
}
return false;
}
//--------------Debugging--------------------------------
public void printUserGrid(int[][] printie)
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
int x = printie[i][j];
String bexp = Integer.toString(x);
if(x==-1)
bexp="[]";
else bexp+=" ";
System.out.print(bexp+" ");
if(j==2||j==5)
System.out.print(" ");
}
System.out.println();
if(i==2||i==5)
System.out.println();
}
}
// //----------Main only for debugging-----------------------
public static void main(String[] args)
{
SudokuSolver Generator = new SudokuSolver(2);
int[][] generatedGrid = Generator.theGrid();
int[][] fullGrid = Generator.fullGrid();
Generator.printUserGrid(fullGrid);
// Generator.printUserGrid(generatedGrid);
System.out.println("\n\n");
SudokuSolver Solver = new SudokuSolver(generatedGrid);
Solver.printUserGrid(fullGrid);
}
}
EDIT:
One key thing I forgot to mention, the solveSudoku method, it rearranges some of the values. That means if I'm starting with a **3 it doesn't have a problem returning 312 (this is just an example for illustration). So I'd assume there is some serious logic error somewhere in there.
What you are attempting to solve is an Artificial Intelligence problem. Going by brute-force, or better called plain backtracking would actually mean you possibly have an exponential time complexity.
An exponential solution is expected to take long. In some cases where the order of guesswork matches the actual solution, your solver will return with a result faster.
So what you can do:
Read upon the AI technique called Constraint Satisfaction, and try to implement that.
Read upon more specific AI sudoku solving techniques, maybe some research paper if there is one and try and implement that.
This is my version of a SudokuSolver:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Sudoku
{
//This member has been intentionally left public, as the solved sudoku is
//obtained from here and user will find it much easier to handle this.
//The Sudoku input has to be given through this instance variable only.
//Moreover, many a times, Sudoku inputs as an edit-able 2D array is more
//comfortable than passing a whole 9x9 2D array as a constructor parameter.
public String SUDOKU[][]=new String[9][9];
//This variable records the nature of the Sudoku whether solvable or not
public boolean VALID=true;
public Sudoku()//this constructor can be used to create SUDOKU objects
{
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
SUDOKU[i][j]="";
}
private Sudoku(String SDK[][])//This is constructor kept private for program use
{
SUDOKU=SDK;
}
//This function checks if a certain digit is possible in a particular cell
private boolean isPossible(int n,int i,int j)
{
for(int a=i/3*3;a<i/3*3+3;a++)
for(int b=j/3*3;b<j/3*3+3;b++)
if(SUDOKU[a][b].length()==1 && n==Integer.parseInt(SUDOKU[a][b]))
return false;
for(int k=0;k<9;k++)
if(SUDOKU[i][k].length()==1 && n==Integer.parseInt(SUDOKU[i][k]) || SUDOKU[k][j].length()==1 && n==Integer.parseInt(SUDOKU[k][j]))
return false;
return true;
}
//The following function is compulsory as it is the only function to place appropriate
//possible digits in the cells of the Sudoku. The easiest Sudokus will get solved here.
private void fillPossibles()
{
boolean newdigit=false;
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
if(SUDOKU[i][j].length()!=1)
{
SUDOKU[i][j]="";
int count=0;
for(int k=1;k<10;k++)
if(isPossible(k,i,j))
{
SUDOKU[i][j]+=k;
count++;
}
if(count==1)
newdigit=true;
}
if(newdigit)
fillPossibles();
}
//This following function is optional, if the Sudoku is known to be genuine. As,
//in that case it only increases the solving speed!! But if the nature is not known,
//this function becomes necessary because the nature of the Sudoku is checked here.
//It returns true if any cell is filled with a digit and false for all other cases
private boolean deepFillPossibles(int ai,int aj,int bi,int bj,boolean first)
{
if(SUDOKU!=null)
for(char c='1';c<='9';c++)
{
int count=0,digit=0,possibility=0,i=0,j=0;
boolean valid=true;
for(int a=ai;a<bi;a++)
for(int b=aj;b<bj;b++)
{
if(SUDOKU[a][b].length()==0)
valid=false;
for(int k=0;k<SUDOKU[a][b].length();k++)
if(SUDOKU[a][b].charAt(k)==c)
{
if(SUDOKU[a][b].length()>1)
{
i=a; j=b; count++;
}
if(SUDOKU[a][b].length()==1)
digit++;
possibility++;
}
}
//the following code is executed only if solution() is called first time
if(first && (digit>1 || valid && possibility==0))
{
SUDOKU=null; return false;
}
if(count==1)
{
SUDOKU[i][j]=String.valueOf(c);
fillPossibles(); return true;
}
}
return false;
}
//This function is also optional if Sudoku is genuine. It only combines the solving
//power of fillPossibles() and deepFillPossibles() to reduce memory consumption
//in the next stages. In many cases the Sudoku gets solved at this stage itself.
private void solution(boolean first)
{
fillPossibles();
for(int i=0;i<9;i++)
if(deepFillPossibles(i,0,i+1,9,first) || deepFillPossibles(0,i,9,i+1,first) ||
deepFillPossibles(i/3*3,i%3*3,i/3*3+3,i%3*3+3,first))
i=-1;
}
//This function is the most challenging. No Sudoku can ever escape solution after
//passing this stage. It uses ECHO TREE logic implementing brute force to check all
//kinds of combinations until solution is obtained. It returns a null for no solution.
private void treeSolution(Tracker track)
{
if(SUDOKU==null)
{
track.TRACK_SUDOKU=null;
return;
}
solution(false);
//For a genuine sudoku the statement could have been replaced by "fillPossibles();"
//(Only it would make solving slower and increase memory consumption!)
//But it is risky if there is a doubt regarding the genuineness of the Sudoku
int a=-1,b=-1;
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
if(SUDOKU[i][j].length()>1 && a==-1)
{
a=i; b=j;
}
else if(SUDOKU[i][j].length()==0)
return;
if(a==-1)//checks if the Sudoku is solved or not setting necessary flags
{
track.TRACK_SOLUTION++;
for(int i=0;i<9;i++)
for(int j=0;j<9;track.TRACK_SUDOKU[i][j]=SUDOKU[i][j],j++);
return;
}
String temp[][]=new String[9][9];
for(int k=0;k<SUDOKU[a][b].length();k++)
{
for(int i=0;i<9;i++)
for(int j=0;j<9;temp[i][j]=SUDOKU[i][j],j++);
temp[a][b]=String.valueOf(SUDOKU[a][b].charAt(k));
new Sudoku(temp).treeSolution(track);
//The following condition stops the braching TREE if the Sudoku is solved by
//echoing back to the root, depending on the flags set on being solved
if(track.TRACK_SOLUTION==2 || track.TRACK_SUDOKU==null)
return;
}
return;
}
//This is the last function which has public access and can be called by the user.
//It sets the Sudoku as null if non-genuine and VALIDity as false if no unique solution
public void solve()
{
try
{
for(int i=0;i<9;SUDOKU[i][8]=SUDOKU[i][8],SUDOKU[8][i]=SUDOKU[8][i],i++);
}
catch(Exception e)
{
SUDOKU=null; VALID=false; return;
}
Tracker track=new Tracker();
solution(true);
treeSolution(track);
SUDOKU=track.TRACK_SOLUTION==0?null:track.TRACK_SUDOKU;
if(track.TRACK_SOLUTION!=1)
VALID=false;
}
}
//the following class is purposely designed to easily track the changes during solution,
//including the nature of the Sudoku and the solution of the Sudoku(if possible)
class Tracker
{
protected int TRACK_SOLUTION=0;
protected String TRACK_SUDOKU[][]=new String[9][9];
}
public class SudokuSolver extends JApplet implements KeyListener, MouseListener
{
private String SUDOKU[][]=new String[9][9];
private Sudoku SDK=new Sudoku();
private Image BOX[][]=new Image[9][9],SELECT_IMG;//BOX is an array of square images
private int SELECT_ROW=4,SELECT_COLUMN=4;//stores the position of the selection box
//this function is used to initialize the coloured square images and fonts
public void init()
{
resize(190,190);
setFont(new Font("Dialog",Font.BOLD,12));
addMouseListener(this);
addKeyListener(this);
Graphics g;
for(int i=0;i<9;i++)
for(int j=0;j<9;SUDOKU[i][j]="",j++)
{
BOX[i][j]=createImage(22,22);
g=BOX[i][j].getGraphics();
if((i/3+j/3)%2==0)
g.setColor(Color.yellow);
else
g.setColor(Color.green);
g.fillRect(0,0,21,21);
g.setColor(Color.black);
g.drawRect(0,0,21,21);
}
//the following statements colour the selection box red
SELECT_IMG=createImage(22,22);
g=SELECT_IMG.getGraphics();
g.setColor(Color.red);
g.fillRect(0,0,21,21);
g.setColor(Color.black);
g.drawRect(0,0,21,21);
}
public void mouseExited(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
//the following function handles the mouse click operations
public void mousePressed(MouseEvent e)
{
if(SDK.SUDOKU==null)
{
SDK.SUDOKU=new String[9][9];
for(int i=0;i<9;i++)
for(int j=0;j<9;SUDOKU[i][j]="",SDK.SUDOKU[i][j]="",j++);
SDK.VALID=true;
}
if(e.getY()<190 && e.getX()<190 && e.getY()%21!=0 && e.getX()%21!=0)
{
SELECT_ROW=e.getY()/21;
SELECT_COLUMN=e.getX()/21;
}
repaint();
}
public void keyReleased(KeyEvent e){}
//this function manages the operations associated with the various keys
public void keyPressed(KeyEvent e)
{
int code=e.getKeyCode();
if(code==KeyEvent.VK_DELETE || code==KeyEvent.VK_BACK_SPACE || code==KeyEvent.VK_SPACE)
{
SUDOKU[SELECT_ROW][SELECT_COLUMN]=""; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="";
}
switch(code)
{
case KeyEvent.VK_Y : if(SDK.SUDOKU!=null) SDK.VALID=true; break;
case KeyEvent.VK_UP : SELECT_ROW=(SELECT_ROW+8)%9; break;
case KeyEvent.VK_DOWN : SELECT_ROW=(SELECT_ROW+1)%9; break;
case KeyEvent.VK_LEFT : SELECT_COLUMN=(SELECT_COLUMN+8)%9; break;
case KeyEvent.VK_RIGHT : SELECT_COLUMN=(SELECT_COLUMN+1)%9; break;
case KeyEvent.VK_ENTER : SDK.solve(); break;
case KeyEvent.VK_N : if(SDK.SUDOKU!=null){ SDK.VALID=true; code=KeyEvent.VK_ESCAPE;}
case KeyEvent.VK_ESCAPE : if(SDK.SUDOKU==null)
{
SDK.SUDOKU=new String[9][9];
for(int i=0;i<9;i++)
for(int j=0;j<9;SUDOKU[i][j]="",SDK.SUDOKU[i][j]="",j++);
SDK.VALID=true;
}
else
for(int i=0;i<9;i++)
for(int j=0;j<9;SDK.SUDOKU[i][j]=SUDOKU[i][j],j++);
}
repaint();
}
//this function is for entering the numbers in the sudoku grid
public void keyTyped(KeyEvent e)
{
char code=e.getKeyChar();
if(Character.isDigit(code))
switch(code)
{
case '1': SUDOKU[SELECT_ROW][SELECT_COLUMN]="1"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="1"; break;
case '2': SUDOKU[SELECT_ROW][SELECT_COLUMN]="2"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="2"; break;
case '3': SUDOKU[SELECT_ROW][SELECT_COLUMN]="3"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="3"; break;
case '4': SUDOKU[SELECT_ROW][SELECT_COLUMN]="4"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="4"; break;
case '5': SUDOKU[SELECT_ROW][SELECT_COLUMN]="5"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="5"; break;
case '6': SUDOKU[SELECT_ROW][SELECT_COLUMN]="6"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="6"; break;
case '7': SUDOKU[SELECT_ROW][SELECT_COLUMN]="7"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="7"; break;
case '8': SUDOKU[SELECT_ROW][SELECT_COLUMN]="8"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="8"; break;
case '9': SUDOKU[SELECT_ROW][SELECT_COLUMN]="9"; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="9"; break;
default : SUDOKU[SELECT_ROW][SELECT_COLUMN]=""; SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN]="";
}
}
//the paint() function is designed to print the the sudoku grid and other messages
public void paint(Graphics g)
{
if(!SDK.VALID)
{
g.setColor(Color.white);
g.fillRect(1,1,188,188);
g.setColor(Color.black);
g.drawRect(0,0,189,189);
if(SDK.SUDOKU==null)
{
g.drawString("INVALID SUDOKU!!",45,80);
g.drawString("[PRESS ESCAPE TO RE-ENTER]",10,105);
}
else
{
g.drawString("INCOMPLETE SUDOKU!!",30,60);
g.drawString("Would you like to see a",30,90);
g.drawString("possible solution?",45,105);
g.drawString("Y / N",80,120);
}
}
else
{
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
{
g.drawImage(BOX[i][j],j*21,i*21,null);
g.drawString(SDK.SUDOKU[i][j],8+j*21,15+i*21);
}
g.drawImage(SELECT_IMG,SELECT_COLUMN*21,SELECT_ROW*21,null);
g.drawString(SDK.SUDOKU[SELECT_ROW][SELECT_COLUMN],8+SELECT_COLUMN*21,15+SELECT_ROW*21);
}
}
}
I have tried to use minimum brute force wherever possible

Error: Syntax error on token "(", ; expected

I have two issues on the same line the first is
Error: Syntax error on token "(", ; expected
Error: Syntax error on token ")", ; expected
I have no idea why its telling me that error, the noob mode is kicking in right now so I cant figure it out.
import java.awt.*;//for graphics class
import java .util.*;// for scanner class
//start of class
public class bouncingball {
// public static final int CENTER = 300;
//start of main
public static void main(String[] args) {
System.out.println("Project 2 modified by Jordan Spicer");
DrawingPanel panel = new DrawingPanel(400, 400);
Graphics g = panel.getGraphics();
Scanner input = new Scanner(System.in);
ball(g);
int test = 0;
String colors = "";
System.out.println(" this program prints out a bouncing ball");
System.out.println("please pick a color for the ball either red or blue ");
colors = input.nextLine();
if( (colors.compareTo("blue") == 0) ||colors.compareTo("red") == 0){
System.out.println("that wasnt a good color try again only put red or blue");
colors = input.nextLine();
System.out.println(colors);
}
else{
System.out.println(colors);
}
public static void ball (Graphics g){ <======= the errors are at this line here
g.setcolor(Color.RED);
g.drawcircle(50,50,50,50);
}
}
}
It seems you method inside another method. Move it to outside. Move following method declarationt to outside.
public static void ball (Graphics g){....}
A little rusty with java right now, but I don't think you can have the method
public static void ball (Graphics g)
inside of the main method. Try declaring it before the main method?

Categories

Resources