سؤال

I'm developing a program and in it, a field from a database is pulled and according to its numerical value, will display one of three things in the GUI: "WARNING", "SEVERE" OR "CRITICAL".

If it is between 0 and 100, it should display "WARNING" If it is between 100 and 200, it should display "SEVERE" If it is over 200, it should display "CRITICAL"

The part of my code that determines this is posted below. I am getting unfavorable results, for any value that is between 100 and 200, "ERROR" is displayed. Is my logic wrong, or is there something deeper going on here?

public class ThreatPanel {

...

final int TEST = 0;
final int TEST2 = 100;
final int TEST3 = 200;
...
}



public void ShowThreats(){

    String targetEnd = MainDisplay.getTargetIpHolder();     
    TargetServerData.setText(targetEnd);

    String attackerEnd = MainDisplay.getAttackerIpHolder();
    AttackerData.setText(attackerEnd);

    int threatLevelEnd = MainDisplay.getThreatLevelHolder();
    System.out.println(threatLevelEnd);
    if ((threatLevelEnd > TEST ) && (threatLevelEnd < TEST2)){
        ThreatLevelData.setText("WARNING");
    }
    if ((threatLevelEnd > TEST2 ) && (threatLevelEnd < TEST3)){
        ThreatLevelData.setText("SEVERE");
    }
    if (threatLevelEnd > TEST3){
        ThreatLevelData.setText("CRITICAL");
    }
    else{
        ThreatLevelData.setText("ERROR");
    }

}
هل كانت مفيدة؟

المحلول

Solution to your problem:

// checks for value in between 0 to 100 excluding 0 and 100
if (threatLevelEnd  > 0 && i<100) 
    System.out.println("WARNING");
// checks for value in between 100 to 200 excluding 200
else if (threatLevelEnd >= 100 && threatLevelEnd < 200) 
    System.out.println("SEVERE");
// checks for value greater than 200
else if (threatLevelEnd >= 200)
    System.out.println("CRITICAL");
else 
// this is default if value is negative or zero
     System.out.println("ERROR");

Currently what you are doing.

// checks for value in between 0 to 100 excluding 0 and 100
if (threatLevelEnd  > 0 && i<100) 
    System.out.println("WARNING");
// checks for value in between 100 to 200 excluding 100 and 200
if (threatLevelEnd > 100 && threatLevelEnd < 200) 
    System.out.println("SEVERE");
// checks for value greater than 200
if (threatLevelEnd > 200)
    System.out.println("CRITICAL");
else 
// if value is not grether than 200
     System.out.println("ERROR");

So anyhow your very last if-else is getting executed and overwriting your previous values.

نصائح أخرى

Your last else statement only applies to the if directly above it, so this else statement will always trigger when threatLevelEnd is less than TEST3, overwriting any values set in your first 2 if clauses (where you set warning and severe).

Using an if and else if idiom will avoid this, since then the later if clauses are only executed if the earlier if did not, so the final else clause will not override earlier settings.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top