import javax.swing.JOptionPane;
public class CommonLoopAlgorithms
{
public void computeTotal()
{
double total = 0;
String value;
for (int k = 0; k < 5; k++)
{
value = JOptionPane.showInputDialog("number, please:");
// convert the String from .showInputDialog() to a double:
double number = Double.parseDouble(value);
total = total + number;
}
JOptionPane.showMessageDialog(null, "Total = " + total);
}
public void countMatches()
{
String name = "Joe Biden";
int len = name.length();
System.out.println("len: " + len);
int matches = 0;
char ch; // char is for 1 character
for (int j = 0; j < len; j++)
{ ch = name.charAt(j);
if (ch == 'a')
matches++;
}
JOptionPane.showMessageDialog(null, "Number of matches = " + matches);
}
// continue looping until you find the first lowercase character in the name
public void findFirstMatch()
{
String name = "Kamala Harris";
boolean found = false;
int k = 0;
char ch;
while (! found && k < name.length())
{ ch = name.charAt(k);
if (Character.isLowerCase(ch))
found = true;
else
k++;
}
if (found)
JOptionPane.showMessageDialog(null, "First lowercase letter occurs at position " + k);
else
JOptionPane.showMessageDialog(null, "No lowercase letters.");
}
// prompting until a match is found
public void promptUntilMatch()
{
boolean valid = false;
double input = 0;
String str;
while (! valid)
{ str = JOptionPane.showInputDialog("positive number < 100, please");
input = Double.parseDouble(str);
if (input <= 0 || input >= 100)
JOptionPane.showMessageDialog(null, "Try again");
else
{
valid = true;
JOptionPane.showMessageDialog(null, "Number accepted.");
}
}
}
public void compareAdjacent()
{
String previous, current;
int times = 10;
int k = 0;
int adjacentDuplicates = 0;
previous = JOptionPane.showInputDialog("name, please");
while (k < times)
{
current = JOptionPane.showInputDialog("name, please");
if (current.equals(previous))
{
adjacentDuplicates++;
System.out.println("Adjacent duplicates: " + adjacentDuplicates);
}
previous = current;
k++;
}
JOptionPane.showMessageDialog(null, "Number of adjacent duplicates: " + adjacentDuplicates);
}
public void processInputWithSentinel()
{
String start = "08840";
while ( ! start.equals("0"))
{
start = JOptionPane.showInputDialog("zip code, please");
if ( ! start.equals("0"))
System.out.println(start + " has been accepted.");
}
}
public static void main(String[] args)
{
CommonLoopAlgorithms c = new CommonLoopAlgorithms();
//c.computeTotal();
//c.countMatches();
//c.findFirstMatch();
//c.promptUntilMatch();
//c.compareAdjacent();
c.processInputWithSentinel();
}
}