+ 2
Any way to assign an integer to a string and call that string to get the integer
I have a problem is there any way to assign an int to a string and call that string so I can get the integer printed to the screen or vice versa? I tried hashmap but you can call only the key so that isn't useful.
15 ответов
+ 3
There are multiple ways of doing this. You can go with something fancy like:
int num = 5;
String text = Integer.toString(num);
System.out.println(text);
//Outputs 5
Or you can go with something simple like:
int num = 5;
String text = "" + num;
System.out.println(text);
//Outputs 5
+ 4
You can do this with a HashMap but obviously it's just for different purposes. HashMap is for maintaining a key=value pair mapping. Meaning that if the String you want the Integer to assign to needs to be part of a group, you can use HashMap.
Let's assume "person" is a HashMap and "Gavin" is one of the keys, you then can assign an integer to that key like 26.
So if you call "Gavin" then you do get the Integer.
person("Gavin");
//Outputs 26
But if you want something more temporary and on the fly then use my first answer posted.
Since I don't know what project you're working on, I can't really advise correctly which method would be best for you.
+ 3
Then use the first answer I posted, very simple and straightforward.
+ 2
So I can't use a hashmap but I can make a class which will do what you said right?
+ 2
I just want to assign an integer to a string and to be able to call either of them to get the assigned value
+ 2
thank you for your time and help
+ 2
one more question can I call the integer and get the string because it doesn't look like it
+ 2
If you want to do it the other way around then you need HashMap <Integer, String>. This means that the keys are integers and the strings are values. So when you call person(26) then you get "Gavin".
+ 2
well if I think about it I can make to hashmaps Ang get away with it right?
+ 2
I have another solution...
+ 2
public class Program
{
public static void main(String[] args) {
//This is an Integer
int num = 5;
//This converts the Integer to a String
String text = ""+num;
//This connverts the String back to an Integer
int num2 = Integer.parseInt(text);
//This prints the second Integer converted from the String
System.out.println(num2);
}
}
//Outputs 5
+ 2
You can use that method and skip the HashMapping
+ 1
Maybe you could do this:
public class Pair{
private int i;
private String s;
public Pair(String s){
this.s=s;
}
public void setI(int i){
this.i=i;
}
public void getOther(int i){
return this.s;
}
public void getOther(String s){
return this.i;
}
}
+ 1
Now I have another problem how can I know if the user inserted either the string or integer. Sorry but I just got my certificate and this is my first code.
+ 1
You may get input as a string. Once you got the input you may check if it's an integer using Integre.parseInt(inputstring). If it's not it will raise a NumberFormatException