为什么我的if-else工作没有任何意义?

时间:2013-07-27 04:43:45

标签: java if-statement logic

下面是我的代码,我相信我的问题在于我的getGeoLoc()方法。此方法的目的是通过输入IP从api获取地理位置信息,然后使用该信息,特别是纬度和经度值,以使地图图像与城市和地区值一起显示在GUI中。 / p>

我的问题是,我发现在if和else if语句中没有任何反应,我测试api是否成功失败并采取相应措施。我通过测试字符串来做到这一点。 api返回的第一行是“success”或“fail”,我将其存储在一个数组(lines [0])中,然后存储到一个变量(geoTester)中。

当我在if / if else之前打印出这个值时,我得到一个值,当我在if / if中打印它时我什么都没得到。为什么是这样?

我怀疑它可能与我的变量的方式或我的if / if else中的某种逻辑错误有关。

道歉:我没有意识到我的问题在我的比较陈述中存在,我忽略了它。对不起,重复的问题

ThreatPanel.java:

public class ThreatPanel {

JPanel DarkPanel = new JPanel(); //panel to house all display components using GridBagLayout

public GridBagLayout gridBag = new GridBagLayout();
public GridBagConstraints gbc = new GridBagConstraints();

//Parameters for determining the threat level
final int TEST = 0;
final int TEST2 = 10;
final int TEST3 = 20;

//Variables used for finding the geo location and displaying the google map image
private String geoTester;
private String city;
private String region;
private String latitude;
private String longitude;
private Image img;
private ImageIcon icon;
URL geoLocRetriever;

Color severeColor = new Color(225,69,00); // a more distinguishable 'orange'
Color borderColor = new Color(235,235,235); // color used for each components border


//Target declarations.  
JLabel Target = new JLabel("TARGET");
JLabel TargetServerData;

//Client declaration
JLabel ClientIdData = new JLabel("filler"); //filler

//ServerID declarations 
JLabel ServerIdData;

//Attacker declarations.
JLabel Attacker = new JLabel("ATTACKER");
JLabel AttackerData;

//Geo Location declarations 
JLabel GeoLocData;
JLabel GeoLocImg;
JLabel GeoLocLabel = new JLabel("LOCATION");

//Threat Level declarations.
JLabel ThreatLevel = new JLabel("THREAT");
JLabel ThreatLevelData;

//Number of Attacks declarations
JLabel NumberOfAttacks = new JLabel("ATTACKS");
JLabel NumberOfAttacksData;

//DUMMY
JLabel dummy1 = new JLabel();
JLabel dummy2 = new JLabel();


public ThreatPanel()
{
DarkPanel.setLayout(gridBag);
DarkPanel.setBackground(Color.BLACK);

//Create new JLabels for the data that is to be continuously updated
TargetServerData = new JLabel();
AttackerData = new JLabel();
ThreatLevelData = new JLabel();
NumberOfAttacksData = new JLabel();
ServerIdData = new JLabel();
GeoLocData = new JLabel();
GeoLocImg = new JLabel();

// Component settings. After each add(), GridBagConstraint (gbc) returns to default.
// gridx and gridy refer to the cells position, similar to Excel or HTML tables.
// weightx and weighty determines how to distribute space among columns and rows.
// gridheight and gridwidth define how many cells a component occupies.
// fill determines how the component will fill the display area.

//FIRST COLUMN//////////////

Target.setFont(new Font("Arial", Font.BOLD, 85));
Target.setForeground(Color.GREEN);
Target.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
Target.setBorder(BorderFactory.createMatteBorder(3, 3, 2, 2, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(Target, gbc);

ClientIdData.setForeground(Color.WHITE);
ClientIdData.setFont(new Font("Arial", Font.BOLD, 100));
ClientIdData.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 0;
gbc.gridy = 1;
ClientIdData.setBorder(BorderFactory.createMatteBorder(0, 3, 0, 2, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(ClientIdData, gbc);

TargetServerData.setForeground(Color.WHITE);
TargetServerData.setFont(new Font("Arial", Font.BOLD, 110));
TargetServerData.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 0;
gbc.gridy = 2;
TargetServerData.setBorder(BorderFactory.createMatteBorder(0, 3, 0, 2, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(TargetServerData, gbc);

ServerIdData.setForeground(Color.WHITE);
ServerIdData.setFont(new Font("Arial", Font.BOLD, 100));
ServerIdData.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 0;
gbc.gridy = 3;
ServerIdData.setBorder(BorderFactory.createMatteBorder(0, 3, 0, 2, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(ServerIdData, gbc);

Attacker.setFont(new Font("Arial", Font.BOLD, 85));
Attacker.setForeground(Color.GREEN);
Attacker.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 0;
gbc.gridy = 4;
Attacker.setBorder(BorderFactory.createMatteBorder(2, 3, 2, 2, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(Attacker, gbc);

AttackerData.setForeground(Color.RED);
AttackerData.setFont(new Font("Arial", Font.BOLD, 110));
AttackerData.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 0;
gbc.gridy = 5;
AttackerData.setBorder(BorderFactory.createMatteBorder(0, 3, 0, 2, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(AttackerData, gbc);

GeoLocData.setFont(new Font("Arial", Font.BOLD, 70));
GeoLocData.setForeground(Color.RED);
GeoLocData.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 0;
gbc.gridy = 6;
GeoLocData.setBorder(BorderFactory.createMatteBorder(0, 3, 3, 2, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(GeoLocData, gbc);

//SECOND COLUMN/////////////////

ThreatLevel.setFont(new Font("Arial", Font.BOLD, 85));
ThreatLevel.setForeground(Color.GREEN);
ThreatLevel.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.0;
ThreatLevel.setBorder(BorderFactory.createMatteBorder(3, 0, 2, 3, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(ThreatLevel, gbc);

ThreatLevelData.setFont(new Font("Arial", Font.BOLD, 100));
ThreatLevelData.setForeground(Color.BLACK);
ThreatLevelData.setOpaque(true);
ThreatLevelData.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 1;
gbc.gridy = 1;
ThreatLevelData.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 3, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(ThreatLevelData, gbc);

NumberOfAttacks.setFont(new Font("Arial", Font.BOLD, 85));
NumberOfAttacks.setForeground(Color.GREEN);
NumberOfAttacks.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 1;
gbc.gridy = 2;
NumberOfAttacks.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 3, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(NumberOfAttacks, gbc);

NumberOfAttacksData.setFont(new Font("Arial", Font.BOLD, 100));
NumberOfAttacksData.setForeground(Color.RED);
NumberOfAttacksData.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 1;
gbc.gridy = 3;
NumberOfAttacksData.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 3, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(NumberOfAttacksData, gbc);

GeoLocLabel.setFont(new Font("Arial", Font.BOLD, 85));
GeoLocLabel.setForeground(Color.GREEN);
GeoLocLabel.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 1;
gbc.gridy = 4;
GeoLocLabel.setBorder(BorderFactory.createMatteBorder(2, 0, 2, 3, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(GeoLocLabel, gbc);

GeoLocImg.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridheight = 2;
gbc.gridx = 1;
gbc.gridy = 5;
GeoLocImg.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 3, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(GeoLocImg, gbc);

//DUMMY ROW AND COLUMN used in order to preset fixed size for map component
dummy1.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridheight = 2;
gbc.gridx = 2;
gbc.gridy = 5;
gbc.insets = new Insets(302,0,0,0); //extra 2 pixels to account for border
dummy1.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 0, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(dummy1, gbc);

dummy2.setHorizontalAlignment(SwingConstants.CENTER);
gbc.gridx = 1;
gbc.gridy = 7;
gbc.insets = new Insets(0,503,0,0); //extra 3 pixels to account for border
dummy2.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 0, borderColor));
gbc.fill = GridBagConstraints.BOTH;
DarkPanel.add(dummy2, gbc);

MainDisplay.frame.add(DarkPanel);

}

public void getGeoLoc()
{
String locHolder;
try {
    //System.out.print(MainDisplay.getAttackerIpHolder());
    geoLocRetriever = new URL("http://ip-api.com/line/"+ MainDisplay.getAttackerIpHolder());
} catch (MalformedURLException e) {
    e.printStackTrace();
}

InputStream stream = null;
try {
    stream = geoLocRetriever.openStream(); //read from url
} catch (IOException e1) {
    e1.printStackTrace();
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
if (stream != null) try {
    final BufferedInputStream input = new BufferedInputStream(stream);
    final byte[] reader = new byte[16384];
    int r = 0;
    while ((r = input.read(reader, 0, 16384)) != -1)
        buffer.write(reader, 0, r);
    buffer.flush();
} catch(IOException e) {
    e.printStackTrace();
} finally {
    if(stream != null) try {
        stream.close();
    } catch(IOException e) {
        e.printStackTrace();
    }
}


locHolder = new String(buffer.toByteArray());
String[] lines = locHolder.split("\n"); //arranges data from stream into an array
System.out.print(lines[0]);
geoTester = lines[0];
if (geoTester == "success"){ //test the first returned line for success or failure to avoid null outputs in the panel


    System.out.print(geoTester);
    city = lines[5] + ",";
    region = lines[4];
    latitude = lines[7];
    longitude = lines[8];
    //System.out.print(city);
    System.out.print(lines[5]);
    String temp;
    temp="https://maps.googleapis.com/maps/api/staticmap?center=" +latitude +"," +longitude +"&zoom=7&size=500x300&markers=color:red|label:A|" +latitude +"," +longitude +"&sensor=false";
    URL mapurl = null;
    try {
        mapurl = new URL(temp);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        img = ImageIO.read(mapurl);
    } catch (IOException e) {
        e.printStackTrace();
    }
    icon = new ImageIcon(img);  //ImageIcon with the google map image
}
else if (geoTester == "fail"){ // if fail, the jlabel for the map will become error image
    try {
        img = ImageIO.read(new URL ("file:src/jollyroger.jpg"));
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    icon = new ImageIcon(img);
    city = "To "; //to be used for error feedback
    region = "Search"; //to be used for error feedback
}

}

public void ShowThreats(){

getGeoLoc();
String geoLocEnd = city + region;
GeoLocData.setText(geoLocEnd);
GeoLocImg.setIcon(icon);

String targetEnd = MainDisplay.getTargetIpHolder(); 
    if (targetEnd == null){
        TargetServerData.setText("NULL VALUE");
    }
    else TargetServerData.setText(targetEnd);

String attackerEnd = MainDisplay.getAttackerIpHolder();
    if(attackerEnd == null){
        AttackerData.setText("No IP Stored");
    }
    else AttackerData.setText(attackerEnd);

String serverIdEnd = MainDisplay.getServerIdHolder();
    ServerIdData.setText(serverIdEnd);

String numAttacksEnd = MainDisplay.getNumAttacksHolder();
    if(numAttacksEnd == null){
        NumberOfAttacksData.setText("N/A");
    }
    else NumberOfAttacksData.setText(numAttacksEnd);        

    int threatLevelEnd = MainDisplay.getThreatLevelHolder();
    if ((threatLevelEnd > TEST ) && (threatLevelEnd < TEST2)){
        ThreatLevelData.setText("WARNING");
        ThreatLevelData.setForeground(Color.YELLOW);
    }
    else if ((threatLevelEnd > TEST2 ) && (threatLevelEnd < TEST3)){
        ThreatLevelData.setText("SEVERE");
        ThreatLevelData.setBackground(severeColor);
    }
    else if (threatLevelEnd > TEST3){
        ThreatLevelData.setText("CRITICAL");
        ThreatLevelData.setBackground(Color.RED);
    }
    else{
        ThreatLevelData.setText("N/A");
        ThreatLevelData.setBackground(Color.PINK);
    }



}

}

2 个答案:

答案 0 :(得分:2)

您不能使用“==”来比较Java中的字符串。

// Wrong
geoTester = lines[0];
if (geoTester == "success"){ //test the first returned line for success or failure to avoid null outputs in the panel


// Correct
if (geoTester.compareTo("success") == 0)

您还可以使用“String.equals()”或“String.equalsIgnoreCase()”:

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

答案 1 :(得分:1)

==比较确切的值。因此,它会比较primitive值是否相同,

.equals()调用comparison的{​​{1}}方法,该方法将比较引用指向的实际对象。对于字符串,它会比较每个字符以查看它们是否objects

比较像

equal

喜欢阅读:Java Strings: compareTo() vs. equals()

相关问题