Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Force Variable to have specific values

Tags:

java

variables

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

like image 328
user3393046 Avatar asked Sep 11 '26 23:09

user3393046


2 Answers

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.

like image 184
ChristopheD Avatar answered Sep 13 '26 13:09

ChristopheD


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;
}

}
like image 38
loafy Avatar answered Sep 13 '26 14:09

loafy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!