This is an automatic message sent to all CS-10 students, Spring 2007
------------------------------
Greetings,
A student asked me today about how to use JOptionPane. Another student
asked about how to convert a String to an int.
Here is an example program. You can cut and paste it on Sample.java to
try it out.
Best,
- Mock
/* We need to import the swing package in order to use JOptionPane easily
* Otherwise, we need to say javax.swing.JOptionPane every time we refer
* to it.
*/
import javax.swing.*;
/* Importing java.util package gives you access to Scanner */
import java.util.*;
public class Sample {
public static void main(String[] args) {
/* An example of how to use the JOptionPane input dialog */
String name = JOptionPane.showInputDialog("What's your name?");
System.out.println("Hello " + name);
/* An example of how to convert a String to an int
* I give you 2 ways (there are more). Both are equally good
* in my opinion.
*/
String s = "15";
/* Way #1: Using Integer.parseInt */
int x = Integer.parseInt(s);
System.out.println("x + 10 = " + (x+10));
/* Way #2: Using Integer.parseInt */
Scanner sScanner = new Scanner(s);
int y = sScanner.nextInt();
System.out.println("y + 10 = " + (y+10));
}
}
No comments:
Post a Comment