
-----------------------------------
hamid14
Sun Oct 10, 2010 6:02 pm

Convert * to int
-----------------------------------
Basically I'm trying to give a variable called b, which is a string, a integer value of 1 and be able to add it to another integer

String b = "*";
int i = 0; 

//b should have an intege value of 1, so its basically the same thing as 1, it just has a symbol representing the 1, rather than just typing 1

i + b = 2;


Is this even possible?

-----------------------------------
TerranceN
Sun Oct 10, 2010 8:00 pm

RE:Convert * to int
-----------------------------------
Something like this?


String b = "1";
int i = 0;
i = Integer.parseInt(b) + 1;
		
System.out.println(i);


-----------------------------------
hamid14
Sun Oct 10, 2010 8:02 pm

Re: Convert * to int
-----------------------------------
the string has to be * not 1, it should represent and function as a 1 but appear to the user as a *

-----------------------------------
TerranceN
Sun Oct 10, 2010 8:14 pm

RE:Convert * to int
-----------------------------------
Well if it only has to appear to the user to be all *s, then you can just make a function that creates a string the same length, but all *s.

Something like this:

public static void main (String

Although unless the string with a number in it is input, theres not much point of it being a string anymore.

-----------------------------------
hamid14
Sun Oct 10, 2010 8:19 pm

Re: Convert * to int
-----------------------------------
no thats not it. good try though. IT should be like 1 + * = ** and 2 + * = *** and 3 + * = **** and so on.

-----------------------------------
TerranceN
Sun Oct 10, 2010 8:24 pm

RE:Convert * to int
-----------------------------------
Oh in that case you can just use b.length() to get the number of stars there are.

-----------------------------------
DtY
Mon Oct 11, 2010 1:54 pm

Re: RE:Convert * to int
-----------------------------------
Well if it only has to appear to the user to be all *s, then you can just make a function that creates a string the same length, but all *s.

This really is the best option, store it as a number (because that's what it is), and if you need to display it, convert it to a string, like above, and if you need to get that as input, use another function to convert it back. (you might even consider creating a class to wrap all this.)

If you really don't want to do that, you will still need to use those functions. For reference:
toStar(int) => string
fromStar(string) => int
fromStar(int) => int

And then:
toStar(fromStar("*") + fromStar(1)) = "**";
(fromStar(1) really isn't necessary, but it makes it more symmetrical. In dynamically typed languages this would allow you to use them interchangeably, but I don't know if it has any real advantage in a statically typed language like Java.)
