Question

In: Computer Science

JAVA JAVA JAVA . I need to convert a string input to int array, for example...

JAVA JAVA JAVA . I need to convert a string input to int array, for example if user enters 12 / 27 / 2020 , I want to store each value in a separate array and add them afterwards.

Solutions

Expert Solution

For converting string to an int you can use the java method Integer.parseInt()

But this is valid only for a string which is of length more than 0 and is a valid integer.

That is why in you case we cannot directly use this method, instead we have to convert your input in usable format.

For this

  • We will first read all of input in a String.
  • Traverse this string and whenever we encounter a digit for the first time, we start putting it in a number.
  • Once started when we face a non digit character or end of string we stop making this number and then store it in array

Please take a look at the Java code below for better understanding.

import java.util.*;

public class StringToIntArray{
        //method which takes in input string and parses int array from it
        static ArrayList<Integer> convert(String inp){
                ArrayList<Integer> arr = new ArrayList<Integer>();

                //return blank array if input is empty
                if(inp.length()==0)
                        return arr;

                int num=0;
                //this variable keeps a track on wheather we have started making out number
                boolean framing = false; 
                int i=0;
                while(i<inp.length()){
                        //check if it is a digit
                        char x = inp.charAt(i);
                        if(x>='0'&&x<='9'){
                                framing=true;
                                num=num*10+(x-'0'); //extract the numerical digit from char representation
                        }else{
                                if(framing){
                                        //if this character is not a digit and we were making the number,
                                        //then it is time to stop
                                        arr.add(num);

                                        //prepare for next run
                                        num=0;
                                        framing=false;
                                }
                        }
                        i++;
                }
                //Once string ends we might still have a number in process which needs to be added
                if(framing){
                                        //if this character is not a digit and we were making the number,
                                        //then it is time to stop
                                        arr.add(num);

                                        //prepare for next run
                                        num=0;
                                        framing=false;
                }
                return arr;
        }
    public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter string with integers.");
      //read all of input in one string
      String inp = sc.nextLine();

      //call conversion method
      ArrayList<Integer> arr = convert(inp);
      System.out.println("Elements in INT array");
      //print output array
      for(int i=0;i<arr.size();i++){
        System.out.print(arr.get(i)+" ");
      }
    }
}

Sample Output


Related Solutions

In Java, how can I convert a string user input for example a student starts a...
In Java, how can I convert a string user input for example a student starts a uni degree in "Winter/2022", to a date type, and then once I have done that, add 3 years to that value, and changing the season, so for example Student Started: Winter/2022 and Student Finished: Summer/2025. Is there any possible way to do this? Thank you.
Hello, I need to convert this java array into an array list as I am having...
Hello, I need to convert this java array into an array list as I am having trouble please. import java.util.Random; import java.util.Scanner; public class TestCode { public static void main(String[] args) { String choice = "Yes"; Random random = new Random(); Scanner scanner = new Scanner(System.in); int[] data = new int[1000]; int count = 0; while (!choice.equals("No")) { int randomInt = 2 * (random.nextInt(5) + 1); System.out.println(randomInt); data[count++] = randomInt; System.out.print("Want another random number (Yes / No)? "); choice =...
I need convert this java code to C language. There is no string can be used...
I need convert this java code to C language. There is no string can be used in C. Thank you! import java.util.Scanner; public class Nthword { public static void main( String args[] ) { String line; int word; Scanner stdin = new Scanner(System.in); while ( stdin.hasNextLine() ) { line = stdin.nextLine(); word = stdin.nextInt(); stdin.nextLine(); // get rid of the newline after the int System.out.println( "Read line: \"" + line + "\", extracting word [" + word + "]" );...
Java Programming I need an application that collects the user input numbers into an array and...
Java Programming I need an application that collects the user input numbers into an array and after that calls a method that sums all the elements of this array. and display the array elements and the total to the user. The user decides when to stop inputting the numbers. Thanks for your help!
Write a java method that takes a string and returns an array of int that contains...
Write a java method that takes a string and returns an array of int that contains the corresponding alphabetic order of each letter in the received string: An illustration: the method takes: "Sara" the method returns: {4,1,3,2} another illustration: the method takes: "hey" the method returns: {2,1,3}
Write a Java method that takes an array of char and a String as input parameters...
Write a Java method that takes an array of char and a String as input parameters and and returns an boolean. The method returns true if we can find the input string inside the array by starting at any position of the array and reading either forwards or backwards.
Convert this code written in Python to Java: students = int(input("How many students are in your...
Convert this code written in Python to Java: students = int(input("How many students are in your class?" )) while students<0:     print("Invalid # of students, try again.")     students = int(input("How many students are in your class?" )) tests = int(input("How many tests in this class? ")) while tests<0:     print("Invalid # of tests, try again.")     tests = int(input("How many tests in this class? ")) print("Here we go!") # Here we are creating a list called class_average to store average of all students....
binarySearchLengths(String[] inArray, String search, int start, int end) This method will take in a array of...
binarySearchLengths(String[] inArray, String search, int start, int end) This method will take in a array of strings that have been sorted in order of increasing length, for ties in the string lengths they will be in alphabetical order. The method also takes in a search string and range of indexes (start, end). The method will return a String formatted with the path of search ranges followed by a decision (true or false), see the examples below. Example 1: binarySearchLengths({"a","aaa","aaaaa"},"bb",0,2) would...
i need a pseudocode for a program in java that will convert dollars into euros and...
i need a pseudocode for a program in java that will convert dollars into euros and japanese yen using the print and prinln methods an if, if -else, statement a switch statement a while statement utilizes the file class uses the random class and random number generator and uses at least three methods other than main
Please give me an example of this java code. Vehicle - number: int - color: String...
Please give me an example of this java code. Vehicle - number: int - color: String - price: double - horsepower: double + Vehicle ( ) + Vehicle (int number) + Vehicle (int number, String color) + Vehicle (int number, String color, double price) + Vehicle (int number, String color, double price, double horsepower) +getnumber( ):int +setnumber(int number):void +getcolor( ):String +setcolor(String color):void +getprice( ):double +setprice(double price):void +gethorsePower( ):double +sethorsePower(double horsePower):void toString( ):String public String toString( ) { return "\n\n number...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT