Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Creating an array from a string

  1. #1
    Junior Member
    Join Date
    Nov 2012
    Posts
    7
    Thanks
    1
    Thanked 1 Time in 1 Post

    Unhappy Creating an array from a string

    I am having trouble taking a String type of data, extracting information from it, and then putting that information into an array. I have to extract the integers from the string while ignoring all non-digit characters

    Ex: String: "223aiwij233.02 93"
    Output: Array {223, 233, 02, 93}

    The problem lies in the intParse method. My problem is that when I pull out the integers, the program is 'making up' numbers. Right now, the code breaks if there is more than 1 consecutive non-digit in the string and will run, but incorrectly if the String has only 1 non-digit character between integers. I have posted most of the code. After extracting the numbers, I will have to sort them, but I have already figured that part out.

     
    public static void main(String[] args)
    {
    	Scanner stdIn = new Scanner(System.in);
    	System.out.println("Enter a string: ");  
    	String s = stdIn.next();  //String s from user
    	int[] parsed = new int[10];  //Array parsed extracted from string s
    	int[] sorted = new int[10];  //Array sorted from array parsed
     
    	//call intParse method
    	parsed = intParse(s);
     
    	//call intSort method;
    	sorted = intSort(parsed);
     
    	stdIn.close();	
    }
     
    public static int[] intParse(String s)
    {
    	int[] numArray = new int[10];  //creating array to insert elements from string
    	int j = 0;  //counter
    	String number = "";  //empty string to hold integers from String s
    	for (int i=0; i<s.length(); ++i)
    	{
    		if (Character.isDigit(s.charAt(i)))
    		{
    			number += s.charAt(i);  //if the current character is a digit, add it to the number string.  if not a digit, run code under else statement.
    		}
    		else
    		{
    			System.out.println(number);  //print the current number to screen
    			numArray[j] = numToArr(number); //take the current string number and add it to next available array index by running the numToArray method
    			++j; //increase j so the next empty array index will be used
    			number = ""; //set the number string back to a blank and continue through for loop
    		}
    	}
    	return numArray;
    }
     
    public static int numToArr(String b)
    {
    	int realNumber = Integer.parseInt(b);  
    	return realNumber;
    }


  2. #2
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Default Re: Creating an array from a string

    Well, first off, are there any exceptions that are being thrown? If so, please copy-paste the error message into the thread. Second, your intSort(); method is not in your posted code. If you want help, you need to include all methods that are being used. Does intSort(); just sort the array? What does it do?

  3. #3
    Junior Member
    Join Date
    Nov 2012
    Posts
    7
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Creating an array from a string

    Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unk nown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Program10.numToArr(Program10.java:55)
    at Program10.intParse(Program10.java:36)
    at Program10.main(Program10.java:14)


    Below is the entire program:
    import java.util.*;
     
    public class Program10
    {
    	public static void main(String[] args)
    	{
    		Scanner stdIn = new Scanner(System.in);
    		System.out.println("Enter a string: ");  
    		String s = stdIn.next();  //String s from user
    		int[] parsed = new int[10];  //Array parsed extracted from string s
    		int[] sorted = new int[10];  //Array sorted from array parsed
     
    		//call intParse method
    		parsed = intParse(s);
     
    		//call intSort method;
    		sorted = intSort(parsed);
     
    		stdIn.close();	
    	}
     
    	public static int[] intParse(String s)
    	{
    		int[] numArray = new int[10];  //creating array to insert elements from string
    		int j = 0;  //counter
    		String number = "";  //empty string to hold integers from String s
    		for (int i=0; i<s.length(); ++i)
    		{
    			if (Character.isDigit(s.charAt(i)))
    			{
    				number += s.charAt(i);  //if the current character is a digit, add it to the number string.  if not a digit, run code under else statement.
    			}
    			else
    			{
    				System.out.println(number);  //print the current number to screen
    				numArray[j] = numToArr(number); //take the current string number and add it to next available array index by running the numToArray method
    				++j; //increase j so the next empty array index will be used
    				number = ""; //set the number string back to a blank and continue through for loop
    			}
    		}
    		return numArray;
    	}
     
     
    	public static int[] intSort(int[] s)
    	{
    		int[] sortArr = s;
    		sort(s);
    		return sortArr;
    	}
     
     
    	public static int numToArr(String b)
    	{
    		int realNumber = Integer.parseInt(b);
    		return realNumber;
    	}
     
    	public static void sort(int[] list)
    	{
    		int j; // index of smallest value
    		for (int i=0; i<list.length-1; i++)
    		{
    			j = indexOfNextSmallest(list, i);
    			swap(list, i, j);
    		}
    	}
     
    	private static int indexOfNextSmallest(int[] list, int startIndex)
    	{
    		int minIndex = startIndex; // index of smallest value
    		for (int i=startIndex+1; i<list.length; i++)
    		{
    			if (list[i] < list[minIndex])
    			{
    				minIndex = i;
    			}
    		}
    	return minIndex;
    	} 
     
    	private static void swap(int[] list, int i, int j)
    	{
    		int temp; // temporary holder for number
    		temp = list[i];
    		list[i] = list[j];
    		list[j] = temp;
    	}
     
    }

  4. #4
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Default Re: Creating an array from a string

    OK, a NumberFormatException happens when you try to parse a non-number value into a number value.

    //this throws a NumberFormatException because bob isn't a number
    int x = Integer.parseInt("bob");

    In order to fix it, you have to create a method that checks to see if the value you are parsing in a number.

    Something like this

    public boolean isNum(String num)
    {
    //Sorry, won't give you answers
    //write an algorithm here that checks to see if num is a number
    //return false if a non-number is found
    //once looped through, return true
    }

    So, you're numToArr(); method, which is the one getting the exception, would look something like this:

    public static int numToArr(String b)
    	{
               if(isNum(b))
                    return Integer.parseInt(b);
    	}

  5. #5
    Junior Member
    Join Date
    Nov 2012
    Posts
    7
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Creating an array from a string

    Ok, I see that the problem is that my variable number is not being created the way I intended.

    I put a system.out.print in the intParse() method in the if statement and else statement. Depending on the String s input by the user, my method of pulling out numbers is not working correctly.

    Can you help me solve that part? There must be an issue with my logic in the If/Else statement. I want to step through the String s character by character. If the character is a digit, then add that digit to a String number. When the next character is no longer a digit, take that string number and parse it to be an integer then add it to the array. Then continue doing that same process until the end of String s. The logic is breaking down when there are consecutive non-digit characters in the string and I am not sure I can fix it without guidance. When the string has those consecutive non-digit characters, the program stops running and the number variable is either blank or never gets created.

    public static int[] intParse(String s)
    	{
    		int[] numArray = new int[10];  //creating array to insert elements from string
    		int j = 0;  //counter
    		String number = "";  //empty string to hold integers from String s
    		for (int i=0; i<s.length(); ++i)
    		{
    			if (Character.isDigit(s.charAt(i)))
    			{
    				number += s.charAt(i);  //if the current character is a digit, add it to the number string.  if not a digit, run code under else statement.
    			}
    			else
    			{
    				System.out.println(number);  //print the current number to screen
    				numArray[j] = numToArr(number); //take the current string number and add it to next available array index by running the numToArray method
    				++j; //increase j so the next empty array index will be used
    				number = ""; //set the number string back to a blank and continue through for loop
    			}
    		}
    		return numArray;
    	}

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,164
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Creating an array from a string

    You need a new state for scanning. After scanning over digits and finding a non-digit and parsing and saving the number, you need to scan to the next digit character.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Default Re: Creating an array from a string

    In your else statement, you need another if/then statement that contains another loop, while/do while/for, that looks for the next digit. Your if then statement could check to see if number.length() == 0, if it does, then blah blah blah, other wise, use your current else statement code.

    else
    			{
                                    if(number.length()==0)
                                    {
                                             //code here 
                                    }
                                    else{
    				        System.out.println(number);  //print the current number to screen
    				        numArray[j] = numToArr(number); //take the current string number and add it to next available array index by running the numToArray method
    				        ++j; //increase j so the next empty array index will be used
    				        number = ""; //set the number string back to a blank and continue through for loop
                                    }
    			}

Similar Threads

  1. Char array to a String array with hex
    By fortune2k in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 20th, 2014, 01:01 PM
  2. Creating an object with a String from file IO
    By eloel33 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 2nd, 2012, 07:19 PM
  3. Testing if an inputted String exists in an String Array
    By djl1990 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 29th, 2012, 03:46 PM
  4. [SOLVED] Sorting an object array using string variables from a string array
    By Shadud in forum What's Wrong With My Code?
    Replies: 0
    Last Post: November 26th, 2012, 05:50 PM
  5. Using a string when creating an object.
    By ZeroLRS in forum Object Oriented Programming
    Replies: 10
    Last Post: July 13th, 2011, 09:22 PM