dimanche 27 juin 2021

check the value of a String in if statement [duplicate]

As you know, a real interval is a set of real numbers that contains all real numbers lying between any two numbers of the set. I'm writing a program to calculate the Intersect and Union of two intervals. The interval can be (-∞,n) or it can be (n1,n2). For simplification, the user only needs to type "-" instead of "-∞". In a part of my program, I put an if statement to declare if the interval starts with a number or "-". Here's my code:

import java.util.Scanner;

public class myProgram {

    public static void main(String[] args) {
        Scanner s1 = new Scanner(System.in);
        System.out.println("Please type in your first interval:");
        String i1 = s1.next();
        String i1s = i1.substring(1, i1.indexOf(','));
        if(i1s != "-") {
            int e = Integer.parseInt(i1s);
            System.out.println("e = " + e);
        } else if (i1s == "-") {
            System.out.println("i1s = " + i1s);
        }
    }

}

My input is: (-,8) and I see this Error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:642)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at myProgram.main(myProgram.java:11)

It seems like the if statement doesn't work correctly... but why?

Aucun commentaire:

Enregistrer un commentaire