How would I go about converting a string to an integer?

Say someone enters a 4 digit string. Like 1234.

Could I use the place of each digit and work with it? Pretty much, I wanna get 1 from the string "1234" and put it in a variable. Then get 2 from the string "1234" and put it in its own variable, and so forth.

Like take the 0 spot, which would be 1. and say change it to something else?

I know I could do something like

public class GetIntFromString {

   public static void main(String[] args) 
	{
 	   String str = "1234";  
  		for(int i = 0; i < str.length(); i++)
		{
			str.charAt(i);
			
			System.out.println(i);
  		
		}
		  
	}
}

Also do the same thing for each digit of the string. Is this possible without using an array?

Recommended Answers

All 14 Replies

The method str.charAt(i) that you are calling returns a char. Why don't you assign that call to a char variable and print that char.
You can also call the toCharArray method:

String s = "1234";
char [] ch = s.toCharArray();

// Now print the elements of the ch array.

Easiest way to do what you're trying to do would be to make a for loop from str.length()-1 down to 0. Take the least-significant characters first, multiply them the appropriate power of ten, and add them into an int.

So for your "1234" example, you'd take charAt(str.length()-1) on the first time through, which is '4', convert it to an int, and multiply it by 10^0 (==1), and add it to your accumulator variable: 4.

Next time through, you take str.charAt(str.length()-2), which is 3, and multiply it by 10^1 (==10), and add the result to the accumulator: 34.

Next time through, same thing, you add 2* 10^^2: 234
Last time, you get 1 * 10^^3, or 1000, so you end up with the int value 1234.

So should me for loop header be this?

for (int i = 0; i < str.length()-1; i++)

then I don't understand, how do I set it to str.charAt(str.length()-2) and so forth

If you want to count up from zero to (str.length() - 1) you do

for (int i = 0; i<str.length(); i++) {}

So if you want to count down from the end of the string you'd do

for (int i = <str.length()-1; i>=0; i++) {}

Then if str = "1234", str.charAt(i) points to '4', then '3', then '2', then '1'. You can do this other ways as well, but this way you're taking on the numbers in the way you're used to.

The for loop header you gave me is giving me an error

My bad. Should be i-- at the end, not i++.

for (int i = <str.length()-1; i>=0; i--) {}

Still geting them :(

GetIntFromString.java:7: > expected
		 for (int i = <str.length()-1; i>=0; i--)
		                         ^
GetIntFromString.java:7: ';' expected
		 for (int i = <str.length()-1; i>=0; i--)
		                          ^
GetIntFromString.java:7: not a statement
		 for (int i = <str.length()-1; i>=0; i--)
		                                ^
GetIntFromString.java:7: ')' expected
		 for (int i = <str.length()-1; i>=0; i--)
		                                   ^
GetIntFromString.java:7: ';' expected
		 for (int i = <str.length()-1; i>=0; i--)
		                                        ^
5 errors

Sorry, I'm writing this stuff too fast - I'm actually working on some other stuff over here. :)

try <= instead of =<

Yeah, still the same thing

Am I going to have to actually pay attention to what I'm doing?

grumble

for (int i = str.length()-1; i>=0; i --){}

is what it should be. Now, that should work. i is initialized to the index of the last character in the string, it counts down until it hits zero, and then it stops.

public class junk
{
   public static void main(String[] args)
   {
      String str = "test";
      for (int i= str.length()-1; i>=0; i--)
      {
         System.out.println(str.charAt(i));
      }
   }
}

Still geting them :(

GetIntFromString.java:7: > expected
		 for (int i = <str.length()-1; i>=0; i--)
		                         ^
GetIntFromString.java:7: ';' expected
		 for (int i = <str.length()-1; i>=0; i--)
		                          ^
GetIntFromString.java:7: not a statement
		 for (int i = <str.length()-1; i>=0; i--)
		                                ^
GetIntFromString.java:7: ')' expected
		 for (int i = <str.length()-1; i>=0; i--)
		                                   ^
GetIntFromString.java:7: ';' expected
		 for (int i = <str.length()-1; i>=0; i--)
		                                        ^
5 errors

Your syntax is wrong.
The first part of a For loop (int i = <str.length()-1; part) is the initialization. So you can not use a comparison operator (ie: =<) to assign a value. What you must use is;

for (int i = str.length()-1; i>=0; i--)

I suggest you do some further reading on For Loops. Here's a good place.
http://www.cplusplus.com/doc/tutorial/control/

Do I understand your question right? You just want to convert a string to an integer, right?

You can just use Integer.parseInt();

String aNumber = "1234";
int numberValue = Integer.parseInt(aNumber);

No, I wanted to take each digit of the string and put it in it's own variable. I got it working, without the for loop. You'll see two different ways in this same code to do it, but it's giving me an error saying this below, but it compiles. When I run it, it prints our 1 2 3 4, but still gives me the error.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
public class GetIntFromString {

   public static void main(String[] args) 
	{
 	   String str1 = "1234";  
		String s = "1234";
		
		char [] ch = s.toCharArray();
		
		for (int k = 0; k <= ch.length; k++)
		{
			System.out.println(ch[k]);
		}
		
		int decrease = 48;
		
		 int index1 = str1.charAt(0);
		 int index2 = str1.charAt(1);
		 int index3 = str1.charAt(2);
		 int index4 = str1.charAt(3);
		 
		 int[] index = new int[4];
		 index[0] = index1 - decrease;
		 index[1] = index2 - decrease;
		 index[2] = index3 - decrease;
		 index[3] = index4 - decrease;
	
		for (int i = 0; i <= index.length; i++)
		{
			System.out.println(index[i] + " ");
		}
	}
}
Member Avatar for coil

In line 28, you have the terminating condition i <= index.length . As arrays run from index 0 to index length-1, you should change the inequality sign to strictly less than (<).

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.