Computer Programming Methodology Input and While Loop COS 130 Computer Programming Methodology Input and While Loop
Demo Input Program
New Issues How to read data into the program How many times to loop In this case from the key board How many times to loop Don’t know in advance how many numbers the user will type in How to go between characters and int
How to read data – Scanner one of many possibilities import java.util.Scanner; public class Avg { public static void main(String args[]) { Scanner kb = new Scanner(System.in); int num = 0; double sum = 0; int cnt = 0; // more stuff . . . while(num != -1) { System.out.print("enter number: "); num = kb.nextInt(); } This finds the library This creates a Scanner object This specifies the keyboard or redirected file Reads and converts characters to int
Open Loop - while (not counted) while(num != -1) { // do stuff }
Open Loop - while (not counted) boolean done = false; while(!done) { // do stuff }
while can count too int cnt = 0; while(cnt < 10) { // do stuff cnt = cnt + 1; } for(int cnt = 0; cnt < 10; cnt = cnt + 1) { // do stuff }
When to use which loop for – use when the number of repeations is known before the loop starts while – use when the number of repeations is not known before the loop starts
Another way to convert string to int All Java primitives (int, double, etc.) have a corresponding “wrapper” class which contain “helper” methods. int -> Integer double -> Double long -> Long boolean -> Boolean
Another way to convert string to int int num = Integer.parseInt(“123”); double num = Double.parseDouble(“1.23”);
Example of use String word = kb.next(); if("quit".equals(word)) { // code to quit } else { num = Integer.parseInt(word); }
Class vs. Object Notice the difference between: String name = “John Doe”; int len = name.length(); And int num = Integer.parseInt(“123”);