Search Results

Search found 13 results on 1 pages for 'hasnextint'.

Page 1/1 | 1 

  • Java: Infinite loop using Scanner in.hasNextInt()

    - by Tomek
    Hi everyone, I am using the following code: while (invalidInput) { // ask the user to specify a number to update the times by System.out.print("Specify an integer between 0 and 5: "); if (in.hasNextInt()) { // get the update value updateValue = in.nextInt(); // check to see if it was within range if (updateValue >= 0 && updateValue <= 5) { invalidInput = false; } else { System.out.println("You have not entered a number between 0 and 5. Try again."); } } else { System.out.println("You have entered an invalid input. Try again."); } } However, if I enter a 'w' it will tell me "You have entered invalid input. Try Again." and then it will go into an infinite loop showing the text "Specify an integer between 0 and 5: You have entered an invalid input. Try again." Why is this happening? Isn't the program supposed to wait for the user to input and press enter each time it reaches the statement: if (in.hasNextInt()) Thanks in advance, Tomek

    Read the article

  • Why is my code not printing anything to stdout?

    - by WM
    I'm trying to calculate the average of a student's marks: import java.util.Scanner; public class Average { public static void main(String[] args) { int mark; int countTotal = 0; // to count the number of entered marks int avg = 0; // to calculate the total average Scanner Scan = new Scanner(System.in); System.out.print("Enter your average: "); String Name = Scan.next(); while (Scan.hasNextInt()) { mark = Scan.nextInt(); countTotal++; avg = avg + ((mark - avg) / countTotal); } System.out.print( Name + " " + avg ); } }

    Read the article

  • I have applied a check for not allowing alphabets.But its not working.....

    - by bhavna raghuvanshi
    import java.util.Scanner; public class Main extends Hashmap{ public static void main(String[] args) { Hashmap hm = new Hashmap(); int x=0; Scanner input = new Scanner(System.in); do{ System.out.print("Enter any integer value between 1 to 12: "); x = input.nextInt(); }while(x<=0 || x>12); Scanner sc = new Scanner(System.in); //int number; do { while (!sc.hasNextInt()) { System.out.println("That's not a number!"); sc.next(); } x = sc.nextInt(); }while(x>=0); String month = hm.getEntry(x); System.out.println(month); } } here I need to restrict user from entering an alphabet.But its not working. pls help...

    Read the article

  • im writing this code so the user would enter his/her name and followed by his/her marks to get the a

    - by WM
    What if the user wanted to enter his/her grades in the following way: Will 23, 34, 45, 45 how would i get rid of the commas public class StudentAverage { public static void main(String[] args) { int markSum = 0; double average = 0; Scanner input1 = new Scanner(System.in); System.out.print("Enter student record : "); String name = input1.next(); Scanner input2 = new Scanner(input1.nextLine()); int countTotal = 0; while (input2.hasNextInt()) { countTotal++; markSum += input2.nextInt(); } average = markSum / countTotal; // to calculate the total average System.out.print( name + " " + average ); } }

    Read the article

  • How do i change this method to get strings instead of ints

    - by David
    here is the original code: public static int getInt () { Scanner in = new Scanner (System.in) ; if (in.hasNextInt()) { int a = in.nextInt() ; return a ; } else { System.out.println ("try again:") ; return getInt () ; } } This checks and sees if the input it receives is an int. If it is then it returns the int, if not it tells you to try again and re-runs. This is what i tried to do to change it: public static String getIns () { Scanner in = new Scanner (System.in) ; if (in.hasNextString()) { String a = in.nextString() ; return a ; } else { System.out.println ("try again:") ; return getIns () ; } } This doesn't work though. I looked through the documentation for the scanner class and i think the problem is that there is no such method as in.hasNextString or in.nextString What methods from the scanner class can i use to do what i intend these to do?

    Read the article

  • FileNotFoundException Java

    - by Troels Hansen
    Hi, I'm trying to make a simple highscore system for a minesweeper game. However i keep getting a file not found exception, and i've tried to use the full path for the file aswell. package minesweeper; import java.io.*; import java.util.*; public class Highscore{ public static void submitHighscore(String difficulty) throws IOException{ int easy = 99999; int normal = 99999; int hard = 99999; //int newScore = (int) MinesweeperView.getTime(); int newScore = 10; File f = new File("Highscores.dat"); if (!f.exists()){ f.createNewFile(); } Scanner input = new Scanner(f); PrintStream output = new PrintStream(f); if (input.hasNextInt()){ easy = input.nextInt(); normal = input.nextInt(); hard = input.nextInt(); } output.flush(); if(difficulty.equals("easy")){ if (easy > newScore){ easy = newScore; } }else if (difficulty.equals("normal")){ if (normal > newScore){ normal = newScore; } }else if (difficulty.equals("hard")){ if (hard > newScore){ hard = newScore; } } output.println(easy); output.println(normal); output.println(hard); } //temporary main method used for debugging public static void main(String[] args) throws IOException { submitHighscore("easy"); } }

    Read the article

  • Line End Problem Reading with Scanner Class in Java

    - by dikbas
    I am not an experienced Java programmer and i'm trying to write some text to a file and then read it with Scanner. I know there are lots of ways of doing this, but i want to write records to file with delimiters, then read the pieces. The problem is so small. When I look the output some printing isn't seen(shown in below). I mean the bold line in the Output that is only written "Scanner". I would be appreciated if anyone can answer why "String: " isn't seen there. (Please answer just what i ask) I couldn't understand if it is a simple printing problem or a line end problem with "\r\n". Here is the code and output: import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Tmp { public static void main(String args[]) throws IOException { int i; boolean b; String str; FileWriter fout = new FileWriter("test.txt"); fout.write("Testing|10|true|two|false\r\n"); fout.write("Scanner|12|one|true|"); fout.close(); FileReader fin = new FileReader("Test.txt"); Scanner src = new Scanner(fin).useDelimiter("[|\\*]"); while (src.hasNext()) { if (src.hasNextInt()) { i = src.nextInt(); System.out.println("int: " + i); } else if (src.hasNextBoolean()) { b = src.nextBoolean(); System.out.println("boolean: " + b); } else { str = src.next(); System.out.println("String: " + str); } } fin.close(); } } Here is the output: String: Testing int: 10 boolean: true String: two String: false Scanner int: 12 String: one boolean: true

    Read the article

  • Import? Initialize? what do to?

    - by Jeremy B
    I'm working on homework and I'm close but I am having an issue. I just learned how to work with packages in eclipse so I have a class that is importing another class from a package (I think I said that right) The main prompts the user to enter an integer between -100 and 100 and I am having an issue with validating it. I know the issue is where I'm importing I'm just unsure the direction I need to go to fix it. This is a section of my main code. (my issue starts with the last couple lines if you want to skip ahead) import myUtils.util.Console; public class ConsoleTestApp { public static void main(String args[]) { // create the Console object Console c = new Console(); // display a welcome message c.println("Welcome to the Console Tester application"); c.println(); // int c.println("Int Test"); int i = c.getIntWithinRange("Enter an integer between -100 and 100: ", -101, 101); c.println(); I have a class called Console that is located in another package that I believe I have properly imported. here is the code I am stuck on in my console class. public int getIntWithinRange(String prompt, int min, int max) { int i = 0; boolean isValid = false; while (isValid == false) { System.out.println(prompt); if (sc.hasNextInt()) { //if user chooses menu option less than 1 the program will print an error message i = sc.nextInt(); if (i < min) { System.out.println("Error! Please enter an int greater than -100"); } else if (i > max) { System.out.println("Error! Please enter an int less than 100"); } else isValid = true; } else System.out.println("Error! Invalid number value"); sc.nextLine(); } // return the int return i; } when I run this I keep getting my last print which is an invalid number value. am I not importing the code from the main method in the other console properly?

    Read the article

  • Printing Two Dimensional Array in Special Format

    - by user554313
    Hello everybody, I am working in a small task that allow the user to enter the regions of any country and store them in one array. Also, each time he enters a region, the system will ask him to enter the neighbours of that entered region and store these neighbours. I did the whole task but I have a small problem: I could not be able to print each region and its neighbours like the following format: Region A: neighbour1 neighbour2 Region B: neighbour1 neighbour2 For example, let us take USA map. I want to print the result as following: Washington D.C: Texas, Florida, Oregon and so on. My code is: import java.io.*; import java.util.Arrays; import java.util.Scanner; public class Test7{public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.print("Please enter the number of regions: "); int REGION_COUNT = kb.nextInt(); String[] regionNames = new String[REGION_COUNT]; String[][] regions = new String[REGION_COUNT][2]; for (int r = 0; r < regions.length; r++) { System.out.print("Please enter the name of region #" + (r + 1) + ": "); regionNames[r] = kb.next(); System.out .print("How many neighbors for region #" + (r + 1) + ": "); if (kb.hasNextInt()) { int size = kb.nextInt(); regions[r] = new String[size]; for (int n = 0; n < size; n++) { System.out.print("Please enter the neighbour #" + (n) + ": "); regions[r][n] = kb.next(); } } else System.exit(0); } for (int i = 0; i < REGION_COUNT; i++) { System.out.print(regionNames[i] +": "); for (int k = 0; k < 2; k++) { System.out.print(regions[i][k]+", "); } System.out.println(); } } }

    Read the article

  • Ladder-like word game in Java

    - by sasquatch90
    I've found this question http://stackoverflow.com/questions/2844190/choosing-design-method-for-ladder-like-word-game and I would also like to do this kind of program. I've written some code but already have two issues. Here's what I already have : GRID : public class Grid { public Grid(){} public Grid( Element e ){} } ELEMENT : public class Element { final int INVISIBLE = 0; final int EMPTY = 1; final int FIRST_LETTER = 2; final int OTHER_LETTER = 3; private int state; private String letter; public Element(){} //empty block public Element(int state){ this("", 0); } //filled block public Element(String s, int state){ this.state = state; this.letter = s; } public static void changeState(int s){ } public int getState(){ return state; } public boolean equalLength(){ return true; } public boolean equalValue(){ return true; } @Override public String toString(){ return "["+letter+"]"; } } MAIN: import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Height: "); while (!sc.hasNextInt()) { System.out.println("int, please!"); sc.next(); } final int height = sc.nextInt(); Grid[] game = new Grid[height]; for(int i = 1; i <= height; i++) { String s; do { System.out.println("Length " + i + ", please!"); s = sc.next(); } while (s.length() != i); Element[] line = new Element[s.length()+1]; Element single = null; String[] temp = null; //issue here temp = s.split(""); System.out.println("s.length: "+s.length()); System.out.println("temp.length: "+temp.length); // for(String str : temp){ System.out.println("str:"+str); } for (int k = 0 ; k < temp.length ; k++) { if( k == 0 ){ single = new Element(temp[k], 2); System.out.println("single1: "+single); } else{ single = new Element(temp[k], 3); System.out.println("single2: "+single); } line[k] = single; } for (Element l : line) { System.out.println("line:"+l); } //issue here game[i] = line; } // for (Grid g : game) { System.out.println(g); } } } And sample output for debug : Height: 3 Length 1, please! A s.length: 1 temp.length: 2 str: str:A single1: [] single2: [A] line:[] line:[A] Here's what I think it should work like. I grab a word from user. Next create Grid element for whole game. Then for each line I create Element[] array called line. I split the given text and here's the first problem. Why string.split() adds a whitespace ? You can see clearly in output that it is added for no reason. How can I get rid of it (now I had to add +1 to the length of line just to run the code). Continuing I'm throwing the splitted text into temporary String array and next from each letter I create Element object and throw it to line array. Apart of this empty space output looks fine. But next problem is with Grid. I've created constructor taking Element as an argument, but still I can't throw line as Grid[] elements because of 'incompatible types'. How can I fix that ? Am I even doing it right ? Maybe I should get rid of line as Element[] and just create Grid[][] ?

    Read the article

  • Ladder word-like game GUI problems

    - by sasquatch90
    Ok so I've written my own version of game which should look like this : http://img199.imageshack.us/img199/6859/lab9a.jpg but mine looks like that : http://img444.imageshack.us/img444/7671/98921674.jpg How can I fix this ? Is there a way to do the layout completely differently ? Here's the code : Main.java : import java.util.Scanner; import javax.swing.*; import java.awt.*; public class Main { public static void main(String[] args){ final JFrame f = new JFrame("Ladder Game"); Scanner sc = new Scanner(System.in); System.out.println("Creating game data..."); System.out.println("Height: "); while (!sc.hasNextInt()) { System.out.println("int, please!"); sc.next(); } final int height = sc.nextInt(); Grid[]game = new Grid[height]; for(int L = 0; L < height; L++){ Grid row = null; int i = L+1; String s; do { System.out.println("Length "+i+", please!"); s = sc.next(); } while (s.length() != i); Element[] line = new Element[s.length()]; Element single = null; String[] temp = null; String[] temp2 = new String[s.length()]; temp = s.split(""); for( int j = temp2.length; j>0; j--){ temp2[j-1] = temp[j]; } for (int k = 0 ; k < temp2.length ; k++) { if( k == 0 ){ single = new Element(temp2[k], 2); } else{ single = new Element(temp2[k], 1); } line[k] = single; } row = new Grid(line); game[L] = row; } //############################################ //THE GAME STARTS HERE //############################################ JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.setBackground(Color.ORANGE); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); for(int i = 0; i < game.length; i++){ panel.add(game[i].create()); } f.setContentPane(panel); f.pack(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); boolean end = false; boolean word = false; String tekst; while( !end ){ while( !word ){ tekst = JOptionPane.showInputDialog("Input word: "); for(int i = 0; i< game.length; i++){ if(game[i].equalLength(tekst)){ if(game[i].equalValue(tekst)){ word = true; for(int j = 0; j< game.length; j++){ game[i].repaint(); } } } } } word = false; for(int i = 0; i < game.length; i++){ if(game[i].solved()){ end = true; } else { end = false; } } } } } Grid.java import javax.swing.*; import java.awt.*; public class Grid extends JPanel{ private Element[]e; private Grid[]g; public Grid(){} public Grid( Element[]elements ){ e = new Element[elements.length]; for(int i=0; i< e.length; i++){ e[i] = elements[i]; } } public Grid(Grid[]grid){ g = new Grid[grid.length]; for(int i=0; i<g.length; i++){ g[i] = grid[i]; } Dimension d = new Dimension(600, 600); setMinimumSize(d); setPreferredSize(new Dimension(d)); setMaximumSize(d); } public JPanel create(){ JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); for(int j = 0; j < e.length; j++){ panel.add(e[j].paint()); } return panel; } @Override public void repaint(){ } public boolean equalLength(String s){ int len = s.length(); boolean equal = false; for(int j = 0; j < e.length; j++){ if(e.length == len){ equal = true; } } return equal; } public boolean equalValue(String s){ int len = s.length(); boolean equal = false; String[] temp = null; String[] temp2 = new String[len]; temp = s.split(""); for( int j = len; j>0; j--){ temp2[j-1] = temp[j]; } for(int j = 0; j < e.length; j++){ if( e[j].letter().equals(temp2[j]) ){ equal = true; } else { equal = false; } } if(equal){ for(int i = 0; i < e.length; i++){ e[i].changeState(3); } } return equal; } public boolean solved(){ boolean solved = false; for(int j = 0; j < e.length; j++){ if(e[j].getState() == 3){ solved = true; } else { solved = false; } } return solved; } @Override public String toString(){ return ""; } } Element.java import javax.swing.*; import java.awt.*; public class Element { final int INVISIBLE = 0; final int EMPTY = 1; final int FIRST_LETTER = 2; final int OTHER_LETTER = 3; private int state; private String letter; public Element(){ } //empty block public Element(int state){ this("", 0); } //filled block public Element(String s, int state){ this.state = state; this.letter = s; } public JButton paint(){ JButton button = null; if( state == EMPTY ){ button = new JButton(""); button.setBackground(Color.WHITE); } else if ( state == FIRST_LETTER ){ button = new JButton(letter); button.setBackground(Color.red); } else { button = new JButton(letter); button.setBackground(Color.yellow); } button.setSize(20,20); return button; } public void changeState(int s){ state = s; } public String letter(){ return letter; } public int getState(){ return state; } @Override public String toString(){ return "["+letter+"]"; } }

    Read the article

  • StringIndexOutOfBoundsException error in main method

    - by Ro Siv
    I am obtaining a StringIndexOutOfBoundsError when running my main method. Here is the output of my program in the command line. "Please enter the shift, 1 for day, 2 for night" 1 "you entered a number for the shift" "Please enter the hourly pay Rate" 2 "you entered a number for the pay Rate" "Please enter the employees name" brenda "cat6b" "your value you entered is correct 0-9 or a - z" "Please enter the employee number" 100e "cat41" "your value you entered is correct 0-9 or a - z" "Please enter current date in XXYYZZZZ format, X is day, Y is month, Z is year" 10203933 "cat81 " "your value you entered is correct 0-9 or a - z" 90 1 valye of array is 1 81 0 value of array is 0 82 2 value of array is 2 83 0 value of array is 0 84 3 value of array is 3 85 9 value of array is 9 86 3 value of array is 3 87 3 value of array is 3 "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8 at java.lang.String.charAt(String.java:658) at ProductionWorker<init>(ProductionWorker.java:66) at labBookFiftyFour.main(labBookFiftyFour.java:58)" "Press any key to continue . . ." Ignore the cat parts in the code, i was using a println statement to test the code. Ignore the value of array output as well, as i wanted to use an array in the program later on. Here is my main method. import java.math.*; import java.text.DecimalFormat; import java.io.*; import java.util.*; public class labBookFiftyFour { public static void main(String[] args) { Scanner myInput = new Scanner(System.in); int shift = -1; double pRate = -2; String name = " "; String number = " "; String date = " "; while(shift < 0 || pRate < 0 ) { System.out.println("Please enter the shift, 1 for day, 2 for night"); if(myInput.hasNextInt()){ System.out.println("you entered a number for the shift"); shift = myInput.nextInt(); } System.out.println("Please enter the hourly pay Rate"); if(myInput.hasNextDouble()){ System.out.println("you entered a number for the pay Rate"); pRate = myInput.nextDouble(); } else if (myInput.hasNext()) { System.out.println("Please enter a proper value"); myInput.next(); } else { System.err.println("No more input"); System.exit(1); } } myInput.nextLine(); //consume newLine System.out.println("Please enter the employees name"); name = myInput.nextLine(); //use your isValid method if(isValid(name)) { System.out.println("your value you entered is correct 0-9 or a - z "); } System.out.println("Please enter the employee number"); number = myInput.nextLine(); //use your isValid method if(isValid(number)) { System.out.println("your value you entered is correct 0-9 or a - z "); } System.out.println("Please enter current date in XXYYZZZZ format, X is day, Y is month, Z is year"); date = myInput.nextLine(); //use your isValid method if(isValid(date)) { System.out.println("your value you entered is correct 0-9 or a - z "); } ProductionWorker myWorker = new ProductionWorker(shift, pRate, name, number, date); //int day and night , double payRate System.out.println("THis is the shift " + myWorker.getShift() + " This is the pay Rate " + myWorker.getPRate() + " " + myWorker.getName() + " " + myWorker.getNumber() + " " + myWorker.getDate()); } //Made this method for testing String input for 0-9 or a - z values , put AFTER main method, but before end of class public static boolean isValid(String stringName) //This method has to be static, for some reason? { System.out.println("cat" + stringName.length() + stringName.charAt(0)); boolean flag = true; int index = 0; while(index < stringName.length()) { if(Character.isLetterOrDigit(stringName.charAt(index))) { flag = true; } else { flag = false; } ++index; } return flag; } } Here is my employeeOne. java Superclass public class employeeOne { private String name; private String number; private String date; public employeeOne(String name, String number, String date) { this.name = name; this.number = number; this.date = date; } public String getName() { return name; } public String getNumber() { return number; } public String getDate() { return date; } } Here is my ProductionWorker.java subclass, which extends employeeOne public class ProductionWorker extends employeeOne { private int shift; //shift represents day or night, day = 1, night = 2 private double pRate; //hourly pay rate public ProductionWorker(int shift, double pRate, String name, String number, String date) { super(name, number, date); this.shift = shift; if(this.shift >= 3 || this.shift <= 0) { System.out.println("You entered an out of bounds shift date, enter 1 for day or 2 for night, else shift will be day"); this.shift = 1; } this.pRate = pRate; boolean goodSoFar = true; int indexNum = 0; int indexDate = 0; if(name.length() <= 10 && number.length() <= 4 && date.length() < 9 ) { goodSoFar = true; } else { goodSoFar = false; } while(goodSoFar && indexNum < 3) //XXXL XXX digits 1-9, L is a letter A -M { if(Character.isDigit(number.charAt(indexNum))) { goodSoFar = true; } else { goodSoFar = false; } ++indexNum; } while(goodSoFar && indexNum < 4) { if(Character.isLetter(number.charAt(indexNum))) { goodSoFar = true; } else if(Character.isDigit(number.charAt(indexNum))) { goodSoFar = false; } else if(Character.isDigit(number.charAt(indexNum)) == false && Character.isLetter(number.charAt(indexNum)) == false) { goodSoFar = false; } ++indexNum; } int[] dateValues = new int[date.length()]; while(goodSoFar && indexDate <= date.length()) //XXYYZZZZ { System.out.println("" + date.length() + indexDate + " " + date.charAt(indexDate)); if(Character.isDigit(date.charAt(indexDate))) { dateValues[indexDate] = Character.getNumericValue(date.charAt(indexDate)); System.out.println("value of array is " + dateValues[indexDate]); ++indexDate; } else { goodSoFar = false; } } if(goodSoFar) { System.out.println("your input is good so far"); } else { System.out.println("your input is wrong for name or number or date"); } } public int getShift() { return shift; } public double getPRate() { return pRate; } }

    Read the article

  • Using repaint() method.

    - by owca
    I'm still struggling to create this game : http://stackoverflow.com/questions/2844190/choosing-design-method-for-ladder-like-word-game .I've got it almost working but there is a problem though. When I'm inserting a word and it's correct, the whole window should reload, and JButtons containing letters should be repainted with different style. But somehow repaint() method for the game panel (in Main method) doesn't affect it at all. What am I doing wrong ? Here's my code: Main: import java.util.Scanner; import javax.swing.*; import java.awt.*; public class Main { public static void main(String[] args){ final JFrame f = new JFrame("Ladder Game"); Scanner sc = new Scanner(System.in); System.out.println("Creating game data..."); System.out.println("Height: "); //setting height of the grid while (!sc.hasNextInt()) { System.out.println("int, please!"); sc.next(); } final int height = sc.nextInt(); /* * I'm creating Grid[]game. Each row of game contains Grid of Element[]line. * Each row of line contains Elements, which are single letters in the game. */ Grid[]game = new Grid[height]; for(int L = 0; L < height; L++){ Grid row = null; int i = L+1; String s; do { System.out.println("Length "+i+", please!"); s = sc.next(); } while (s.length() != i); Element[] line = new Element[s.length()]; Element single = null; String[] temp = null; String[] temp2 = new String[s.length()]; temp = s.split(""); for( int j = temp2.length; j>0; j--){ temp2[j-1] = temp[j]; } for (int k = 0 ; k < temp2.length ; k++) { if( k == 0 ){ single = new Element(temp2[k], 2); } else{ single = new Element(temp2[k], 1); } line[k] = single; } row = new Grid(line); game[L] = row; } //############################################ //THE GAME STARTS HERE //############################################ //create new game panel with box layout JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setBackground(Color.ORANGE); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); //for each row of the game array add panel containing letters Single panel //is drawn with Grid's paint() method and then returned here to be added for(int i = 0; i < game.length; i++){ panel.add(game[i].paint()); } f.setContentPane(panel); f.pack(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); boolean end = false; boolean word = false; String text; /* * Game continues until solved() returns true. First check if given word matches the length, * and then the value of any row. If yes - change state of each letter from EMPTY * to OTHER_LETTER. Then repaint the window. */ while( !end ){ while( !word ){ text = JOptionPane.showInputDialog("Input word: "); for(int i = 1; i< game.length; i++){ if(game[i].equalLength(text)){ if(game[i].equalValue(text)){ game[i].changeState(3); f.repaint(); //simple debug - I'm checking if letter, and //state values for each Element are proper for(int k=0; k<=i; k++){ System.out.print(game[k].e[k].letter()); } System.out.println(); for(int k=0; k<=i; k++){ System.out.print(game[k].e[k].getState()); } System.out.println(); //set word to true and ask for another word word = true; } } } } word = false; //check if the game has ended for(int i = 0; i < game.length; i++){ if(game[i].solved()){ end = true; } else { end = false; } } } } } Element: import javax.swing.*; import java.awt.*; public class Element { final int INVISIBLE = 0; final int EMPTY = 1; final int FIRST_LETTER = 2; final int OTHER_LETTER = 3; private int state; private String letter; public Element(){ } //empty block public Element(int state){ this("", 0); } //filled block public Element(String s, int state){ this.state = state; this.letter = s; } public JButton paint(){ JButton button = null; if( state == EMPTY ){ button = new JButton(" "); button.setBackground(Color.WHITE); } else if ( state == FIRST_LETTER ){ button = new JButton(letter); button.setBackground(Color.red); } else { button = new JButton(letter); button.setBackground(Color.yellow); } return button; } public void changeState(int s){ state = s; } public void setLetter(String s){ letter = s; } public String letter(){ return letter; } public int getState(){ return state; } } Grid: import javax.swing.*; import java.awt.*; public class Grid extends JPanel{ public Element[]e; private Grid[]g; public Grid(){} public Grid( Element[]elements ){ e = new Element[elements.length]; for(int i=0; i< e.length; i++){ e[i] = elements[i]; } } public Grid(Grid[]grid){ g = new Grid[grid.length]; for(int i=0; i<g.length; i++){ g[i] = grid[i]; } Dimension d = new Dimension(600, 600); setMinimumSize(d); setPreferredSize(new Dimension(d)); setMaximumSize(d); } //for Each element in line - change state to i public void changeState(int i){ for(int j=0; j< e.length; j++){ e[j].changeState(3); } } //create panel which will be single row of the game. Add elements to the panel. // return JPanel to be added to grid. public JPanel paint(){ JPanel panel = new JPanel(); panel.setLayout(new GridLayout(1, e.length)); panel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); for(int j = 0; j < e.length; j++){ panel.add(e[j].paint()); } return panel; } //check if the length of given string is equal to length of row public boolean equalLength(String s){ int len = s.length(); boolean equal = false; for(int j = 0; j < e.length; j++){ if(e.length == len){ equal = true; } } return equal; } //check if the value of given string is equal to values of elements in row public boolean equalValue(String s){ int len = s.length(); boolean equal = false; String[] temp = null; String[] temp2 = new String[len]; temp = s.split(""); for( int j = len; j>0; j--){ temp2[j-1] = temp[j]; } for(int j = 0; j < e.length; j++){ if( e[j].letter().equals(temp2[j]) ){ equal = true; } else { equal = false; } } if(equal){ for(int i = 0; i < e.length; i++){ e[i].changeState(3); } } return equal; } //check if the game has finished public boolean solved(){ boolean solved = false; for(int j = 0; j < e.length; j++){ if(e[j].getState() == 3){ solved = true; } else { solved = false; } } return solved; } }

    Read the article

1