Programming01_chapter0&1
- 格式:pdf
- 大小:1.43 MB
- 文档页数:53


Chapter 2-7 Structural ProgrammingIntroducing Programming with anExampleListing 2.1 Computing the Area of aCircleThis program computes the area of thecircle.ComputeAreaRunpublic class ComputeArea {/** Main method */public static void main(String[] args) {double radius;double area;// Assign a radiusradius = 20;// Compute areaarea = radius * radius * 3.14159;// Display resultsSystem.out.println("The area for the circle of radius " + radius + " is " + area);}}no value radiusallocate memoryfor radiuspublic class ComputeArea { /** Main method */public static void main(String[] args) {double radius;double area;// Assign a radiusradius = 20;// Compute areaarea = radius * radius * 3.14159;// Display resultsSystem.out.println("The area for the circle of radius " + radius + " is " + area);}}no value radiusmemoryno value areaallocate memoryfor areapublic class ComputeArea { /** Main method */public static void main(String[] args) {double radius;double area;// Assign a radiusradius = 20;// Compute areaarea = radius * radius * 3.14159;// Display resultsSystem.out.println("The area for the circle of radius " + radius + " is " + area);}}20radiusno value areaassign 20 to radiuspublic class ComputeArea { /** Main method */public static void main(String[] args) {double radius;double area;// Assign a radiusradius = 20;// Compute areaarea = radius * radius * 3.14159;// Display resultsSystem.out.println("The area for the circle of radius " + radius + " is " + area);}}20radiusmemory1256.636areacompute area and assign itto variable areapublic class ComputeArea { /** Main method */public static void main(String[] args) {double radius;double area;// Assign a radiusradius = 20;// Compute areaarea = radius * radius * 3.14159;// Display resultsSystem.out.println("The area for the circle of radius " + radius + " is " + area);}}20 radiusmemory1256.636 areaprint a message to the consoleReading Input from the Console1. Create a Scanner objectScanner input = new Scanner(System.in);2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(),nextDouble(), or nextBoolean()to obtain to a string, byte, short, int, long, float, double, or boolean value. For example,System.out.print("Enter a double value: ");Scanner input = new Scanner(System.in);double d = input.nextDouble();ComputeAreaWithConsoleInput RunComputeAverage RunIdentifiers☞An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).☞An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit.–An identifier cannot be a reserved word. (See Appendix A,“Java Keywords,” for a list of reserved words).☞An identifier cannot be true, false, ornull.☞An identifier can be of any length.Constantsfinal datatype CONSTANTNAME = VALUE;final double PI = 3.14159;final int SIZE = 3;Numerical Data TypesName Range Storage Size byte –27 (-128) to 27–1 (127) 8-bit signed short –215 (-32768) to 215–1 (32767) 16-bit signed int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed long –263 to 263–1 64-bit signed(i.e., -9223372036854775808to 9223372036854775807)f loat Negative range: 32-bit IEEE 754-3.4028235E+38 to -1.4E-45Positive range:1.4E-45 to 3.4028235E+38d ouble Negative range: 64-bit IEEE 754-1.7976931348623157E+308 to-4.9E-324Positive range:4.9E-324 to 1.7976931348623157E+308Numeric OperatorsName Meaning Example Result + Addition 34 + 1 35- Subtraction 34.0 – 0.1 33.9* Multiplication 300 * 30 9000/ Division 1.0 / 2.0 0.5% Remainder 20 % 3 2Integer Division+,-,*,/,and%5/2yields an integer2.5.0/2yields a double value2.55%2yields1(the remainder of the division)Problem: Displaying Time Write a program that obtains minutes from seconds.DisplayTime RunNOTECalculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example,System.out.println(1.0-0.1-0.1-0.1-0.1-0.1); displays0.5000000000000001,not0.5,and System.out.println(1.0-0.9);displays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.Problem: Displaying Current Time Write a program that displays current time in GMT in the format hour:minute:second such as 1:45:19.The currentTimeMillis method in the System class returns the current time in milliseconds since the midnight, January 1, 1970 GMT . (1970 was the year when the Unix operating system was formally introduced.) You can use this method to obtain the current time, and then compute the current second, minute, and hour as follows.ShowCurrentTime RunElapsedtimeUnix Epoch01-01-197000:00:00 GMT Current Time Time System.currentTimeMills()Numeric Type Conversion Consider the following statements:byte i=100;long k=i*3+4;double d=i* 3.1+k/2;Conversion RulesWhen performing a binary operation involving twooperands of different types, Java automaticallyconverts the operand based on the following rules: 1.If one of the operands is double, the other isconverted into double.2.Otherwise, if one of the operands is float, the other isconverted into float.3.Otherwise, if one of the operands is long, the other isconverted into long.4.Otherwise, both operands are converted into int.Type CastingImplicit castingdouble d=3;(type widening)Explicit castingint i=(int)3.0;(type narrowing)int i = (int)3.9; (Fraction part is truncated)What is wrong?int x=5/2.0;range increasesbyte, short, int, long, float, doubleProblem: Keeping Two Digits AfterDecimal PointsWrite a program that displays the sales tax with two digits after the decimal point.SalesTax RunCharacter Data TypeFour hexadecimal digits.char letter='A';(ASCII)char numChar='4';(ASCII)char letter = '\u0041'; (Unicode)char numChar = '\u0034'; (Unicode)NOTE:The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example,the following statements display character b.char ch='a';System.out.println(++ch);Unicode FormatJava characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000'to '\uFFFF'. So, Unicode can represent 65535 + 1 characters.Unicode \u03b1 \u03b2 \u03b3 for three GreeklettersProblem: Displaying Unicodes Write a program that displays two Chinese characters and three Greek letters.DisplayUnicode RunEscape Sequences for Special Characters Description Escape Sequence Unicode Backspace \b\u0008 Tab \t\u0009 Linefeed \n\u000A Carriage return \r\u000D Backslash \\\u005C Single Quote \'\u0027 Double Quote \"\u0022Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007fASCII Character Set, cont.ASCII Character Set is a subset of the Unicode from \u0000 to \u007fCasting between char andNumeric Typesint i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97;The String TypeThe char type only represents one character. To represent a string of characters, use the data type called String. For example,String message = "Welcome to Java";String is actually a predefined class in the Java library just like the System class and JOptionPane class. The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type for a variable.String Concatenation// Three strings are concatenatedString message = "Welcome " + "to " + "Java";// String Chapter is concatenated with number 2String s = "Chapter" + 2; // s becomes Chapter2// String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementBConverting Strings to IntegersThe input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number.To convert a string into an int value, you can use the static parseInt method in the Integer class as follows:int intValue = Integer.parseInt(intString);where intString is a numeric string such as “123”.Converting Strings to DoublesTo convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”.Programming Style andDocumentation☞Appropriate Comments☞Naming Conventions☞Proper Indentation and Spacing Lines☞Block StylesAppropriate CommentsInclude a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses.Include your name, class section, instructor, date, and a brief description at the beginning of the program.Naming Conventions☞Choose meaningful and descriptive names.☞Variables and method names:–Use lowercase. If the name consists of severalwords, concatenate all in one, use lowercasefor the first word, and capitalize the first letterof each subsequent word in the name. Forexample, the variables radius and area, and the method computeArea.Naming Conventions, cont.☞Class names:–Capitalize the first letter of each word inthe name. For example, the class nameComputeArea.☞Constants:–Capitalize all letters in constants, and useunderscores to connect words. Forexample, the constant PI andMAX_VALUEProper Indentation and Spacing☞Indentation–Indent two spaces.☞Spacing–Use blank line to separate segments of the code.Block Styles Use end-of-line style for braces.public class Test{public static void main(String[] args){System.out.println("Block Styles");}}public class Test {public static void main(String[] args) { System.out.println("Block Styles");}} End-of-line styleNext-line styleProgramming Errors ☞Syntax Errors–Detected by the compiler☞Runtime Errors–Causes the program to abort☞Logic Errors–Produces incorrect resultSyntax Errorspublic class ShowSyntaxErrors{public static void main(String[]args){ i=30;System.out.println(i+4);}}Runtime Errorspublic class ShowRuntimeErrors{public static void main(String[]args){ int i=1/0;}}Logic Errorspublic class ShowLogicErrors{public static void main(String[]args){ //Add number1to number2int number1=3;int number2=3;number2+=number1+number2;System.out.println("number2is"+number2);}}DebuggingLogic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. You can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility.DebuggerDebugger is a program that facilitates debugging. You can use a debugger to☞Execute a single statement at a time.☞Trace into or stepping over a method.☞Set breakpoints.☞Display variables.☞Display call stack.☞Modify variables.JOptionPane InputThis book provides two ways of obtaining input.ing the Scanner class (console input)ing JOptionPane input dialogsString input = JOptionPane.showInputDialog( "Enter an input");String string = JOptionPane.showInputDialog( null, “Prompting Message”, “Dialog Title”, JOptionPane.QUESTION_MESSAGE);Two Ways to Invoke the Method There are several ways to use the showInputDialog method. For the time being, you only need to know two ways to invoke it. One is to use a statement as shown in the example:String string = JOptionPane.showInputDialog(null, x,y, JOptionPane.QUESTION_MESSAGE);where x is a string for the prompting message, and y is a string for the title of the input dialog box.The other is to use a statement like this:JOptionPane.showInputDialog(x);where x is a string for the prompting message.Common ErrorsAdding a semicolon at the end of an if clause is a common mistake.if (radius >= 0);Wrong{area = radius*radius*PI;System.out.println("The area for the circle of radius " +radius + " is " + area);}This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error.This error often occurs when you use the next-line block style.TIPif (number % 2 == 0) even = true;elseeven = false;(a) Equivalent boolean even= number % 2 == 0;(b)CAUTIONif (even == true)System.out.println( "It is even.");(a) Equivalent if (even)System.out.println("It is even.");(b)。
电脑编程入门从零开始学习编程为了适应信息时代的发展,学习电脑编程已经变得越来越重要。
电脑编程不仅能够开发出各种应用软件,还能够提升逻辑思维能力,并开启一个崭新的职业发展方向。
对于没有编程基础的初学者而言,如何从零开始学习编程变得尤为重要。
本文将介绍一些学习编程的基本步骤和方法。
1. 选择合适的编程语言编程语言是学习编程的基础,初学者可以选择易于理解的编程语言开始学习。
常见的编程语言有Python、JavaScript、Java等。
Python是一门简单易学的语言,它的语法规则简单明了,非常适合初学者入门。
与此同时,Python在数据科学、人工智能等领域也有广泛的应用。
2. 学习基本的编程概念和语法在开始编写代码之前,了解基本的编程概念和语法是必不可少的。
编程中常见的概念包括变量、条件语句、循环语句等。
初学者可以通过阅读编程教程、参加在线课程或者参考相关书籍来学习这些概念和语法。
3. 练习编程要掌握编程技巧,需要进行大量的实践练习。
初学者可以选择一些简单的编程项目开始,例如编写一个打印“Hello World!”的程序,或者编写一个简单的计算器程序。
通过实际动手做项目,可以更好地理解和掌握编程知识。
4. 参与编程社区和讨论编程社区是一个学习和交流的重要平台。
初学者可以加入一些编程社区,例如GitHub、Stack Overflow等,与其他开发者交流经验,解决遇到的问题。
在社区中,可以学习到更多高级技术和实践经验,提高编程水平。
5. 持续学习和实践编程是一个不断进步和学习的过程。
初学者应该保持持续的学习和实践,通过不断地编写代码来提高自己的编程技能。
可以参考一些推荐的编程书籍、网站或者参加一些编程培训课程,不断扩展自己的编程知识。
总结起来,学习电脑编程需要选择合适的编程语言,学习基本的概念和语法,进行实践练习,并参与编程社区和讨论。
同时需要保持持续的学习和实践,不断提升自己的编程技能。
通过坚持不懈的努力,相信每个人都能够从零开始学习编程,并在编程领域取得成功。