Sudden JavaStructure of a Java programJava structure and EclipseSimple program outlineCommentsDeclaring variablesSome Java data typesReading in numbersPrintingProgram to double a numberAssignment statementsMethodsMethod types and returnsMethod callsOrganization of a classArithmetic expressionsBoolean expressionsString concatenationif statementsCompound statementswhile loopsThe do-while loopThe for loopParts of the for loopExample for loopsExample: Multiplication tableWhen do you use each loop?The assert statementEnabling assertionsA complete programAnother complete programThe EndJan 18, 2019Sudden Java2Structure of a Java programA program, or project, consists of one or more packagesPackage = directory = folderA package contains one or more classesA class contains one or more fields and methodsA method contains declarations and statementsClasses and methods may also contain commentsWe’ll begin by looking at the “insides” of methods• packages• classes• fields• methods• declarations• statementsProject:3Java structure and EclipseA workspace is where Eclipse keeps projectsWhen you use Eclipse to create a project (a single “program”), it creates a directory with that name in your workspaceWithin the project, you next create a packageFinally, you create a class in that packageFor the simplest program, you need only a single package, and only one (or a very few) classes4Simple program outlineNotes:The class name (MyClass) must begin with a capitalmain and run are methodsThis is the form we will use for nowOnce you understand all the parts, you can vary thingsclass MyClass { public static void main(String[ ] args) { new MyClass().run(); } void run() { // some declarations and statements go here // this is the part we will talk about today }}main methodanother methodCommentsPython: Single-line comments start with #Java: Single-line comments start with //Java: Multi-line comment start with /* and end with */Python: Documentation comments are enclosed in triple quotes, and are put right after the def lineJava: Documentation comments start with /** and end with */, and are put just before the definition of a variable, method, or classDocumentation comments are more heavily used in Java, and there are much better tools for working with them56Declaring variablesIn Python, a variable may hold a value of any typeIn Java, every variable that you use in a program must be declared (in a declaration)The declaration specifies the type of the variableThe declaration may give the variable an initial valueExamples:int age;int count = 0;double distance = 37.95;boolean isReadOnly = true;String greeting = "Welcome to CIT 591";String outputLine;7Some Java data typesIn Java, the most important primitive (simple) types are:int variables hold integer valuesdouble variables hold floating-point numbers (numbers containing a decimal point)boolean variables hold a true or false valueOther primitive types arechar variables hold single charactersfloat variables hold less accurate floating-point numbersbyte, short and long hold integers with fewer or more digitsAnother important type is the StringA String is an Object, not a primitive typeA String is composed of zero or more chars8Reading in numbersFirst, import the Scanner class:import java.util.Scanner;Create a scanner and assign it to a variable:Scanner scanner = new Scanner(System.in);The name of our scanner is scannernew Scanner(...) says to make a new oneSystem.in says the scanner is to take input from the keyboardNext, it’s polite to tell the user what is expected:System.out.print("Enter a number: ");Finally, read in the number:myNumber = scanner.nextInt();If you haven’t previously declared the variable myNumber, you can do it when you read in the number:int myNumber = scanner.nextInt();9PrintingThere are two methods you can use for printing:System.out.println(something);This prints something and ends the lineSystem.out.print(something);This prints something and doesn’t end the line (so the next thing you print will go on the same line)These methods will print anything, but only one thing at a timeYou can concatenate values of any type with the + operatorExample:System.out.println("There are " + appleCount + " apples and " + orangeCount + " oranges.");10Program to double a numberimport java.util.Scanner;public class Doubler { public static void main(String[] args) { new Doubler().run(); } private void run() { Scanner scanner; int number; int doubledNumber; scanner = new Scanner(System.in); System.out.print("Enter a number: "); number = scanner.nextInt(); doubledNumber = 2 * number; System.out.println("Twice " + number + " is " + doubledNumber); }}11Assignment statementsValues can be assigned to variables by assignment statementsThe syntax is: variable = expression;The expression must be of the same type as the variableThe expression may be a simple value or it may involve computationExamples:name = "Dave";count = count + 1;area = (4.0 / 3.0) * 3.1416 * radius * radius;isReadOnly = false;When a variable is assigned a value, the old value is discarded and totally forgotten12MethodsA method is a named group of declarations and statementsvoid tellWhatYearItIs( ) { int year = 2006; System.out.println("Hello in " + year + "!");}We “call,” or “invoke” a method by naming it in a statement:tellWhatYearItIs( );This should print out Hello in 2006!Method types and returnsEvery method definition must specify a return typevoid if nothing is to be returnedEvery method parameter must be typedExample: double average(int[] scores) { … }The return type is double, the parameter type is int[]If a method returns void (nothing), you may use plain return statements in itIf you reach the end of the method, it automatically returnsIf a method returns something other than void, you must supply return statements that specify the value to be returnedExample: return sum / count;1314Method callsA method call is a request to an object to do something, or to compute a valueSystem.out.print(expression) is a method call; you are asking the System.out object to evaluate and display the expressionWhen you call a method, do
View Full Document