Search code examples
javaarraysstringnumberscube

How to take multiple integers as single input separated by space in java, then break them into integers?


Need to take input 1 2 3 or of any length separated by space then break it into separate integers. I have tried array, Strings and CharAt() , string.split() method but they are not working.

Input can be 1 2 3 4 or 1 2 or of any length, we need to separate 1,2,3 as integers.

I have tried so far:

class Cube{ 
  public static void main(String args[]){ 
    int i,j=0,sum=0; int arr[]=new int[10]; 
    Scanner scan=new Scanner(System.in); 
    String s=scan.nextLine(); 
    int len =s.length(); 
    for(i=0;i<=len;i++){ 
        String[] str=s.split(" "); 
        int i=str[j]; sum+=Math.pow(3,i); j++; 
    } 
  } 
}

Solution

  • You are not parsing the string to int. You need to use Integer.parseInt(). Also, use of BufferedReader is preferred.

    class Cube{ 
      public static void main(String args[]){ 
        int i,j=0,sum=0; int arr[]=new int[10]; 
        Scanner scan=new Scanner(System.in); 
        String s=scan.nextLine(); 
    
        String[] str=s.split(" ");
        for(i=0;i<=str.length;i++){ 
            int temp = Integer.parseInt(str[i]);
            sum+=Math.pow(3,temp); 
        } 
      } 
    }