Is there a better way to compare multiple Strings?

I’m trying to write a code that will only allow you to enter certain numbers. I found a way but I feel like there should be a more efficient way.

String text="";
String saved="";
String degree90="90";
String degree89="89";
void setup(){
  size(700,700);
  }
void draw(){
  background(200);
  fill(180);
  rect(325,268,50,40);
  textAlign(CENTER);
  textSize(35);
  fill(0,0,255);
  text("\nHit enter to save",350,200);
  text(text,350,300);
  text(saved,350,400);
}
void keyPressed(){
  if (key==BACKSPACE) {
    if (text.length()>0) {
      text=text.substring(0, text.length()-1);
    }
  }
  if (key == '\n'){
    if((text.equals(degree90))||(text.equals(degree89))){
      saved=text;
      text="";
    }
  }else{
    text=text+key;
  }
}

I feel like “if((text.equals(degree90))||(text.equals(degree89))” can be improved since I want to do from degree0 to degree90. Any help would be greatly appreciated.

1 Like

Hi @chaotic!

Welcome to the forum!
Is there any specific sequence of numbers?
You could try regex to get the numbers or depending on the input you could try to convert the string into an integer to get the number and check if it is either inside an interval or present in an array of expected values. Examples on how to convert the string into integer are below:

String a = "90";
int b = Integer.parseInt(a);
println("B=" + b);

String c = "degree90";
int d = Integer.parseInt(c.replaceAll("[\\D]", ""));
println("D=" + d);

Hope it helps!
Best regards

2 Likes

What I’m trying to do is allow the user to input a value between 0 and 90. If they do it will save it.

I figure it out!

String text="";
String saved="";
int degree=0;

void setup(){
  size(700,700);  
}

void draw(){
  degree=int(0+text);
  background(200);
  fill(180);
  rect(325,268,50,40);
  textAlign(CENTER);
  textSize(35);
  fill(0,0,255);
  text("\nHit enter to save",350,200);
  text(text,350,300);
  text(saved,350,400); 
}

void keyPressed(){
  if (key==BACKSPACE) {
    if (text.length()>0) {
      text=text.substring(0, text.length()-1);
    }
  }
  if (key == '\n'){
    if((text.length()<=2)&&(degree>=0)&&(degree<=90)){
      saved=text;
      text="";
    }
  }else{
    text=text+key;
  }
  if (key==BACKSPACE) {
    if (text.length()>0) {
      text=text.substring(0, text.length()-1);
    }
  }
}

Thank you for your help.

1 Like

Looks good! One suggestion – update degree=int(0+text); in keyPressed just after you update text=text+key. Otherwise it is possible that a new key+enter might both get processed by keypressed before degrees gets updated on the next frame, and then enter will be ignored even though the text value is correct.