Skip to content

Instantly share code, notes, and snippets.

@rjlutz rjlutz/Dec2Hex.java
Last active Jun 26, 2017

Embed
What would you like to do?
Loops (Chapter 5) - examples from Liang Intro to Java Comprehensive 10e
import java.util.Scanner;
public class Dec2Hex {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a decimal integer
System.out.print("Enter a decimal number: ");
int decimal = input.nextInt();
// Convert decimal to hex
String hex = "";
while (decimal != 0) {
int hexValue = decimal % 16;
// Convert a decimal value to a hex digit
char hexDigit = (hexValue <= 9 && hexValue >= 0) ?
(char)(hexValue + '0') : (char)(hexValue - 10 + 'A');
hex = hexDigit + hex;
decimal = decimal / 16;
}
System.out.println("The hex number is " + hex);
}
}
public class FutureTuition {
public static void main(String[] args) {
double tuition = 10000; // Year 0
int year = 0;
while (tuition < 20000) {
tuition = tuition * 1.07;
year++;
}
System.out.println("Tuition will be doubled in "
+ year + " years");
System.out.printf("Tuition will be $%.2f in %1d years",
tuition, year);
}
}
import java.util.Scanner;
public class GreatestCommonDivisor {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
k++;
}
System.out.println("The greatest common divisor for " + n1 +
" and " + n2 + " is " + gcd);
}
}
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 100");
int guess = -1;
while (guess != number) {
// Prompt the user to guess the number
System.out.print("\nEnter your guess: ");
guess = input.nextInt();
if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
} // End of loop
}
}
import java.util.Scanner;
public class GuessNumberOneTime {
public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 100");
// Prompt the user to guess the number
System.out.print("\nEnter your guess: ");
int guess = input.nextInt();
if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
}
}
import java.util.Scanner;
public class GuessNumberUsingBreak {
public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 100");
while (true) {
// Prompt the user to guess the number
System.out.print("\nEnter your guess: ");
int guess = input.nextInt();
if (guess == number) {
System.out.println("Yes, the number is " + number);
break;
}
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
} // End of loop
}
}
public class MonteCarloSimulation {
public static void main(String[] args) {
final int NUMBER_OF_TRIALS = 10000000;
int numberOfHits = 0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = Math.random() * 2.0 - 1;
double y = Math.random() * 2.0 - 1;
if (x * x + y * y <= 1)
numberOfHits++;
}
double pi = 4.0 * numberOfHits / NUMBER_OF_TRIALS;
System.out.println("PI is " + pi);
}
}
public class MultiplicationTable {
/** Main method */
public static void main(String[] args) {
// Display the table heading
System.out.println(" Multiplication Table");
// Display the number title
System.out.print(" ");
for (int j = 1; j <= 9; j++)
System.out.print(" " + j);
System.out.println("\n-----------------------------------------");
// Print table body
for (int i = 1; i <= 9; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= 9; j++) {
// Display the product and align properly
System.out.printf("%4d", i * j);
}
System.out.println();
}
}
}
public class PrimeNumber {
public static void main(String[] args) {
final int NUMBER_OF_PRIMES = 50; // Number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
int count = 0; // Count the number of prime numbers
int number = 2; // A number to be tested for primeness
System.out.println("The first 50 prime numbers are \n");
// Repeatedly find prime numbers
while (count < NUMBER_OF_PRIMES) {
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
// Test if number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true, number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
// Print the prime number and increase the count
if (isPrime) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Print the number and advance to the new line
System.out.println(number);
}
else
System.out.print(number + " ");
}
// Check if the next number is prime
number++;
}
}
}
import java.util.Scanner;
public class RepeatAdditionQuiz {
public static void main(String[] args) {
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print(
"What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();
while (number1 + number2 != answer) {
System.out.print("Wrong answer. Try again. What is "
+ number1 + " + " + number2 + "? ");
answer = input.nextInt();
}
System.out.println("You got it!");
}
}
import java.util.Scanner;
public class SentinelValue {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Read an initial data
System.out.print(
"Enter an integer (the input ends if it is 0): ");
int data = input.nextInt();
// Keep reading data until the input is 0
int sum = 0;
while (data != 0) {
sum += data;
// Read the next data
System.out.print(
"Enter an integer (the input ends if it is 0): ");
data = input.nextInt();
}
System.out.println("The sum is " + sum);
}
}
import java.util.Scanner;
public class SubtractionQuizLoop {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; // Number of questions
int correctCount = 0; // Count the number of correct answers
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = ""; // output string is initially empty
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// 2. If number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer �What is number1 � number2?�
System.out.print(
"What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
// 4. Grade the answer and display the result
if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++;
}
else
System.out.println("Your answer is wrong.\n" + number1
+ " - " + number2 + " should be " + (number1 - number2));
// Increase the count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : " wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime - startTime;
System.out.println("Correct count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
}
}
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100)
break;
}
System.out.println("The number is " + number);
System.out.println("The sum is " + sum);
}
}
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue;
sum += number;
}
System.out.println("The sum is " + sum);
}
}
public class TestSum {
public static void main(String[] args) {
// Initialize sum
float sum = 0;
// Add 0.01, 0.02, ..., 0.99, 1 to sum
for (float i = 0.01f; i <= 1.0f; i = i + 0.01f)
sum += i;
// Display result
System.out.println("The sum is " + sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.