6.4.1 讀取輸入數值
一般模型:
boolean done = false;
while (!done)
{
String input = read input;
if (end of input indicated)
done = true;
else
{
process input
}
}
這個模型稱為 "Loop and a half"
File DataSet.java
/**
Computes the average of a set of data values.
*/
public class DataSet
{
/**
Constructs an empty data set.
*/
public DataSet()
{
sum = 0;
count = 0;
maximum = 0;
}
/**
Adds a data value to the data set
@param x a data value
*/
public void add(double x)
{
sum = sum + x;
if (count == 0 || maximum < x) maximum = x;
count++;
}
/**
Gets the average of the added data.
@return the average or 0 if no data has been added
*/
public double getAverage()
{
if (count == 0) return 0;
else return sum / count;
}
/**
Gets the largest of the added data.
@return the maximum or 0 if no data has been added
*/
public double getMaximum()
{
return maximum;
}
private double sum;
private double maximum;
private int count;
}
File InputTest.java
import javax.swing.JOptionPane;
/**
This program computes the average and maximum of a set
of input values.
*/
public class InputTest
{
public static void main(String[] args)
{
DataSet data = new DataSet();
boolean done = false;
while (!done)
{
String input = JOptionPane.showInputDialog("Enter value, Cancel to quit");
if (input == null)
done = true;
else
{
double x = Double.parseDouble(input);
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Maximum = " + data.getMaximum());
System.exit(0);
}
}
6.4.2 String Tokenization
File InputTest.java
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
/**
This program computes the average and maximum of a set
of input values that are entered on a single line.
*/
public class InputTest
{
public static void main(String[] args)
{
DataSet data = new DataSet();
String input = JOptionPane.showInputDialog("Enter values:");
StringTokenizer tokenizer = new StringTokenizer(input);
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken();
double x = Double.parseDouble(token);
data.add(x);
}
System.out.println("Average = " + data.getAverage());
System.out.println("Maximum = " + data.getMaximum());
System.exit(0);
}
}
6.4.3 造訪字串中的字元
- s.charAt(i) 是字串 s 的第 i 個字元
- 用法:
for (int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
process ch
}
- 例題: 數數字串中言母音(vowel)的個數
int vowelCount = 0;
String vowels = "aeiouy";
for (int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if (vowels.indexOf(ch) >= 0)
vowelCount++;
}
- s.indexOf(ch) 是字元 ch 在字串 s 中第一次出現的位置, 假如 ch 不在 s 中則為 -1
6.5 亂數(Random Number)
- 亂數產生器(generator)用法
Random generator = new Random();
int n = generator.nextInt(a);
// 0 <= n < a
double x = generator.nextDouble();
// 0 <= x < 1
- 擲骰子(1 和 6 之間的亂數)
int d = 1 + generator.nextInt(6);
File Die.java
import java.util.Random;
/**
This class models a die that, when cast, lands on a random
face.
*/
public class Die
{
/**
Constructs a die with a given number of sides
@param s the number of sides, e.g. 6 for a normal die
*/
public Die(int s)
{
sides = s;
generator = new Random();
}
/**
Simulates a throw of the die
@return the face of the die
*/
public int cast()
{
return 1 + generator.nextInt(sides);
}
private Random generator;
private int sides;
}
File DieTest.java
/**
This program simulates casting a die ten times.
*/
public class DieTest
{
public static void main(String[] args)
{
Die d = new Die(6);
final int TRIES = 10;
for (int i = 1; i <= TRIES; i++)
{
int n = d.cast();
System.out.print(n + " ");
}
System.out.println();
}
}
Buffon Needle Experiment
Needle Position
- Needle length = 1, distance between lines = 2
- Generate random ylow between 0 and 2
- Generate random angle a between 0 and 180 degrees
- yhigh = ylow + sin(
a)
- Hit if yhigh >= 2
File Needle.java
import java.util.Random;
/**
This class simulates a needle in the Buffon needle experiment.
*/
public class Needle
{
/**
Constructs a needle.
*/
public Needle()
{
hits = 0;
tries = 0;
generator = new Random();
}
/**
Drops the needle on the grid of lines and
remembers whether the needle hit a line.
*/
public void drop()
{
double ylow = 2 * generator.nextDouble();
double angle = 180 * generator.nextDouble();
// compute high point of needle
double yhigh = ylow + Math.sin(Math.toRadians(angle));
if (yhigh >= 2) hits++;
tries++;
}
/**
Gets the number of times the needle hit a line.
@return the hit count
*/
public int getHits()
{
return hits;
}
/**
Gets the total number of times the needle was dropped.
@return the try count
*/
public int getTries()
{
return tries;
}
private Random generator;
private int hits;
private int tries;
}
File NeedleTest.java
/**
This program simulates the Buffon needle experiment
and prints the resulting approximations of pi.
*/
public class NeedleTest
{
public static void main(String[] args)
{
Needle n = new Needle();
final int TRIES1 = 10000;
final int TRIES2 = 100000;
for (int i = 1; i <= TRIES1; i++)
n.drop();
System.out.println("Tries / Hits = "
+ (double)n.getTries() / n.getHits());
for (int i = TRIES1 + 1; i <= TRIES2; i++)
n.drop();
System.out.println("Tries / Hits = "
+ (double)n.getTries() / n.getHits());
}
}