Hey guys. I have a headache here as im new to Java. Ive tried searching, but found nothing that really helped me out. forgive a noob :)

Im trying to split a string from a textfile with the following format:
0 0 0 0 0 0 0 0 0 110 0

11 numbers everytime. the numbers will vary though.

Heres the code:

public String input;
	public String values;
		
		info() throws IOException {
		    //System.out.print("Reading from file.");
		    StringBuilder text = new StringBuilder();
		    String NL = System.getProperty("line.separator");
		    Scanner scanner = new Scanner(new FileInputStream(Loader.selectedFile1));
		    try {
		      while (scanner.hasNextLine()){
		        text.append(scanner.nextLine() + NL);
		        input = text.toString();
		      }
		    }
		    finally{
		      scanner.close();
		    }
		    System.out.println(java.util.Arrays.toString(
		            input.split(" ")));
		    values = java.util.Arrays.toString(input.split(" "));
		    	
		    }

This will output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 110, 0]

Can someone help me conver these into integers and fill them into an array? This is killing me :)

thanks
Theformand

Recommended Answers

All 3 Replies

Get the array of Strings that you get from the split(" ").
Create an array of integers of the same size.
For each String in the array you can use a method in the Integer class (seek and ye shall find) to parse the string into an integer, which you can then save into the corresponding position in the integer array.

Okay, almost got it working now. Although I am getting a numberFormatException from it.
The code is now:

String[] strings= new String[11];
		    strings = input.split(" ");
		    int[] values = new int[11];
		    //System.out.println(strings);
		   
		    
		    try{
		   for (int i = 0; i<strings.length; i++){
	    	values[i]=Integer.parseInt(strings[i]);
		     System.out.println(values[i]);
		    }
		    }
		    catch(NumberFormatException e){
		    	System.out.println("numberformat exception: " +e.getMessage());	
		    }
		    }
		    
		    }

Here is the output:

1
2
3
4
5
6
7
8
9
10
11
numberformat exception: For input string: "
"

You will notice, there is nothing between the two "" where it seems to fail.... any ideas?

Not "nothing" exactly, it looks like a new line character ( "\n" )
Presumably this is what comes after the 11th value in the input?
There are a few ways to handle this, eg you can test strings for equal to "\n" before trying to parse it. You may also want to check that the split array has the right number of values for the int array (or vicce-versa)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.