Download presentation
Presentation is loading. Please wait.
Published byRandell Bennett Modified over 6 years ago
1
Computer Programming Methodology Input and While Loop
COS 130 Computer Programming Methodology Input and While Loop
2
Demo Input Program
3
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
4
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
5
Open Loop - while (not counted)
while(num != -1) { // do stuff }
6
Open Loop - while (not counted)
boolean done = false; while(!done) { // do stuff }
7
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 }
8
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
9
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
10
Another way to convert string to int
int num = Integer.parseInt(“123”); double num = Double.parseDouble(“1.23”);
11
Example of use String word = kb.next(); if("quit".equals(word)) {
// code to quit } else { num = Integer.parseInt(word); }
12
Class vs. Object Notice the difference between: String name = “John Doe”; int len = name.length(); And int num = Integer.parseInt(“123”);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.