forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidate.java
More file actions
54 lines (49 loc) · 1.31 KB
/
Validate.java
File metadata and controls
54 lines (49 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.Scanner;
/**
* Do-while, break, and continue.
*/
public class Validate {
public static double scanDouble() {
Scanner in = new Scanner(System.in);
boolean okay;
do {
System.out.print("Enter a number: ");
if (in.hasNextDouble()) {
okay = true;
} else {
okay = false;
String word = in.next();
System.err.println(word + " is not a number");
}
} while (!okay);
double x = in.nextDouble();
return x;
}
public static double scanDouble2() {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
if (in.hasNextDouble()) {
break;
}
String word = in.next();
System.err.println(word + " is not a number");
}
double x = in.nextDouble();
return x;
}
public static double addNumbers() {
Scanner in = new Scanner(System.in);
int x = -1;
int sum = 0;
while (x != 0) {
x = in.nextInt();
if (x <= 0) {
continue;
}
System.out.println("Adding " + x);
sum += x;
}
return sum;
}
}