user3393046
user3393046

Reputation: 163

Java Force Variable to have specific values

I want to force one variable to have specific values. For example lets talk about CPU. Lets say that we have the following

public class CPU
{
   static String CPU_TYPE;
   static String CPU_SPEED;

   public static void main(String[] args) 
   {
      CPU_TYPE = "Don't allow this";
   }
}

I want for example the CPU_TYPE to be only AMD/Intel and CPU_SPEED To be only 3.0 or 4.0. I tried with enum but i am doing something wrong and its not working.

I don't want a simple solution with if statements since i have load of these variables and specific values.

Thank you

Upvotes: 3

Views: 967

Answers (3)

fastcodejava
fastcodejava

Reputation: 41117

​Java has a built solution for this kind of problems, it is called enum. There is no other way to restrict a variable do some pre-defined values without checking manually in your code.

Upvotes: 0

loafy
loafy

Reputation: 105

As @ChristopheD said, use Enums. Here's an example:

    package main;

public enum CPU_TYPE {

    TYPE1,
    TYPE2,
    TYPE3;

}

and then in your main class:

public CPU_TYPE cpuType = new CPU_TYPE();

public static void main(String[] args) {
//setting

cpuType = CPU_TYPE.TYPE1;

// getting
if(cpuType == CPU_TYPE.TYPE1) {
cpuType = CPU_TYPE.TYPE2;
}

}

Upvotes: 1

ChristopheD
ChristopheD

Reputation: 116237

Do use enums in this case, simply use Enum.valueOf() to parse your incoming string. It will throw an IllegalArgumentException when it can't convert it to one of the existing enum values.

Upvotes: 4

Related Questions