Download presentation
Presentation is loading. Please wait.
Published byAdrian Harris Modified over 8 years ago
1
© 2007 Lawrenceville Press Slide 1 Chapter 4 Review Assignment Statement An assignment statement gives a value to a variable. Assignment can take several forms: x = 5; a literal (5) is assigned to x x = y + 2; the value of an expression (y + 2) is assigned to x x = z; the value of another variable ( z ) is assigned to x
2
© 2007 Lawrenceville Press Slide 2 Chapter 4 Variable Assignment A variable can store only one value at any time. int x; x = 5; x = 10; x 5 10 The box starts out empty
3
© 2007 Lawrenceville Press Slide 3 Chapter 4 Primitive Data Types TypeStorage Required int 4 bytes double 8 bytes char 2 bytes boolean 1 bit One byte is 8 bits Like 00010110
4
© 2007 Lawrenceville Press Slide 4 Chapter 4 The Scanner Class Part of the java.util package Type: import java.util.Scanner; At the top of your program to use the Scanner A Scanner object reads in text and numbers Methods include: next() – reads a word nextLine() – read a sentence nextInt() – read a number nextDouble() – read a number nextBoolean() – read true/false close() – stop reading
5
© 2007 Lawrenceville Press Slide 5 ExceptionsExceptions When using the Scanner class, if you tell the program to read the wrong type of data it will generate an error. An exception is an error that happens when the program is running. – –nextLine() can read any kind of data, Strings and numbers, it reads the entire line a person types in – –next() reads just one word – –nextDouble() reads a number with a decimal point – –nextInt() only reads whole numbers – –nextBoolearn() only reads true/false
6
© 2007 Lawrenceville Press Slide 6 Greeting Program Greeting Program This program will ask a person for their name and greet them personally import java.util.Scanner; public class Greeting { public static void main(){ Scanner keyboard = new Scanner(); System.out.print(“Enter your name: “); String name = keyboard.nextLine(); System.out.println(“Hello, “+name); } } To allow people to type in information while a program is running, you need the Scanner The class is called Greeting The method is called main Before you can use the Scanner you have to create a Scanner object This is called a prompt This reads what is typed at the keyboard and stores it in the name variable Print the word Hello followed by the contents of the variable name (+ means concatenation)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.