Home > Net >  Convert List<object> to int
Convert List<object> to int

Time:12-06

//CODE SNIPPET

boolean ShouldContinue1 = true;
List<String> b = new LinkedList();
input.useDelimiter("//s");

  




  while (ShouldContinue1) {

       String key = input.nextLine();

       b.add(key);

       int[] num = new int[(b.size()) / 2];
       int[] denom = new int[(b.size()) / 2];

   if (b_contains_string(key) == 1) {

  

// Problem

       for (int i = 0; i < b.size() - 1; i  ) {

            if (i % 2 == 0) {

               

                   num[i / 2] = Integer.parseInt(b.get(i));
            
           } 
          else if (i % 2 != 0) {

           

        denom[i / 2] = Integer.parseInt(b.get(i));
        
      }
    }
  } 
  else {

    for (int i = 0; i < b.size(); i  ) {

      if (i % 2 == 0) {

        

//This line causes error

            num[i / 2] = Integer.parseInt(b.get(i));

//

      } 
      else if (i % 2 != 0) {

        

             denom[i / 2] = Integer.parseInt(b.get(i));

//Ends

       }
    }

  }

//The error message I get (with specified lines)

//Exception in thread "main" java.lang.NumberFormatException: For input string: "12 24 21 30" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at line

//

//

Not a duplicate, other posts ineffective in explaining my problem

CodePudding user response:

you should use the parseInt method for converting string to integer.

Eg: num[i / 2] = Integer.parseInt((b.get(i));

CodePudding user response:

List<String> b = new LinkedList(); means that the list b can only store strings.

You're then checking if(b.get(i) instanceof Number){, which won't work because b only contains strings, as it is of type List<String>. You're getting a compile time error because the compiler knows that it will always be false, because the String and Number aren't interchangable like that.

x instanceof SomeType is used to see if x's type is castable to SomeType. So in your code it is checking if the type of b.get(i) is stored as a Number. b.get(i) will always be a string, and so b.get(i) instanceof Number will throw an exception, because regardless of what that string is (whether it is "asdaasd" or "12" or "123asda") it will never be stored as a Number, as the value came from a List<String>.

Remove the instanceof Number if statements as they are causing the errors you are seeing. If you are just expecting numerical strings (like "12", "41", "123" etc) in b, just use the Integer.parseInt. If you are expecting a mixture of numeric strings and non-numeric strings (like "12", "aaa", "123aaa"), then please look at this question: How to check if a String is numeric in Java . Despite what you said in your question, it is effective at explaining your problem.

(Editted for clarity/based off comment below)

  •  Tags:  
  • java
  • Related