Basic Java Language: Difference between revisions
wikademia>Cremisis13 |
wikademia>Cremisis13 |
||
| Line 234: | Line 234: | ||
If, when running, it says invalid class file, perhaps the compiler did not create a file. It might have given error messages. | If, when running, it says invalid class file, perhaps the compiler did not create a file. It might have given error messages. | ||
=Asking the User= | |||
Now, let's go on to asking the user to entire a number and doing calculations on it. Basically: <code>JOptionPane.showInputDialog(null, "Hello. Enter something")</code>. Try putting that in a class (in the main method, of course) and run it. Currently, we can't do anything with it because the value is deleted. | |||
Because what you enter can consist of letters OR numbers, and any length of them, what is "produced" by that is a String. The following will work: <code>String mine = JOptionPane.showInputDialog(null, "Now I can set a String!");</code>. Now lets say that after you get the string you want to print it. Just like regularly, add the following line: <code>System.out.println(mine);</code>. | |||
Now you probably want to be able to enter a number. Java provides a method of changing a String to an int. It is Integer.parseInt(String_Here);. So lets say you want the user to enter a number and you print it. Do: | |||
<pre> | |||
int mine = Integer.parseInt(JOptionPane.showInputDialog(null, "Now I can set an INTEGER!")); | |||
System.out.println(mine); | |||
</pre> | |||
And now, of course, you can do whatever you want with that... | |||
=Exercises= | =Exercises= | ||
A. Create a program that creates a String with the value "ABC". Then print the value using System.out.println(StringIdentifierHere). You could also do System.out.prinln("ABC"), but we are focusing on creating variables. | A. Create a program that creates a String with the value "ABC". Then print the value using System.out.println(StringIdentifierHere). You could also do System.out.prinln("ABC"), but we are focusing on creating variables. | ||