Download presentation
Presentation is loading. Please wait.
Published byClemence Leslie Baker Modified over 9 years ago
1
1 Week 2 Variables, output, and input Semester 1 2014-2015
2
2 Last week on 4CS001 …..
3
3 Structure of a Java Program public class OutputDemo { public static void main(String[] args) { System.out.print( "What a wonderful world" ); System.out.println( " it is" ); } // end main } // end OutputDemo A Java program is defined in a class. You can call classes any name you wish but must start with a letter and consist of only letters and digits (no spaces). The class name must be identical to the name of the file you save it in. Below is the file OutputDemo.java The contents of the class must be enclosed in braces { } A class definition begins with 2 keywords
4
4 Structure of a Java Program public class OutputDemo { public static void main(String[] args) { System.out.print( "What a wonderful world" ); System.out.println( " it is" ); } // end main } // end OutputDemo Execution starts from the main method. The first line of the main method must look like this. The contents of the main method must be enclosed in braces { } Methods contain a statement sequence. Each statement ends with a semi colon; Statement sequence. Indentation is important to make the code easier to read.
5
5 You ran this program public class OutputDemo { public static void main(String[] args) { System.out.print( "What a wonderful world" ); System.out.println( " it is" ); } // end main } // end OutputDemo Remember indentation is important to make the code easier to read.
6
6 Variables and Calculations Variables are used to store data in memory. Each variable must have: –a data type –a unique identifier (or name) –a value Every variable can store just one item of data of the specified type. int x = 10; data typename value
7
7 Variables, Input, and Output
8
8 Learning Outcomes Understand how to make programs produce output. –System.out.print –System.out.println –JOptionPane.showMessageDialog Gain practical experience of writing programs. –Finding syntax errors in a program (e.g. spelling mistakes which prevent the program from compiling successfully)
9
9 Variables Assignment may be used to transfer values between variables. Literals are used to include exact values in programs. int x = 10; int y = x; int is the data type used. int x is called a variable declaration. x and y are variables of type int – they can store whole numbers. 10 is an example of an integer literal. The first line copies the value10 into the variable x. The second line copies the contents of the x variable to the y variable. After these lines have been executed, both x and y will store 10. Using the equals operator like this is called assignment
10
Somewhere in memory.... int x Int x = 10 int y int y = x (put whatever is in ‘x’ into ‘y’) 10 I’d better reserve a space in memory, which will take an integer value, and I’ll call the space ‘x’ X ‘ ready for an int’ X 10 Y ‘ ready for an int’ Y 10
11
11 Names for classes, variables, methods in Java Must begin with an alphabetic character Can contain upper and lower case letters, numbers, _ and $ Some names are reserved Everything in Java is case sensitive –face is a valid identifier –1face is not valid, it begins with a number –face% is not valid because % is not allowed –face3 is valid –Face is valid but is not the same as face Names in Java
12
12 Variables Each line of code here is called a statement Semicolons ; are used to separate statements. The variable declarations can be made separately. Variables must be declared before they are used. int x = 10; int y = x; These programs are equivalent – they all do the same. int x; x = 10; int y; y = x; int x; int y; x = 10; y = x; int y, x=10; y = x;
13
13 Assignment Statements The general form of assignment is An expression can be: –a variable, or a literal, or –a combination of variables and literals and operators. variableName = expression; int x = 10; int y, z; y = x + 6; z = 2 * y; z = z + x; What is stored in z at the end? Operators + addition - subtraction * multiplication / division x y z 10 16 32 42
14
14 Variables How many values can one variable store? How do we transfer a value from one variable to another ? Which of these words are valid variable names in Java? orange orange2 orange 2 2orange myOrange my Orange my_orange my-orange my$orange my&orange MyOrange class public static Use an assignment statement. For example: int y = x; Only 1 at a time
15
15 Variables How many values can one variable store? How do we transfer a value from one variable to another ? Which of these words are valid variable names in Java? orange orange2 orange 2 2orange myOrange my Orange my_orange my-orange my$orange my&orange MyOrange class public static Use an assignment statement. For example: int y = x; Only 1 at a time
16
16 Variables Which of these code fragments are valid variable declarations and assignment statement combinations? int x = 10; int y = x; int x; x = 10; y = x; int x int y; x = 10; y = x; int y, x; x = 10; y = x; int x; int y; x = 10 y = x; int y, x; x = 10, y = x; int y = 10, x = 10; int x int y x = 10 y = x int x; int y; x = 10; y = x; int y, x; x = 10; z = x; int x, y, z; x = y = 10; z = x;
17
17 Variables The pink boxes indicate which are not valid declarations and assignment statements. int x = 10; int y = x; int x; x = 10; y = x; int x int y; x = 10; y = x; int y, x; x = 10; y = x; int x; int y; x = 10 y = x; int y, x; x = 10, y = x; int y = 10, x = 10; int x int y x = 10 y = x int x; int y; x = 10; y = x; int y, x; x = 10; z = x; int x, y, z; x = y = 10; z = x;
18
18 Assignment Statements Which of these assignment statements are not valid? x = 10; 10 = x; x = 10; y = 20 / 2; x = 10; y = x + x; x = 10, y = x; y = 10 + x / 2 - 3; x = 10 y = x y = 6; y = x; x = 10, y = x / 2; y = 10 + x / 2 – 3 * z; x = 10; y = x / x;
19
19 Assignment Statements The pink boxes indicate which are not valid declarations and assignment statements. x = 10; 10 = x; x = 10; y = 20 / 2; x = 10; y = x + x; x = 10, y = x; y = 10 + x / 2 - 3; x = 10 y = x y = 6; y = x; x = 10, y = x / 2; y = 10 + x / 2 – 3 * z; x = 10; y = x / x;
20
20 BODMAS The order of precedence is : Bracketed expressions first then Orders (i.e. powers) then Divisions & Multiplications (l to r) then Additions & Subtractions (l to r). Often remembered by BODMAS. (alternatives are BIDMAS or BEDMAS with I for “indices” or E for “exponents”). e.g. 4 + 2 * 3 = 10, not 18
21
21 Remember this program? public class Arithmetic { public static void main(String [] args) { int x = 7; int y = 6; int z = x * y; System.out.print( "The answer is " + z); } // end main } // end Arithmetic During your workshop time today try changing the program so that it prints out: (x + y) * 2 and then try x + y * 2 Remember indentation is important to make the code easier to read. Do you expect the answer to be different? Use the + sign to separate items that you want to print using the same print statement.
22
22 Integer & String Integer ( int ) means whole number –e.g. how many holes were dug (4) –e.g. how many exams you passed (8) –There are no decimal points or decimal places Real (double) means not a whole number –e.g. price is £3.75 –e.g. average mark is 80.3 Text (String) is a data type for storing text. –Literals must be enclosed in double quotes String someWords = "Hello Java Fan"; String moreWords; moreWords = someWords;
23
23 Combining Strings Uses the + operator to join together 2 strings. + can be used to convert numbers to text and concatenate them on the strings. Hello Java Fan is stored in the wholeThing variable The special number is 42 is stored in the allMessage variable String firstPart = "Hello "; String secondPart = "Java " + "Fan"; String wholeThing = firstPart + secondPart; int x = 42; String firstPart = "The special number is "; String allMessage = firstPart + x;
24
24 Output System.out.println outputs a string to the console window and moves down to the next line. System.out.print is similar, but does not move down to the next line. System.out.println("Hello Java Fan"); String a = "Hello "; String b = "Java fan"; System.out.print(a); System.out.println(b); String a = "Hello "; String b = "Java fan"; System.out.println(a+b); 3 ways to print the same thing
25
25 Output print vs println public class OutputDemo1 { public static void main(String[] args) { System.out.println( "Java" ); System.out.println( "is" ); System.out.println( "fun" ); } Java is fun public class OutputDemo2 { public static void main(String[] args) { System.out.print( "Java" ); System.out.print( "is" ); System.out.print( "fun" ); } Javaisfun Using println moves down to new line after printing The text to be printed is between quotes Remember indentation is important to make the code easier to read.
26
26 Output of Variables public class Stuff { public static void main(String[] args) { int d = 360; String text = "circle" ; System.out.println( "There are " + d + " degrees in a " ); System.out.println(text); } // end main } // end Stuff There are 360 degrees in a circle As well as text included in quotation marks, the print commands can also output variables How can we change this program to make all the output appear on one line? Remember indentation is important to make the code easier to read.
27
27 Output using JOptionPane A JOptionPane is like a dialog box window that you can use to output data to in a similar way to System.out.print import javax.swing.JOptionPane; public class GraphicHello { public static void main(String[] args) { JOptionPane.showMessageDialog(null,"Hello 4CS001 Student" ); } // end main } // end GraphicHello
28
28 Input using JOptionPane We have looked at output System.out.println( " Hello " ); JOptionPane.showMessageDialog(null, " Hello " ); Most programs also require some kind of user input – keyboard, mouse-click This example uses keyboard input to a dialog box JOptionPane.showInputDialog(null, " Enter your first integer " );
29
29 Using JOptionPane for input The user enters an integer and clicks ok The code fragment causes a dialog box to appear with a prompt (“Enter your first integer”) and an empty field for input. JOptionPane.showInputDialog(null,"Enter your first integer");
30
30 Converting Strings to Numbers JOptionPane can only input to a String variable. In order to do numeric operations, a string must be converted to a number (e.g. int or double) String x = "35"; String y = "6"; x + y356 not 41
31
31 Converting Strings to Integers public class StringToInteger { public static void main(String[] args) { String firstString = "123" ; String secondString = "27" ; int firstNumber = Integer.parseInt(firstString); int secondNumber = Integer.parseInt(secondString); int result = firstNumber + secondNumber; System.out.println( "result = " + result); } // end main } // end StringToInteger convert strings to integers Double.parseDouble is the equivalent for converting to doubles instead of integers. If the string to be converted does not look like a number, a runtime error will occur - don't worry about it - we will return to this
32
32 Importing JOptionPane To use JOptionPane we need an import statement (to import the JOptionPane class from the swing library) import javax.swing.JOptionPane; public class Add { public static void main (String[] args){ String string1 = JOptionPane.showInputDialog(null, "Enter first integer" ); String string2 = JOptionPane.showInputDialog(null, "Enter second integer" ); int firstNum = Integer.parseInt(string1); int secondNum = Integer.parseInt(string2); int result = firstNum + secondNum; JOptionPane.showMessageDialog(null, "The sum of " + firstNum + " and " + secondNum + " is " + result); } As an exercise try missing out the import and see what compiler error you get.
33
33 A Syntactically Incorrect Program pulic class ExerciseA public static void main(String[] args) [ int secondNumber; String a = "universe "; int firstNumber = 13 Strong someWords = "and everything ; String x = "the "; String variable55 = "is "; String z = x + a; secondNumber = 29; system.out.print("The answer to life ", z); System.out.print(someWords, variable5); int thirdNumber = secondNumber + firstnumber; System.out.pr1ntln(thirdNumber); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 How many mistakes can you see? Write them down as you spot them.
34
34 A Syntactically Incorrect Program How can we be sure we have found all the mistakes? Copy the code, paste it into your program editor, and try running it.
35
A Syntactically Incorrect Program Errors are circled below 35 pulic class ExerciseA public static void main(String[] args) [ int secondNumber; String a = "universe "; int firstNumber = 13 Strong someWords = "and everything ; String x = "the "; String variable55 = "is "; String z = x + a; secondNumber = 29; system.out.print("The answer to life ", z); System.out.print(someWords + variable5); int thirdNumber = secondNumber + firstnumber; System.out.pr1ntln(thirdNumber); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 missing wrong character wrong spelling
36
36 ErrorDescriptionFix 1Keyword “public” spelt wrongChange “pulic” to “public” 2{ missingAdd { at the end of the line 3[ wrong bracketReplace [ with { 4missing ;Add ; at end of the line 5String spelt wrongReplace Strong with String 6" missingAdd " after everything and before ; 7system lower case SReplace system with System 8Missing +Replace, with + 9variable5 spelt wrongReplace variable5 with variable55 10firstnumber spelt wrongReplace firstnumber with firstNumber 11println spelt wrongReplace pr1ntln with println Explain the errors you find
37
37 Programming Task The friendly station announcer has just announced that your train is going to be 13445 seconds late. You need to work out in understandable terms what that actually means. You assume this is going to be quite a long time so you open up your laptop to write a program to convert the 13445 seconds into hours, minutes and seconds.
38
Developing the Algorithm This is similar to exercise 4 from last week’s homework: How many seconds are there in a minute? How many seconds are there in an hour? Algorithm: 1. totalTime = the number of seconds (13445) 2. hours = totalTime divided by 3600 (totalTime/3600) 3. remainder = remainder of totalTime divided by 3600 (totalTime % 3600) 4.minutes = remainder divided by 60 (remainder/60) 5. seconds = remainder of remainder divided by 60 (remainder % 60) 6.output hours, minutes, and seconds 38 60 3600
39
39 Homework for this week You should have already read Chapters 1 to 3 of Currie –Covers material related to this session –Try the programming exercises –Answer the review questions –Use books and the Internet to find better explanations of things that Currie does not explain well –Bring your problems to the session next week We will assume that you have done this Read chapter 4 of Currie Make a list of things you don't understand and bring them to the next session. Read the extra material in this lecture on Wolf before next week Attempt the new Jafa exercises Finish the workshop for week 2 Do the algorithm exercises from Worksheet 2 (on paper).
40
Workshop Exercises Log onto Wolf. If you have not finished the Week 1 Workshop exercises then finish those first. (You really should have done them by now) Find the Week 2 folder. Find Workshop 2 and follow the instructions. 40
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.