Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Agenda For April 2 1. PowerPoint Presentation on converting a String into a number. http://members.shaw.ca/TextToNumber.ppt 2. Finish off ALL Mastery Questions. 3. Start Unit 6 Exercise. Converting A String To a Number Suppose you have declared and initialized a TextField called myTextField. Suppose you would like to retrieve the text information from this textfield and do some mathematical calculations using its value. In order to do this, you must perform the steps shown in the following slide. Converting A String To a Number Cont. 1. Decide what type of number (int or double) you will be storing in the textfield and declare a new variable of that type. 2. Obtain the information from the textfield using the method getText() and store it as a String variable. 3. Then use any one of the following methods to convert the String into a number. (a) Integer.valueOf(someString).intValue() (b) Double.valueOf(someString).doubleValue() 4. Perform your mathematical computation using the number value you obtained in step 3. public class Gui extends Applet { TextField myTextField; public void init() { setLayout(null); myTextField = new TextField(); myTextField.setBounds(10, 50, 100, 20); add(myTextField); myTextField.setText(“5”); } public void myMethod() { // Step 1: declare a new variable int num; // Step 2: store the text in a string variable String wordNum = myTextField.getText(); // Step 3: store the number value inside your variable num = Integer.valueOf(wordNum).intValue(); // Step 4: use your variable in a calculation num = num + 1; } } Outputting Numbers In a TextArea The two methods used for placing text in a TextArea only accept variables of type String. Recall that these methods are: 1. setText(String) 2. append(String) In order to output a number (integer or double value) to a TextArea we use the same trick that was used to draw a number to the screen. An example is shown on the following slide. import java.awt.*; import java.applet.*; public class Gui extends Applet { TextArea myTextArea; public void init() { setLayout(null); myTextArea = new TextArea(); myTextArea.setBounds(25, 50, 150, 100); add(myTextArea); myMethod(); } public { int int int void myMethod() num1 = 5; num2 = 3; num3 = num1 + num2; myTextArea.setText(“” + num1); myTextArea.append(“ + ” + num2 + “ = ” + num3); } }