+ 1
How to cast in Java?
Hey all! I have a little question for all of you ^^ Scanner anniversaireJ = new Scanner (System.in); String dateJA = anniversaireJ.nextLine(); jourNaissance= jourNaissance.value Of (dateJA); Here is an extract of code do you fine any error? The debug said that I missed a « ; » but in fine i really don’t think so... Do you have any idea about this? If I well remember the process of cast is: TypeVar1 Var1 = ......; TypeVar2 Var2 = (TypeVar2) Var1; No? Anyway if you have any idea it would be a plesure to talk about that with u ;) Thanks! https://code.sololearn.com/cUb0OHFpNxaY/?ref=app
28 odpowiedzi
+ 1
After you change value Of to valueOf, there are new errors. Those are type problems
+ 1
So, what Integer.parseInt() does is converting a string such as "98" to an int, 98.
+ 1
ok i will try that thanks!
+ 1
I could write the code for you easily, but that wouldn't be helpful, cause you have to learn it haha.
+ 1
String dateJA = anniversaire.nextLine();
Byte.parseByte(dateJA);
jourNaissance= dateJA;
Here a Problem. As I said, parseByte has to assigned to a variable, here I would say, to jourNaissance.
+ 1
So, the Scanner itself is not important, but it's methods. At the moment, you use nextLine() which returns a String. nextByte() should work out just fine.
+ 1
Done ! 🙄
Ok i understand "Line" is for string object only... Thank you very much ! 🙏
So i suppose it's nextShort fort Short, nextLong for Long etc...
+ 1
Exactly
0
First, I would recommend to put your code into code playground, so we can check it out.
Second, you only can cast types which are compatible, such as you can cast everything to Object.
What's not possible is for example casting ints to String. For such problems you have to use methods as valueOf
Third, I'm not sure if it's a typing mistake,but you wrote value Of() instead of valueOf()
0
here it is
ok i’ll try that
0
ok so I’ve tried with ValueOf instead of Value Of and nothing happens.... :/
Yeah of course convert an int into an object String is not that logic but in the other way it seems to be a little more logic right?
0
So you wanna convert an int to String or the other way around?
0
Look at this:
int to String: String.valueOf(yourInt);
String to int:
Integer.parseInt(yourString);
0
I try to create a Scanner in byte in fact
0
can u just explain your code please? i try to understand it but « Integer.parselnt() » is unknown foor me... :/
0
But that's not that important as you use byte
0
Haha i’ve forgot that ^^ so Byte.parseByte() exist? or there is no way and i’ve to convert my varriable into an Int?
0
A few problems:
Use Byte.parseByte(theString) to get a byte value from a string
Create only one Scanner object and just call .nextLine() two or more times
...
0
Still 1 error in output but it’s better!
0
Just delete line 19