/** * Author: Josiah Yoder et al. * Class: SE1011-051 * Lesson: Week 5, Day 1 */ import java.util.Scanner; import java.util.Random; public class Example051_5_1 { public static void main(String[] ignored) { // Example of a very simple Pseudo-random number generator int max = 7; int increment = 4; int current = 0; for(int i=0;i<7;i++) { current+=increment; current%=max; System.out.println("Current value is: "+current); } // Using Java's random number generator Random generator = new Random(); generator.setSeed(0); // This is so it always uses the same sequence. for(int i=0;i<10;i++) { int random = generator.nextInt(10); System.out.println("The "+i+"th random number is "+random); } // Scanner for the following examples Scanner in = new Scanner(System.in); // Raising a number to a power System.out.println("Please enter a number"); double a = in.nextDouble(); System.out.println("Please enter a second number"); double b = in.nextDouble(); System.out.println("a to the b is "+Math.pow(a,b)); // First implementation of single-digit parsing // Checks that result is not -1 to see if it is a character // Works for all bases, but feels backwards. System.out.println("Please enter a number"); String input = in.next(); int len = input.length(); if ( len > 1 ) { System.out.println("Sorry, that number is too long for me!"); } else { char c; c = input.charAt(0); int result = Character.digit(c,16); if(result == -1) { System.out.println("Unrecognized digit"); } else { System.out.println("Your number is "+result); } } // Second implementation of single-digit parsing // Uses Character.isDigit to test if it is a digit. // Cleaner, but works only for base 10 System.out.println("Please enter a number"); String input2 = in.next(); int len2 = input2.length(); if ( len2 > 1 ) { System.out.println("Sorry, that number is too long for me!"); } else { char c; c = input2.charAt(0); if(!Character.isDigit(c)) { System.out.println("Unrecognized digit"); } else { int result2 = Character.digit(c,10); System.out.println("Your number is "+result2); } } } }