(JAVA) How to turn elements of a String Array into integers

Status
Not open for further replies.

Ry

Beta member
Messages
5
Hey everybody. I working on a project for school that is due may 3rd, and right now I'm trying to turn the elements of a String array into integer values. please help me, i know it is only two or three lines of code at max but i just can't figure it out. Any help you can offer is deeply Appreciated, thanks.

for info on the project i working on go to: http://www.cs.uncc.edu/~rilson/2215/assignments/KnapEncrypt Instructions S05.html

here is my code so far, i am trying to turn the elements of encryptvalue[] into integers in the first while loop.
---------------------------------------------------------------------------
import java.util.*;
import java.io.*;

public class KnapEncrypt
{

public static void main (String[] args)throws java.io.IOException
{

FileReader fr = new FileReader (args[0]);
BufferedReader inFile = new BufferedReader (fr);
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));


String line = inFile.readLine();
int value_index;
StringTokenizer tokens = new StringTokenizer(line);
String[] encryptvalue = new String[tokens.countTokens()];

int converted;
int total = 0;
value_index = 0;
int line_index = 0;



while (value_index < encryptvalue.length)
{
Integer.parseInt(encryptvalue[value_index]);
encryptvalue[value_index] = tokens.nextToken();
System.out.print(encryptvalue[value_index] + " ");
value_index++;

}

total = encryptvalue[1] + encryptvalue[0];
System.out.println(total);

/* ignore this stuff (for now)

while((line = inFile.readLine()) != null && line.length() != 0)
{

if (line.length() == 10)
{
System.out.println("input: " + line);

if (line.charAt(line_index) == '1')
{
total = total + encryptvalue[line_index];
}

else
{
total = total + 0;
}

System.out.println("output: " + total);
}

else
{
System.out.println("input: " + line);
}

line_index++;
}
*/


}
}
 
Code:
Integer.parseInt(encryptvalue[value_index]);
parseInt doesn't change values in place. You'll need to create an Integer (or int, I suppose) and store the parsed value in to that. Right now you are just throwing it away.
 
yep what you have is fine but as CI says you need to create an integer to put the value into:
Code:
int theInteger;

...
...

theInteger =  Integer.parseInt(encryptvalue[value_index]);

The integer value of the string is now stored in "theInteger" for you to do whatever you like with it.
 
Status
Not open for further replies.
Back
Top Bottom