0

I need to read a file using BufferedReader, and on the second line i know there will always be 2 integers: 456 666 for example; but I don't know how many digits they will have, so after extracting the line (type String) with BufferedReader, I read char by char of that string to get the digits and add them to a array of char. When I have all the digits I fill the array with '\0' Example:

array[0] = '4'
array[1] = '5'
array[2] = '6'
array[3] = '\0'
array[4] = '\0'
and so on

Now i wish to turn this array to an integer. I tried to first cast this array to a string and afterward apply Integer.parseInt but i does not work. I have no idea how to fix this problem. any help?

2
  • 1
    @LewsTherin: wouldn't that be a Strinteger? Commented Oct 18, 2012 at 19:57
  • @Wug Ha ha, except it is weird trying to say it ;) Commented Oct 18, 2012 at 20:02

8 Answers 8

2

You can't cast an array to a String... But if you use spaces as fillers instead of \0, then you can do it like this:

int i = Integer.parseInt(String.valueOf(array).trim());

Regarding the comment - cool, trim() eliminates trailing 0x0 too:

public static void main(final String[] args) {
    char[] chars = new char[5];
    chars[2] = '9';
    System.out.printf("Original length: %d%n",String.valueOf(chars).length());
    System.out.printf("Trimmed length:  %d%n",String.valueOf(chars).trim().length());
    System.out.printf("Parsed:          %d%n",Integer.parseInt(String.valueOf(chars).trim()));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Even if you do use nulls as fillers you should still be able to do it this way. You'll just get "456 " instead of "456", both of which Integer.parseInt() should be able to handle.
2

I highly recommend using Scanner instead. From the documentation:

A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

A Scanner will use whitespace as its default delimiter, so you should be able to simply call sc.nextInt() for each expected integer token. See the linked page for usage examples.

Comments

2

What if you read just the line and attempt to parse it as an int. Since you don't know whether it is an integer use an exception to handle it:

String[] nextLine = reader.nextLine().split("\\s+") ;
Integer[] integer = new Integer[nextLine.length()] ;
try
{
  for(int i=0; i < nextLine.length();i++)  
   integer[i] = Integer.parseInt(nextLine[i]) ;
}
catch(NumberFormatException exception)
{
  exception.printStackTrace();
}  

1 Comment

there are two ints, so split the line on \s+ first
1

Assuming array is your char array, this should do your work:

String str = "";
for (char c : array)
    str += c;

int result = Integer.parseInt(str);

2 Comments

String.valueOf(array) is a much better way to do this.
@Wug good point. you are right :) but possibly valueOf() method is doing the same iteration to return the same string. am i wrong?
1

You'd be better off using a Scanner.

Scanner input = new Scanner(new File("myfile.txt"));
int first  = input.nextInt();
int second = input.nextInt();

Comments

0

Ok, if you simply want to turn that array to characters into an integer, here is how you would do it.

char array[] = new char[5];

    array[0] = '4';
    array[1] = '5';
    array[2] = '6';
    array[3] = '\0';
    array[4] = '\0';

    String newString = String.copyValueOf(array);
    newString = newString.replace("\0", "");

    int newInt = Integer.parseInt(newString);

    System.out.println(array);
    System.out.println(newInt);

The above code has been tested and verified.

1 Comment

I want to add that you should be able to use newString = newString.trim(); as an alternative to newString = newString.replace("\0", "");
0
    // Assume an initial size of the array
    char array[] = new char[5];
    array[0] = '4';
    array[1] = '5';
    array[2] = '6';
    array[3] = '\0';
    array[4] = '\0';


    StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < array.length && array[i] != '\0'; i++){
        buffer.append(array[i]);
    }

    int myInteger = Integer.parseInt(buffer.toString());

If you want to create a String first and then parse it to an Integer, I suggest you use StringBuffer mainly because Strings in Java are immutable (you can't change a particular character in them). If you use StringBuffer you can work around this problem by applying toString method to the newly created object and then use Integer.parseInt.

Comments

0

Use String constructor public String(char[] letters) then Integer.parseInt(...).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.