代写代考 COMPSCI4039: Programming

COMPSCI4039: Programming
Lecture 3: Comments, Conditions and keyboard input

What you can do by now

Copyright By PowCoder代写 加微信 powcoder

¡ñ Create projects and write programs in Eclipse
¡ñ Run the programs
¡ñ Fix errors (probably the same ones over and over
and over again!)
¡ñ Declare and assign values to variables
¡ñ Print text (and other variables)
¡ñ Organise code into methods
Not bad for a couple of days…today we will see how to make our programs change their behaviour based on data stored in variables…but first, comments

This video
¡ñ Comments ¡ñ Conditions:
¡ð Else if

Others need to understand your code
¡ñ Get into the habit of commenting your code
¡ð Add comments to explain what it does, how it does it
¡ð This will also help you to learn
public class Comments {
public static void main(String[] args) {
// this is a single line comment
We can also make larger block comments like this

Conditions
Often we will want our programs to take actions that depend on the data stored in variables.
We can achieve this using if, else, and else if
Here¡¯s a simple example – what do you think will happen?
public class Conditions {
public static void main(String[] args) {
int age = 14; // try 18 if(age < 17) { System.out.println("Too young to drive a car"); } Curly brackets are not essential ¡ñ If you only have one line of code to run if the condition is true you can remove the curly brackets. ¡ñ BUT: it is dangerous...you might forget to put them back later when you realise you need an extra line in there.... if(age < 17) System.out.println("You are too young to drive a car"); Conditions ¡ñ 100) {
System.out.println(“Probably too old to drive safely”); } else {
System.out.println(“OK to drive”); }

Other operations
We have seen < (less than) and > (greater than)
Other options are:
¡ð == (equals..note it¡¯s two = together!)
¡ð != (not equals)
¡ð >= (greater than or equal to)
¡ð <= (less than or equal to) And we can string operations together using && (and; both conditions have to be true) and || (or; either condition has to be true) public class Conditions { public static void main(String[] args) { int age = 14; // try 18 if(age < 17 || age > 100) {
System.out.println(“Not suitable for driving”); } else {
System.out.println(“OK to drive”); }

More than one way to do a condition
public class Conditions {
public static void main(String[] args) {
int age = 14; // try 18 if(age < 17 || age > 100) {
System.out.println(“Not suitable for driving”); } else {
public class Conditions {
public static void main(String[] args) {
int age = 14; // try 18 if(age >= 17 && age <= 100) { System.out.println("OK to drive"); } else { System.out.println("OK to drive"); }} Satisfy yourself that these two programs are equivalent... System.out.println("Not suitable for driving"); Lots of else if ¡ñ Output here will be: ¡ð Grade=C ¡ñ In this example testscore also satisfies the condition (testscore >=60)
¡ñ …but as soon as one of the conditions is
satisfied, it doesn¡¯t bother checking any others.
int testscore = 76; char grade;
if (testscore >= 90) {
grade = ‘A’;
} else if (testscore >= 80) {
grade = ‘B’; }elseif(testscore>=70){
grade = ‘C’;
} else if (testscore >= 60) {
grade = ‘D’;
grade = ‘F’; }
System.out.println(“Grade = ” + grade);
Example from
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
class IfElseDemo {
public static void main(String[] args) {

Boolean variables
¡ñ Variables of boolean type can take two values: true or false
¡ñ We can assign values to them like this:
¡ð booleanjavaIsGreat=true;
¡ñ We can also assign values from the outcome of logical expressions:
¡ð BooleanokToDrive=age>=17&&age<=100; ¡ñ Boolean variables can also be used in if statements: public class Conditions { public static void main(String[] args) { int age = 14; // try 18 boolean okToDrive = age >= 17 && age <= 100; if(okToDrive) { System.out.println("OK to drive"); } else { System.out.println("Not suitable for driving"); } ¡ñ The exclamation mark (!) means logical not ¡ñ Performs a logical inverse ¡ð !true (not true) is the same as false ¡ñ Note the extra brackets in the first ¡ð Without them Java would try and interpret the expression as... ¡ð (!a)>=17
¡ð which will throw an error (cannot perform not on an integer)
public class Not {
public static void main(String[] args) {
int age = 14;
if(!(age >= 17)) { // note the extra brackets
System.out.println(“Too young to drive”); }
boolean a = false; if(!a) {
System.out.println(“a is false”); }

COMPSCI4039: Programming
Lecture 3: Comments, Conditions and keyboard input

Comparing String variables
¡ñ What do you think this program should output?
public class StringComparison {
public static void main(String[] args) {
String a = “Hello”; String b = “Hel”; b += “lo”; if(a==b) {
System.out.println(“Success!”); }else {
System.out.println(“Failure!”); }

¡ñ We will understand this when we learn about objects in week 2.
¡ñ Note that this makes it looks like == is ok, but it isn¡¯t!
public class StringComparison {
public static void main(String[] args) {
String a = “Hello”; String b = “Hello”; if(a==b) {
System.out.println(“Success!”); }else {
System.out.println(“Failure!”); }

¡ñ All Strings have a method called equals which we use like this:
¡ð Note the full stop ¡®.¡¯ – we will cover the meaning of this when we learn about objects
public class StringComparison {
public static void main(String[] args) {
String a = “Hello”; String b = “Hel”; b += “lo”; if(a.equals(b)) {
System.out.println(“Success!”); }else {
System.out.println(“Failure!”); }
¡ñ To check if something is not equal you would use: ¡ð if(!a.equals(b)) i.e. if not a == b

COMPSCI4039: Programming
Lecture 3: Comments, Conditions and keyboard input

Class exercise – leap years
¡ñ Rules for determining if a year is a leap year are complicated
¡ñ A year is a leap year if:
¡ð It is divisible by 4
¡ð But if its is also divisible by 100 it isn¡¯t
¡ð …unless it is divisible by 400
¡ñ Assuming you have an integer variable called year (e.g. int year = 2018), write a series of if elseif else statements to set a boolean variable isLeapYear to true or false
¡ñ Note:(n % 4 == 0)istrueifnis divisible by4
¡ñ Implement your solution in today¡¯s lab…

Aside – testing
¡ñ It¡¯s good for programs to work properly
¡ñ It¡¯s not necessarily easy to make them do so
¡ñ Thorough testing is a key part of software
development
¡ñ Try and develop a ¡®testing¡¯ mindset:
¡ð How can I convince myself that this program works
¡ð What are good inputs to check (test cases)
¡ñ Can you think of some good test cases for the leap year code?

Keyboard input
¡ñ It¡¯s more interesting to write programs that act upon some user input
¡ñ Most modern programs use Graphical User Interfaces (GUIs)
¡ð We¡¯ll get to them later
¡ñ For now, we¡¯ll work with keyboard input

Keyboard input
¡ñ New things:
¡ð The import command
¡ð The Scanner ¡ð System.in
¡ñ Let¡¯s look at them one by one…
import java.util.Scanner;
public class KeyboardInput {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println(“Please enter your name, followed by return: “); String name = s.nextLine();
System.out.println(“Hello ” + name);

¡ñ Java has lots and lots and lots of useful classes that you can use in your programs.
¡ñ Some of them are available by default (System.out)
¡ñ Some of them have to be imported
¡ñ The line:
¡ð importjava.util.Scanner;
¡ñ Tells Java that we want to use the Scanner class (part of
a group of classes known as util)
¡ñ Eclipse can help you add these where necessary

Scanner and System.in
¡ñ We can think of System.in like a storage locker with a door at the front and the back.
¡ñ We can open the door and take out what¡¯s in there.
¡ñ When a key is pressed on the keyboard, the system
puts that character in the box (from the back)
¡ñ System.in.read() is a method that looks in the box
and takes out what is in there.
¡ð If the box is empty, it waits until something turns up (waits for a
key to be pressed)
¡ñ It would be tedious to use this directly for input
¡ð “Java has lots and lots and lots of useful classes that you can
use in your programs¡±
¡ð Scanner is one such thing, and it makes our life easier…

Scanner and System.in
¡ñ Scanner shields us from directly working with individual key presses
¡ñ Scanner has lots of useful methods:
¡ð nextLine() collects all key presses until the user presses return and packages them up into a
import java.util.Scanner;
public class KeyboardInput {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println(“Please enter your name, followed by return: “); String name = s.nextLine();
System.out.println(“Hello ” + name);

The steps in that program
¡ñ Import Scanner (done outside the class)
¡ñ Make a Scanner (called s) that checks System.in
¡ð Scanners can work with all sorts of things
¡ñ Print out a message
¡ñ Call the nextLine method for our Scanner (s.nextLine()) to wait for the user
input (until they press return)
¡ñ The resulting String is stored as name
¡ñ Print out a message

More Scanner methods
¡ñ The best way to understand a Scanner is to make one with a String instead of System.in (see below)
¡ñ The next() method returns the next token which by default is a series of characters separated by white-space (a space or a tab) or a new line.
¡ñ Progressively move through a String, extracting the individual components
¡ñ Other methods, e.g. nextInt() extract the next token and try and convert it
to an integer
import java.util.Scanner; public class ScannerFun {
public static void main(String[] args) {
String testString = “Hello, my name is Simon”; Scanner s = new Scanner(testString); System.out.println(s.next()); // Hello, System.out.println(s.next()); // my

COMPSCI4039: Programming
Lecture 3: Comments, Conditions and keyboard input

Special characters
¡ñ You¡¯re familiar with characters like ¡®a¡¯, ¡®b¡¯, ¡®2¡¯,
¡ñ But maybe less so with: ¡ð ¡®\t¡¯ tab
¡ð ¡®\n¡¯ newline
¡ñ Special characters start with a ¡®\¡¯: this tells Java that the
next letter is something special.
¡ñ We can insert these in Strings if we like:
¡ð System.out.println(¡°Hello\nGoodbye¡±); // prints
Goodbye on the next line
¡ð Note that System.out.println(a) prints out: a + ¡®\n¡¯
¡ð System.out.print() doesn¡¯t add the ¡®\n¡¯

Reading an int from the keyboard
¡ñ All looks as expected
¡ñ Except the extra s.nextLine()?
import java.util.Scanner;
public class ScannerFun {
public static void main(String[] args) {
Scanner s = new Scanner(System.in); System.out.println(“Please enter your age:”);
int age = s.nextInt();
s.nextLine();
System.out.println(“You are ” + age + ” years old!”); System.out.println(“Do you like being so old?”); String answer = s.nextLine();

Why the extra nextLine()
If we remove it…
Initially, Scanner is empty
Scanner after user has typed 38 and pressed enter (the new line character is included!):
import java.util.Scanner;
public class ScannerFun {
public static void main(String[] args) {
Scanner s = new Scanner(System.in); System.out.println(“Please enter your age:”);
int age = s.nextInt();
System.out.println(“You are ” + age + ” years old!”); System.out.println(“Do you like being so old?”); String answer = s.nextLine();
Scanner after Java has extracted next integer:
Scanner when we call nextLine() again:
We get an empty line (ended by the \n)
An extra nextLine() after nextInt() removes the extra \n and ensures that answer includes the new response.

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com