-1

What is wrong with my code? I'm trying request prompt a user to enter a number if it is not between 1 and 6 or a number it should say invalid and prompt another try. The user may only have 3 tries.

import java.util.Scanner;

public class Game {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] numbers = new int[6];

    System.out.println("Enter a number on a die from 1-6:");
    String dieinput = input.next();
    int invalidcount = 0;
    System.out.println("Your number is: " + dieinput);



    do{
    try
    {
      // the String to int conversion
      int dienum = Integer.parseInt(dieinput.trim());
      int dienumOE = 0;
      int count=0;

      //test number input
      if ((dienum >= 1) && (dienum<= 6))
            System.out.println("number is " + dienum + oddoreven(dienum));
      else
            System.out.println("Invalid number, please enter a number 1-6");
            count++;
            System.out.println("Count" + count);
      }
    catch (NumberFormatException nfe){
        System.out.println("Invalid number, please enter a number 1-6");
        System.out.println("Count" + count);
        }
    while (count <= 3 && count >=0);
    }
    }





// Check if odd or even
public static String oddoreven(int num) {
    String result;

    if (num % 2 == 0)
        result = "even";
    else
        result = "odd";
    return result;
}
}
Kushan
  • 10,657
  • 4
  • 37
  • 41

1 Answers1

2

Your problem is "wrong" scoping: You can't use a variable within the catch block that is declared within the scope of the try block!

In other words; you need:

int counter = 0;
try { ...
} catch (... 

if you want to use counter within both try and catch!

The "rule" is very simple: a variable is only visible up to that } that closes the "block" it is in.

That prevents you from actually compiling your code!

So, the real lesson here is more like: do not write 100 lines of code to then run the compiler. Only write as few lines as possible - every time when you think: this is "enough" to compile .. then compile. And then fix the errors reported to you. The java compiler is really good at giving you specific messages that tell you what you did wrong; but the more messy code you put up, the harder that gets!

And for the record: SO is not a "remote" compiler service that you should use to get your messy code to compile!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • *And for the record: SO is not a "remote" compiler service that you should use to get your messy code to compile!* which is funny, because you did just that. There are duplicates of those questions, there is no need to answer again. – Tunaki Oct 22 '16 at 13:00