Presentation is loading. Please wait.

Presentation is loading. Please wait.

User input We’ve seen how to use the standard output buffer

Similar presentations


Presentation on theme: "User input We’ve seen how to use the standard output buffer"— Presentation transcript:

1 User input We’ve seen how to use the standard output buffer
Via System.out object How can we gather user information during execution? We can ask, during runtime! Use the Scanner class

2 Java input Class Scanner can take text input from many different sources and process it We will use the scanner with System.in Similar to System.out, but reads from standard input Scanner sc = new Scanner(System.in); int i = sc.nextInt(); This code will wait for the user to enter text, then process it, creating an int and assigning it We can prompt before the input with System.out as before Caveat: to use extra utilities, we often have to import them import java.util.Scanner;

3 Modify our HelloWorld class to be a HelloUser class
/** * The HelloUser class prints “Hello, [name]!” * to the console, where the name is gathered * from user input. */ import java.util.Scanner; public class HelloUser { public static void main( String[] args ) { Scanner sc = new Scanner(System.in); System.out.println(“What is your name?”); String name = sc.nextLine(); System.out.println(“Hello, ” + name + “!”); sc.close() // you should close your buffer! }

4 Notes We didn’t actually need to output the first line of text, but it is good user experience We didn’t need to close the scanner, but otherwise, it would have remained open, using resources we don’t need It would automatically close at the termination of the program anyway More information on Scanner class at API docs will be your friend! Note the “Hello, ” + name + “!” part of the program How does it know what to do?! This is an expression Expressions are computations that get calculated during runtime

5 Expressions Expressions involve variables or hard-coded data and evaluate to something specific (they compute things!) They involve operators, and appear similarly to mathematical expressions interest_rate * principal Evaluates to the product of the two numbers System.out.println(“Hello, World!”) Evaluates to nothing, but sends data to the output stream (a + b) * c Parentheses can be used to group expressions, changing order of operation myAge++ Increments myAge and stores it back in the same location, but evaluates to the original value (increments after the evaluation) myAge > yourAge Evaluates to the boolean value true if myAge is more than yourAge and false otherwise

6 operators Arithmetic Addition (+), subtraction(-), division(/), multiplication(*) Binary – take two arguments, on either side (e.g. x * y) Can be used with short, int, long, float, double Operands must be of the same type E.g. if you compute , the 10 is converted to a float (10.0) and then they are added Conversion can happen automatically if it needs to Note: the result will be of the same type as the operands! So 25/3 will give 8 as the answer. The fraction is discarded But try 25.0/3.0 and 25.0/3

7 Assignment Just as when defining a variable, we can assign new values to variables principal = 1000; interest = principal * 0.05; Here, the “=” is actually an operator! As before, it requires type compatibility int a = 10; int b = 20; double c = 5.5; a = c // Causes an error, because information is unintentionally lost c = a + b; // is OK in Java because we can add the “.0” without loss a = (int) c; // is now OK because we told the compiler we do want to // convert down to an int. This is called “type casting”

8 double principal = 1000 double interest_rate = 0
double principal = 1000 double interest_rate = 0.07 double interest interest = interest_rate * principal Notes: First, second, and fourth line are assignment statements They name a variable, and tell the program to assign some value to it Some values are hard-coded and some are derived from other variables The equals sign (=) is called an assignment operator The third line is only a declaration of a new variable Until the fourth line, it has no value The first and second lines declare new variables and assign them values at the same time The fourth line uses previously declared variables Values can be changed later, as seen here Important: the example is not a complete program, but is just to give an idea It could be a valid Java snippet with semicolons (;) on the end of each line

9 Increment and decrement
It is very common to increment or decrement variables E.g. counter = counter + 1; Note that this is not a mathematical statement! There are dedicated operators for this, ++ and -- Usage: Pre-increment/decrement: ++counter and --counter Post-increment/decrement: counter++ and counter-- The difference is that pre evaluates to the new value, where post evaluates to the old value!

10 int a, b; // note the simultaneous declaration
int a, b; // note the simultaneous declaration! int counter = 0; a = counter++; // a now holds 0; counter holds 1; b = ++counter; // b holds 2; counter holds 2; a = counter++ is equivalent to: a = counter; counter = counter + 1; // can also be written as += 1; a = ++counter is equivalent to: counter += 1; // Using the shortcut operator

11 Flow Control Often times, a program needs to make decisions based on the data available For example, if a use is trying to calculate their income tax, their income may be in different tax brackets In a simplified example, we need to capture the logical statement “if you make more than X but less than Y, you pay Z percent tax, and W percent otherwise” Thus, we need to control which actions are taken by the program and which are not, but still be able to account for all possible situations

12 Code block In Java, and many languages, a block is denoted by being enclosed in brackets: { and } { <expressions> } The block-model allows us to group code to be repeated, skipped, and other useful things

13 If statements We have the keywords “if” and “else” to control the flow of our program The “if” statement comes before a logical expression contained in parentheses, which is followed by a code block double principal = 10000; double interest; if (principal > 10000) { interest = principal * 0.05; }

14 If + Else The “if” block may be followed by an “else” keyword, followed by another code block if (principal > 10000) { interest = principal * 0.05; } else { interest = principal * 0.04; }

15 Conditional Operators
true // Always evaluates to true false // Always evaluates to false A == B // Is A "equal to" B? A != B // Is A "not equal to" B? A < B // Is A "less than" B? A > B // Is A "greater than" B? A <= B // Is A "less than or equal to" B? A>=B Is A "greater than or equal to" B?

16 Compound Conditions The && operator between two conditional expressions evaluates to true if and only if both conditionals are true ( 1 > 2 ) && ( myTaxes > 0 ) <expression1> && <expression2> && <expression 3> Evaluates left-to-right, equivalent to (<expression1> && <expression2>) && <expression 3> The || operator evaluates to true if at least one of the expressions is true ( 1 > 2 ) || ( myTaxes > 0 ) <expression1> || <expression2> || <expression 3> Evaluates left-to-right, equivalent to (<expr1> || <expr2>) || <expr3>

17 Loops Used to repeat code Run until condition is met “While” loop
“Do while” loop “For” loop

18 While loops Checks conditional and runs inner code if it is true, then repeats while (<conditional>) { // Code to execute }

19 Do-while loops Similar to while loop, but always runs the inner code at least once, then checks at the end do { // Code to execute } while (<conditional>);

20 Break command ”break” and “continue” commands allow you to abort a loop before it finishes, either stopping regardless of conditionals, or repeat the loop based on the conditional int counter = 0; while(counter < 10){ // repeat until the counter is 10 if ( counter == 5 ){ break; // will stop the loop completely } System.out.println(counter); counter = counter + 1;

21 Continue command int counter = 0;
while(counter < 10){ // repeat until the counter is 10 if ( counter == 5 ){ continue; // will skip further operations and go to loop start } System.out.println(counter); counter = counter + 1;

22 Demo – Iteration Check each integer from 1 to 10. Tell the user if it is even or odd: int counter = 1; while ( counter <= 10 ){ if ( counter % 2 == 0 ){ System.out.println(counter + “ is even.”); } else { System.out.println(counter + “ is odd.”); } Error!

23 For-loop Captures the “counter” idea more succinctly:
for ( ⟨initialization ⟩; ⟨continuation-condition ⟩; ⟨update ⟩ ) { ⟨statements ⟩ } Used for: Iterating objects in a set order Checking array elements (later)

24 For loop parity check for ( int i = 0; i < 10; i++ ){ if ( i % 2 == 0 ){ System.out.println(i + “ is even.”); } else { System.out.println(i + “ is odd.”); }

25 Chained “if” statements
if ( <variable> == <constant 1> ){ <statements> } else if (<variable> == <constant 2> ){ } else if (<variable> == <constant 3> ){ } else { }

26 Switch STatement if ( <variable> == <constant 1> ){
switch ( <variable> ){ case <constant 1>: <statements> break; case <constant 2>: case <constant 3>: default: } if ( <variable> == <constant 1> ){ <statements> } else if (<variable> == <constant 2> ){ } else if (<variable> == <constant 3> ){ } else { }

27 Switch Statements Great for menus The “break” command is optional
Allow the user a multiple-choice option The “break” command is optional If left out, it will “fall” down to the next case and run that code until a ”break” is found

28 Switch Example: Rock, Paper, Scissors
Algorithm: Generate a random integer from 1, 2, or 3 Translate this to “rock”, “paper”, or “scissors” respectively Print the result to the user To get a random integer: Call Math.random() which will return a double uniformly distributed between 0 and 1 Can use that random value in (0,1) with addition and multiplication to change the range and cast to an int


Download ppt "User input We’ve seen how to use the standard output buffer"

Similar presentations


Ads by Google