《JAVA基础教程》第三章 Java程序设计基础
- 格式:doc
- 大小:69.50 KB
- 文档页数:12
实验10import java.util.*;public class shiyan10{public static void main(String[] args){int a=0,b=0,c=0,max=0;Scanner reader=new Scanner(System.in);System.out.println("从键盘输入第一个整数");a=reader.nextInt();System.out.println("从键盘输入第二个整数");b=reader.nextInt();System.out.println("从键盘输入第三个整数");c=reader.nextInt();if(a>b)max=a;elsemax=b;if(c>max)max=c;System.out.println("最大的数是"+max);}}//在程序中输入三个整数,比较它们的大小,输出最大的数实验11public class shiyan11{public static void main(String[] args){int s=0;for(int i=0;i<100;i++){s=s+i;i++;}System.out.println("1+3+5+···+99="+s);}}//用for循环语句求1+3+5+···+99的值实验12import java.util.*;public class shiyan12{public static void main(String[] args){int a=0,i=1,s=0;Scanner reader=new Scanner(System.in);while(a<50||a>100){System.out.println("从键盘输入一个50~100的整数");a=reader.nextInt();}System.out.println("你输入的数是"+a);while(i<=a){s=s+i;i++;}System.out.println("1+2+3+···+"+a+"="+s);}}//编写从键盘输入一个范围在50~100的整数,如果不正确,则继续输入;然后求1到输入整数的累加实验13public class shiyan13{public static void main(String[]args){int i=100,s=0;do{s=s+i;i--;}while(i>0);System.out.println("100+99+98+···+2+1="+s);}}//用do-while语句求100+99+···+2+1的值实验14import java.util.*;public class shiyan14{public static void main(String[] args)int a=-1;Scanner reader=new Scanner(System.in);System.out.println("从键盘输入0~6的整数");a=reader.nextInt();while(a<0||a>6){System.out.println("输入错误");System.out.println("从键盘输入0~6的整数");a=reader.nextInt();}switch(a){case 0:System.out.println("今天是星期日");break;case 1:System.out.println("今天是星期一");break;case 2:System.out.println("今天是星期二");break;case 3:System.out.println("今天是星期三");break;case 4:System.out.println("今天是星期四");break;case 5:System.out.println("今天是星期五");break;case 6:System.out.println("今天是星期六");break;default:System.out.println("输入错误");break;}}}//让用户通过输入一个0~6的整数,显示今天是xingqijipublic class shiyan15{public static void main(String[] args){for(int i=1;i<10;i++){if(i==6)break;System.out.println(""+i);}System.out.println("\n显示完毕");for(int i=1;i<10;i++){if(i%2==0)continue;System.out.println(""+i);}System.out.println("\n显示完毕");}}//先显示1~5各个整数,然后再显示1~10的各个奇数。
Java程序设计基础习题答案Java程序设计基础课后习题参考答案第2章1、关于Java Application得入口方法main()得检验:main()方法得参数名就是否可以改变?main()方法得参数个数就是否可以改变?该方法名就是否可以改变?参考答案:(1)main()方法得参数名可以改变.(2)main()方法得参数个数不可以改变。
(3)该方法名不可以改变。
2、当一个程序没有main()方法时,能编译吗?如果能编译,能运行吗?参考答案:当一个程序没有main()方法就是,就是可以编译通过得,但就是不能给运行,因为找不到一个主函数入口。
3、下列语句能否编译通过?bytei =127;bytej = 128;longl1 = 999999;long l2= 9999999999;参考答案:byte i 与long l1可以编译通过。
而byte j 与longl2 超出自身数据类型范围,所以编译失败。
4、下列语句能否编译通过?float f1 =3、5;float f2 = 3.5f;参考答案:java中浮点型得数据在不声明得情况下都就是doubl e型得,如果要表示一个数据就是float型得,必须在数据后面加上“F”或“f”;因此,floatf1 无法编译通过。
5、验证int 与char,int与double等类型就是否可以相互转换。
参考答案:(1)char类型可以转换为int 类型得,但就是int类型无法转换为char类型得;(2)int 可以转换为double类型得,但就是double类型无法转换为int 类型得。
6、计算下列表达式,注意观察运算符优先级规则。
若有表达式就是非法表达式,则指出不合法之处且进行解释。
(1)4+5 == 6*2 ?(2) (4=5)/6??(3)9%2*7/3>17(4)(4+5)<=6/3 ?(5) 4+5%3!=7-2(6)4+5/6〉=10%2参考答案:表达式(2)为不合法表达式,只能将值赋值给一个变量,因此其中(4=5)将5赋值给4就是不合法得.7、下列()就是合法得Java标识符。
java程序设计基础第三版Java程序设计基础第三版Java是一种广泛使用的编程语言,以其跨平台的特性、面向对象的特性、健壮性、安全性和性能而闻名。
《Java程序设计基础》第三版是对Java语言的深入介绍,适合初学者和有一定编程基础的读者。
本版书籍在前两版的基础上,更新了Java语言的最新发展,并增加了一些实用的编程技巧。
第一章:Java语言概述Java语言由Sun Microsystems公司(现为Oracle公司)在1995年发布。
Java是一种纯面向对象的语言,这意味着在Java中,所有的数据都是对象。
Java的设计哲学是“一次编写,到处运行”(Write Once, Run Anywhere),这得益于它的虚拟机(JVM)技术。
第二章:Java开发环境搭建在开始Java编程之前,需要安装Java开发工具包(JDK),并配置环境变量。
此外,还可以使用集成开发环境(IDE)如Eclipse或IntelliJ IDEA来提高开发效率。
第三章:基本语法Java的基本语法包括数据类型、变量、运算符、控制语句等。
Java是强类型语言,所有变量在使用前必须声明其类型。
Java提供了丰富的控制语句,如if-else、switch、while、for等。
第四章:面向对象编程面向对象编程(OOP)是Java的核心特性。
本章介绍了类和对象的概念,以及如何使用类来封装数据和行为。
此外,还介绍了继承、多态和接口等OOP的基本概念。
第五章:数组和字符串数组是Java中存储固定大小的同类型元素的集合。
字符串是字符的序列,Java提供了String类来处理字符串,包括字符串的创建、连接、比较等操作。
第六章:集合框架Java集合框架提供了一套接口和类,用于存储和操作对象集合。
包括List、Set、Map等接口,以及ArrayList、HashSet、HashMap等实现类。
第七章:异常处理Java使用异常处理机制来处理程序运行时出现的错误。
java程序设计基础课后习题答案Java程序设计基础课后习题答案在学习Java程序设计基础课程的过程中,课后习题是非常重要的一部分。
通过完成课后习题,我们可以巩固课堂上所学的知识,提高编程能力,加深对Java 语言的理解。
下面我们来看一些常见的Java程序设计基础课后习题答案。
1. 编写一个Java程序,实现输入两个整数,然后输出它们的和。
```javaimport java.util.Scanner;public class AddTwoNumbers {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("请输入第一个整数:");int num1 = input.nextInt();System.out.println("请输入第二个整数:");int num2 = input.nextInt();int sum = num1 + num2;System.out.println("它们的和是:" + sum);}}```2. 编写一个Java程序,实现输入一个整数,然后判断它是奇数还是偶数。
```javaimport java.util.Scanner;public class OddOrEven {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("请输入一个整数:");int num = input.nextInt();if (num % 2 == 0) {System.out.println(num + "是偶数");} else {System.out.println(num + "是奇数");}}}```3. 编写一个Java程序,实现输入一个年份,然后判断它是否是闰年。
《Java语言程序设计-基础篇》第03章答案3.1 答:if(i % 2 == 0) System.out.println(“偶数”); else System.out.println(“奇数”); 3.2 答:当 x = 3, y = 2 时,输出:无输出当x = 3, y = 4 时,输出:z is 7 当 x = 2,y = 2 时,输出:x is 2 3.3 答:等价的语句有:a, c和d 正确缩进的是:c 3.4 答:当 x = 2, y = 3 时,输出:x is 2 当 x = 3, y = 2 时,输出:无输出当 x = 3,y = 3 时,输出:z is 7 3.5 答:等价 3.6 答:switch变量可以是char, byte, short, int。
执行case语句后没有break,则继续执行下一个case语句。
switch可转换为等价的if语句(嵌套),反之不一定可以。
3.7 答:y的值是2。
3.8 答:switch(a){ case 1: x += 5; break; case 2: x += 10; break; case 3: x += 16; break; case 4: x += 34; } 3.9 答:System.out.print(count + (count % 10 == 0 ? “\n“ : ““)); 3.10 答:(a)执行0次,无输出(b)执行9次,输出如下:3 5 7 9 3.11 答:(略)3.12 答:相同,均为45。
3.13 答:for(int i = 1; i System.out.println(i); 3.14 答:无限循环。
3.15 答:不能。
3.16 答:能。
(略)3.17 答:(略)3.18 答:(a)输出:balance is 1 (b)不能结束(编译有错,输出语句执行不到)3.19 答:能。
(略)3.20 答:int i=0; while(iif(i%3==0){ i++; continue; } sum += i; i++; } 3.21 答:(a)主方法如下:public static void main(String[] args) { int sum = 0; int number = 0; while(number number++; sum += number; } System.out.println(“The number is “ + number); System.out.println(“The sum is “ + sum); } (b)主方法如下:public static void main(String[] args) { int sum = 0; int number = 0; while(number number++; if(!(number == 10 || number == 11)) sum += number; } System.out.println(“The number is “ + number); System.out.println(“Thesum is “ + sum); } 3.22 答:执行next:后面的语句。
《程序设计基础(Java)》教案一、教学目标1. 让学生掌握Java编程语言的基本语法和结构。
2. 培养学生编写简单的Java程序,为后续深入学习打下基础。
3. 帮助学生理解面向对象编程的基本概念,如类、对象、封装、继承和多态。
二、教学内容1. Java语言简介:介绍Java语言的发展历程、特点和应用领域。
2. Java基本语法:变量、数据类型、运算符、控制语句、数组和字符串。
3. 面向对象编程:类与对象、封装、继承和多态。
4. 常用Java类库:ng、java.util、java.awt等。
5. 编程实践:编写简单的Java程序,如计算器、排序算法等。
三、教学方法1. 讲授法:讲解Java语言的基本语法和面向对象编程概念。
2. 案例分析法:分析实际编程案例,让学生理解面向对象编程的应用。
3. 实践操作法:让学生动手编写Java程序,提高编程能力。
4. 讨论法:分组讨论编程问题,培养学生的团队协作能力。
四、教学安排1. 第1-2课时:Java语言简介及基本语法。
2. 第3-4课时:面向对象编程。
3. 第5-6课时:常用Java类库。
4. 第7-8课时:编程实践。
5. 第9-10课时:总结与复习。
五、教学评价1. 课堂参与度:评估学生在课堂上的发言和提问情况。
2. 编程作业:评估学生编写的Java程序的正确性和完整性。
3. 小组讨论:评估学生在讨论中的表现和团队协作能力。
4. 期末考试:考察学生对Java编程基础知识的掌握程度。
六、教学资源1. 教材:《Java程序设计基础》2. 课件:教师自制的PPT课件3. 编程环境:Eclipse、IntelliJ IDEA等4. 在线编程平台:LeetCode、牛客网等5. 教学视频:网易云课堂、慕课网等提供的Java编程教程七、教学过程1. 导入:通过介绍Java语言在实际应用中的案例,激发学生的学习兴趣。
2. 讲解:结合课件,讲解Java语言的基本语法和面向对象编程概念。
java程序设计基础知识⼀、Java语⾔概述1.1 Java基本概念:类是java程序的基本构成单位,重要的⼊⼝main⽅法,基本结构主类主⽅法public class test{public static void main(String[] args){System.println(“hello java”);}}1.2 Java特性:跨平台、安全稳定、⽀持多线程、⽀持⽹络编程、具有丰富的库函数、⾯向对象(继承、封装、多态)1.3 Java程序的执⾏环境和源⽂件处理过程:javac xxx.java //编译java xxx //运⾏举个栗⼦:假设有⼀个test.java⽂件javac test.javajavac test编译如果通过就会⽣成⼀个.class后缀结尾的字节码(bytecode)⽂件字节码由Java虚拟机执⾏1.4 JDK⽂件的结构:bin: 该⽬录存放运⾏程序;db: 该⽬录存放有关数据库⽅⾯的⽂件;demo: 该⽬录存放⼀些实例⽂件;include: 该⽬录存放与C相关的头⽂件;jre:该⽬录存放java运⾏环境相关的⽂件;lib: 该⽬录存放程序库;更多的可以了解JDK官⽅⽂档查就ok1.5 ⾯向对象的软件开发过程:⾯向对象的分析(Object Oriented Analysis OOA)⾯向对象的设计(Object Oriented Design OOD)⾯向对象的实现(Object Oriented Programming OOP)⼆、Java编程基础2.1 基础数据类型:注意和包装类的区别(包装类⾸字母⼤写,⽽基本类型都是⼩写),注意和C语⾔的区别,注意类型之间的转换,低精度可以直接存储到⾼精度变量中,这是⾃动转换;⾼精度数据放⼊低精度变量必须强制转换。
还要注意有些数据类型不能转换。
⽐如boolean不能将其转换为其他类型,尤其是整型,这⼀点是和C的明显区别。
float a=8.1; //报错,8.1默认是double类型2.2 命名规则:类、接⼝⾸字母⼤写,变量⾸字母⼩写,常量全⼤写(⾏业惯例)标识符的命名规则(掌握,这是强⾏规定)⾸字符必须是字母(⼤⼩写均可)、下划线(_)或美元符号($)标识符可以由数字(0-9)、A-Z、a-z和下划线(_)、美元符号($)长度不限2.3 Java的注释符号a) 单⾏注释//开始⾏尾结束b) 多⾏注释/*开始 */结束c) doc注释/**开始 */结束注意:第3种注释主要是为⽀持JDK⼯具javadoc⽽采⽤的。
《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案3.1public class Exercise03_01 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a, b, c: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double discriminant = b * b - 4 * a * c;if (discriminant < 0) {System.out.println("The equation has no real roots");}else if (discriminant == 0) {double r1 = -b / (2 * a);System.out.println("The equation has one root " + r1);}else { // (discriminant > 0)double r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);double r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);System.out.println("The equation has two roots " + r1 + " and " + r2);}}}3.1附加public class Exercise03_01Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter a numerator: ");int numerator = input.nextInt();System.out.print("Enter a denominator: ");int denominator = input.nextInt();if (numerator < denominator) {System.out.println(numerator + " / " + denominator + " is a proper fraction");}else if (numerator % denominator == 0) {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and it can be reduced to " + numerator / denominator);}else {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and its mixed fraction is " + numerator / denominator + " + " +numerator % denominator + " / " + denominator);}}}3.2public class Exercise03_02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);int number1 = (int)(System.currentTimeMillis() % 10);int number2 = (int)(System.currentTimeMillis() * 7 % 10);int number3 = (int)(System.currentTimeMillis() * 3 % 10);System.out.print("What is " + number1 + " + " + number2 + " + " +number3 + "? ");int answer = input.nextInt();System.out.println(number1 + " + " + number2 + " + " + number3 +" = " + answer + " is " +(number1 + number2 + number3 == answer));}}3.2附加public class Exercise03_02Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter the coordinates for two points: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();double m = (y2 - y1) / (x2 - x1);double b = y1 - m * x1;System.out.print("The line equation for two points (" + x1 + ", " + y1 + ") and (" + x2 + ", " + y2 + ") is " + "y = ");if (m == -1)System.out.print("-x");else if (m == 1)System.out.print("x");elseSystem.out.print(m + "x");if (b > 0)System.out.println(" + " + b);else if (b < 0)System.out.println(" - " + (-1 * b));else// b is 0System.out.println();}}3.3public class Exercise03_03 {public static void main(String[] args) {Scanner input = new Scanner(System.in); System.out.print("Enter a, b, c, d, e, f: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double d = input.nextDouble();double e = input.nextDouble();double f = input.nextDouble();double detA = a * d - b * c;if (detA == 0) {System.out.println("The equation has no solution"); }else {double x = (e * d - b * f) / detA;double y = (a * f- e * c) / detA;System.out.println("x is " + x + " and y is " + y);}}}3.3附加public class Exercise03_03Extra {public static void main(String[] args) {final double RADIUS = 5;double angle = Math.random() * 2 * Math.PI;double x = RADIUS * Math.random() * Math.cos(angle);double y = RADIUS * Math.sin(angle);double distance = Math.pow(x * x + y * y, 0.5);System.out.println("The point is (" + x + ", " + y + ") and its distance to the center is " + distance);}}3.4public class Exercise03_04 {public static void main(String[] args) {int number = (int)(Math.random() * 12) + 1;// or int number = (int)(System.currentTimeMillis() % 12 + 1);// or int number = (int)(Math.random() * 12) + 1;if (number == 1)System.out.println("Month is Januaray");else if (number == 2)System.out.println("Month is Feburary");else if (number == 3)System.out.println("Month is March");else if (number == 4)System.out.println("Month is April");else if (number == 5)System.out.println("Month is May");else if (number == 6)System.out.println("Month is June");else if (number == 7)System.out.println("Month is July");else if (number == 8)System.out.println("Month is August");else if (number == 9)System.out.println("Month is September");else if (number == 10)System.out.println("Month is October");else if (number == 11)System.out.println("Month is November");else// if (number == 12)System.out.println("Month is December");}}3.5public class Exercise03_05 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter an integer for todaySystem.out.print("Enter today抯 day: ");int today = input.nextInt();System.out.print("Enter the number of days elapsed since today: ");int elapsedDays = input.nextInt();String nameForToday;if (today == 0)nameForToday = "Sunday";else if (today == 1)nameForToday = "Monday";else if (today == 2)nameForToday = "Tuesday";else if (today == 3)nameForToday = "Wednesday";else if (today == 4)nameForToday = "Thursday";else if (today == 5)nameForToday = "Friday";else// if (today == 6)nameForToday = "Saturday";int futureDay = (today + elapsedDays) % 7; String nameForFutureDay;if (futureDay == 0)nameForFutureDay = "Sunday";else if (futureDay == 1) nameForFutureDay = "Monday";else if (futureDay == 2) nameForFutureDay = "Tuesday";else if (futureDay == 3) nameForFutureDay = "Wednesday";else if (futureDay == 4) nameForFutureDay = "Thursday";else if (futureDay == 5) nameForFutureDay = "Friday";else// if (futureDay == 6) nameForFutureDay = "Saturday";System.out.println("Today is " + nameForToday+ " and the future day is " + nameForFutureDay); } }3.6public class Exercise03_06 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in pounds System.out.print("Enter weight in pounds: "); double weight = input.nextDouble();// Prompt the user to enter heightSystem.out.print("Enter feet: ");double feet = input.nextDouble();System.out.print("Enter inches: ");double inches = input.nextDouble();double height = feet * 12 + inches;// Compute BMIdouble bmi = weight * 0.45359237 / ((height * 0.0254) * (height * 0.0254));// Display resultSystem.out.println("BMI is " + bmi);if (bmi < 18.5)System.out.println("Underweight");else if (bmi < 25)System.out.println("Normal");else if (bmi < 30)System.out.println("Overweight");elseSystem.out.println("Obese");}}3.7/** Break down an amount into smaller units* Display the non-zero denominations only, and display singular* words for single units like 1 dollars, 1 penny, and display plural * words for more than one unit like 2 dollars, 3 pennies.*/public class Exercise03_07 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Receive the amount entered from the keyboardSystem.out.print("Enter an amount in double, for example 11.56: ");double amount = input.nextDouble();int remainingAmount = (int)(amount * 100);// Find the number of one dollarsint numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quarters in the remaining amountint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amountint numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amountint numberOfPennies = remainingAmount;// Display resultsif (amount < 0) {System.out.println("Your amount is negative");System.exit(1);}else if (amount < 0) {System.out.println("Your amount is zero");System.exit(2);}System.out.println("Your amount " + amount + " consists of ");if (numberOfOneDollars > 1)System.out.println(numberOfOneDollars + "\ dollars");else if (numberOfOneDollars == 1)System.out.println(numberOfOneDollars + "\ dollar");if (numberOfQuarters > 1)System.out.println(numberOfQuarters + "\ quarters");else if (numberOfQuarters == 1)System.out.println(numberOfQuarters + "\ quarter");if (numberOfDimes > 1)System.out.println(numberOfDimes + "\ dimes");else if (numberOfDimes == 1)System.out.println(numberOfDimes + "\ dime");if (numberOfNickels > 1)System.out.println(numberOfNickels + "\ nickels");else if (numberOfNickels == 1)System.out.println(numberOfNickels + "\ nickel");if (numberOfPennies > 1)System.out.println(numberOfPennies + "\ pennies");else if (numberOfPennies == 1)System.out.println(numberOfPennies + "\ penny");}}3.8public class Exercise03_08 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three numbersSystem.out.print("Enter three integers: ");int number1 = input.nextInt();int number2 = input.nextInt();int number3 = input.nextInt();if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}if (number2 > number3) {int temp = number2;number2 = number3;number3 = temp;}if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}System.out.println("The sorted numbers are "+ number1 + " " + number2 + " " + number3);}}public class Exercise03_09 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter the first 9 digits of an ISBN as integer: ");int number = input.nextInt();// Calculate checksum (You may write a loop to simplify it in Ch4int checksum =((number / 100000000 % 10) * 1 +(number / 10000000 % 10) * 2 +(number / 1000000 % 10) * 3 +(number / 100000 % 10) * 4 +(number / 10000 % 10) * 5 +(number / 1000 % 10) * 6 +(number / 100 % 10) * 7 +(number / 10 % 10) * 8 +(number % 10) * 9) % 11;System.out.print("The ISBN-10 number is ");// Display leading zeros, improve the solution using loops in the next chapterif (number / 100000000 == 0) {System.out.print("0");if (number / 10000000 == 0) {System.out.print("0");if (number / 1000000 == 0) {System.out.print("0");if (number / 100000 == 0) {System.out.print("0");if (number / 10000 == 0) { System.out.print("0");if (number / 1000 == 0) { System.out.print("0");if (number / 100 == 0) {System.out.print("0");if (number / 10 == 0) {System.out.print("0");if (number == 0) {System.out.print("0");}}}}}}}}}System.out.print(number);if (checksum == 10)System.out.print("X");elseSystem.out.print(checksum);}}3.10public class Exercise03_10 {public static void main(String[] args) {// 1. Generate two random single-digit integersint number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);// 2. Prompt the student to answer 搘hat is number1 + number2?? System.out.print("What is " + number1 + " + " + number2 + "? "); Scanner input = new Scanner(System.in);int answer = input.nextInt();// 4. Grade the answer and display the resultString replyString;if (number1 + number2 == answer)replyString = "You are correct!";elsereplyString = "Your answer is wrong.\" + number1 + " + "+ number2 + " should be " + (number1 + number2);System.out.println(replyString);}}3.11public class Exercise03_11 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter inputSystem.out.print("Enter a month in the year (e.g., 1 for Jan): ");int month = input.nextInt();System.out.print("Enter a year: ");int year = input.nextInt();int numberOfDaysInMonth = 0;switch (month) {case 1:System.out.print("January " + year);numberOfDaysInMonth = 31;break;case 2:System.out.print("February " + year);if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { numberOfDaysInMonth = 29;}else {numberOfDaysInMonth = 28;}break;case 3:System.out.print("March " + year);numberOfDaysInMonth = 31;break;case 4:System.out.print("April " + year);numberOfDaysInMonth = 30;break;case 5:System.out.print("May " + year);numberOfDaysInMonth = 31;break;case 6:System.out.print("June " + year);numberOfDaysInMonth = 30;break;case 7:System.out.print("July " + year);numberOfDaysInMonth = 31;break;case 8:System.out.print("August " + year);numberOfDaysInMonth = 31;break;case 9:System.out.print("September " + year);numberOfDaysInMonth = 30;break;case 10:System.out.print("October " + year);numberOfDaysInMonth = 31;break;case 11:System.out.print("November " + year);numberOfDaysInMonth = 30;break;case 12:System.out.print("December " + year);numberOfDaysInMonth = 31;break;}System.out.print(" has " + numberOfDaysInMonth + " days"); }}3.12public class Exercise03_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a three-digit integer: ");int number = input.nextInt();if (number / 100 == number % 10)System.out.println(number + " is a palindrome");elseSystem.out.println(number + " is not a palindrome");}}3.13public class Exercise03_13 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter filing statusSystem.out.print("(0-single filer, 1-married jointly or qualifying widow(er),"+ "\2-married separately, 3-head of household)\" + "Enter the filing status: ");int status = input.nextInt();// Prompt the user to enter taxable incomeSystem.out.print("Enter the taxable income: ");double income = input.nextDouble();// Compute taxdouble tax = 0;if (status == 0) { // Compute tax for single filersif (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 82250) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950)* 0.25; } else if (income <= 171550) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;} else if (income <= 372950) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (income - 171550) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;}} else if (status == 1) { // Compute tax for married file jointly if (income <= 16700) {tax = income * 0.10;} else if (income <= 67900) {tax = 16700 * 0.10 + (income - 16700) * 0.15;} else if (income <= 137050) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (income - 67900) * 0.25; } else if (income <= 208850) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (income - 137050) * 0.28;} else if (income <= 372950) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (income - 208850) * 0.33;} else {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (171950 - 137050) * 0.28 + (372950 - 208850) * 0.33+ (income - 372950) * 0.35;}} else if (status == 2) { // Compute tax for married separately if (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 68525) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25; } else if (income <= 104425) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (income - 68525) * 0.28;} else if (income <= 186475) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (income - 104425) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (186475 - 104425) * 0.33 + (income - 186475) * 0.35;}} else if (status == 3) { // Compute tax for head of household if (income <= 11950) {tax = income * 0.10;} else if (income <= 45500) {tax = 11950 * 0.10 + (income - 11950) * 0.15;} else if (income <= 117450) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (income - 45500) * 0.25; } else if (income <= 190200) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (income - 117450) * 0.28;} else if (income <= 372950) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (income - 190200) * 0.33;} else {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (372950 - 190200) * 0.33+ (income - 372950) * 0.35;}} else {System.out.println("Error: Wrong filing status");System.exit(1);}// Display the resultSystem.out.println("Tax is " + (int) (tax * 100) / 100.0);}}3.14public class Exercise03_14 {public static void main(String[] args) {// Obtain the random number 0 or 1int number = (int)(Math.random() * 2);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Guess head or tail? " +"Enter 0 for head and 1 for tail: ");int guess = input.nextInt();// Check the guessif (guess == number)System.out.println("Correct guess");else if (number == 0)System.out.println("Sorry, it is a head");elseSystem.out.println("Sorry, it is a tail");}}3.15public class Exercise03_15 {public static void main(String[] args) {// Generate a lotteryint lottery = (int)(Math.random() * 1000);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter your lottery pick (three digits): ");int guess = input.nextInt();// Get digitsint l1 = lottery / 100;int l2 = (lottery % 100) / 10; // l2 = (lottery / 10) % 10int l3 = lottery % 10;int g1 = guess / 100;int g2 = (guess % 100) / 10;int g3 = guess % 10;System.out.println("Lottery is " + lottery);// Check the guessif (guess == lottery)System.out.println("Exact match: you win $10,000");else if (g1 == l1 && g3 == l2 && g2 == l3 ||g2 == l1 && g1 == l2 && g3 == l3 ||g2 == l1 && g3 == l2 && g1 == l3 ||g3 == l1 && g1 == l2 && g2 == l3 ||g3 == l1 && g2 == l2 && g1 == l3)System.out.println("Match all digits: you win $3,000"); else if (g1 == l1 || g1 == l2 || g1 == l3 ||g2 == l1 || g2 == l2 || g2 == l3 ||g3 == l1 || g3 == l2 || g3 == l3)System.out.println("Match one digit: you win $1,000"); elseSystem.out.println("Sorry, no match");}}3.16public class Exercise03_16 {public static void main(String[] args) {double x = Math.random() * 100 - 50;double y = Math.random() * 200 - 100;System.out.println(x + ", " + y);}}3.17public class Exercise03_17 {public static void main(String[] args) {// Generate scissor, rock, paperint computerNumber = (int)(Math.random() * 3);// Prompt the user to enter scissor, rock, or paper java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("scissor (0), rock (1), paper (2): ");int userNumber = input.nextInt();// Check the guessswitch (computerNumber) {case 0:if (userNumber == 0)System.out.print("The computer is scissor. You are scissor too. It is a draw");else if (userNumber == 1)System.out.print("The computer is scissor. You are rock. You won");else if (userNumber == 2)System.out.print("The computer is scissor. You are paper. You lost");break;case 1:if (userNumber == 0)System.out.print("The computer is rock. You are scissor. You lost");else if (userNumber == 1)System.out.print("The computer is rock. You are rock too. It is a draw");else if (userNumber == 2)System.out.print("The computer is rock. You are paper. You won");break;case 2:if (userNumber == 0)System.out.print("The computer is paper. You are scissor. You won");else if (userNumber == 1)System.out.print("The computer is paper. You are rock. You lost");else if (userNumber == 2)System.out.print("The computer is paper. You are paper too.It is a draw");break;}}}3.18public class Exercise03_18 {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter package weight: ");double w = input.nextDouble();if (w <= 1) {System.out.println("The shipping cost is $3.5");}else if (w <= 3) {System.out.println("The shipping cost is $5.5");}else if (w <= 10) {System.out.println("The shipping cost is $8.5");}else if (w <= 20) {System.out.println("The shipping cost is $10.5");}else {System.out.println("The package cannot be shipped");}}}3.19public class Exercise03_19 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three edgesSystem.out.print("Enter three edges (length in double): ");double edge1 = input.nextDouble();double edge2 = input.nextDouble();double edge3 = input.nextDouble();。
第三章Java程序设计基础3.1 Java编程概况现在你可以复习一下Java语言的背景材料,它的基本结构象C/C++,但任何用面向过程语言编写过程序的人都可以了解Java语言的大部分结构.3.1.1程序结构Java语言的源程序代码由一个或多个编译单元(compilation unit)组成,每个编译单元只能包含下列内容(空格和注释除外):*一个程序包语句(package statement )*入口语句(import statements) *类的声明(class declarations)*界面声明(interface declarations) 每个Java的编译单元可包含多个类或界面,但是每个编译单元最多只能有一个类或者界面是公共的。
Java的源程序代码被编译?reg;后,便产生了Java字节代码。
Java的字节代码由一?copy;不依赖于机器的指令组成,这?copy;指令能被Java的运行系统(runtimesystem)有效地解释。
Java的运行系统工作起来如同一台虚拟机。
在当前的Java实现中,每个编译单元就是一个以.java为后缀的文件。
每个编译单元有若干个类,编译后,每个类生成一个.class文件。
.class文件是Java虚拟机能够识别的代码。
3.1.2 注释三种类型如下://注释一行/*一行或多行注释*//**文档注释**/文档注释一般放在一个变量或函数定义?reg;前,指示在任何自动生成文档系统中调入。
这?copy;注释都是声明条目的描述.。
3.1.3 标识符变量,函数,类和对象的名称都是标识符,程序员需要标识和使用的东西都需要标识符。
在Java语言里,标识符以字符或_,$开头,后面可以包含数字,标识符是大小写有区别的,没有长度限制。
有效的标识符 myname ict_network Hello _sys_path $bill例子:int a_number; char _onechar; float $bill;关键词 abstract continue for new switch boolean default goto null synchronized break do if package this byte double implements private threadsafe byvalue else import protected throw case extends instanceof public transient catch false int return true char final interface shorttry class finally long static void const float native super while 其它保留词以下单词被保留使用:cast future generic inner operator outer rest var3.1.4 数据类型Java使用五种基本类型:integer(整数),floating(浮点数),point(指针),Boolean(布尔变量),Character or String(字符或字符串)。
integer整数下边给出的数据表示都是整数的例子:4,15,089,0xAD00整数长度数据类型表示 8 bits byte 16 bits short 32 bits int 64 bits long floating 浮点数下边给出的数据表示都是浮点数的例子:6.37,3.7E15,3e8浮点数长度数据类型表示 32 bits float 64 bits doubleBoolean 布尔变量下边是布尔变量的两种可能取值:true false Character 字符下边给出的都是字符的例子: a \\t (tab) \\u????(unicode) String字符串下边给出的都是字符串的例子:\"This is a string literal\" \"中国科学院计算所\"数组你可以定义任意类型的数组. char s[]; 这是字符型数组; int [] array; 这是整型数组;你还可以定义数组的数组. int block[][]=new int [2][3]; 数组边界在运行时被检测,避免堆栈溢出和内存崩溃.在Java里,数组实际上是一个对象,数组有一个成员变量:length。
你可以用这个成员函数来查看任意数组的长度.int a[][] = new int [10][3];a.length; /* 10 */a[0].length; /* 3 */创建数组在Java里创建数组,你可使用两种基本方法:一。
创建一个空数组:int list[]=new int[50]; 或你可以用初始数值填充数组.String names[] = { \"Chenji\",\"Yuan\",\"Chun\",\"Yang\" };相当于下面功能:String names[];names = new String[4];names[0]=new String(\"Chenji\");names[1]=new String(\"Yuan\");names[2]=new String(\"Chun\");names[3]=new String(\"Yang\");在编译时你不能象下例那样创建静态数组。
int name[50];//将产生一个编译错误你也不能用new操作去填充一个没定义大小的数组。
int name[];for (int i=0;i<9;i++){ name[i] = i; }3.1.5 表达式Java语言的表达式和C语言非常类似。
运算符运算符(operator)优先级从高到底排列如下:. [ ] () ++ -- ! ~ instanceof * / % + - << >> >>> < > <= >\\ == ! = & ^ && || ? := op = , 整数运算符在整数运算时,如果操作数是long类型,则运算结果是long类型,否则为int类型,绝不会是byte,short或char型。
这样,如果变量i被声明为short或byte,i+1的结果会是int。
如果结果超过该类型的取值范围,则按该类型的最大值取模。
单目整数运算符是:运算符操作-单目非~位补码++加1--减1++运算符用于表示直接加1操作。
增量操作也可以用加运算符和赋值操作间接完成。
++lvalue(左值?copy;表示lvalue+=1,++lvalue也表示lvalue =lvalue +1 (只要lvalue没有副作用)。
--运算符用于表示减1操作。
++和--运算符既可以作为前缀运算符,也可以做为后缀运算符。
双目整数运算符是:运算符操作**+加-减*乘/除%取模&位与|位或^位异或<<左移>>右移(带符号)>>>添零右移整数除法按零舍入。
除法和取模遵守以下等式:(a/b)*b+(a%b)==a整数算术运算的异常是由于除零或按零取模造成的。
它将引发一个算术异常。
下溢产生零,上溢导致越界。
例如:加1超过整数最大值,取模后,变成最小值。
一个op=赋值运算符,和上表中的各双目整数运算符联用,构成一个表达式。
整数关系运算符<,>,<=,>=,==和!=产生boolean类型的数据。
布尔运算符布尔(boolean)变量或表达式的组合运算可以产生新的boolean 值。
单目运算符!是布尔非。
双目运算符&,|和^是逻辑AND,OR和XOR运算符,它们强制两个操作数求布尔值。
为避免右侧操作数冗余求值,用户可以使用短路求值运算符&&和||。
用户可以使用==和!=,赋值运算符也可以用&=、|=、^=。
三元条件操作符?:和C语言中的一样。
浮点运算符浮点运算符可以使用常规运算符的组合:如单目运算符++、--,双目运算符+、-、*和/,以及赋值运算符+=,-=,*=,和/=。
此外,还有取模运算:%和%=也可以作用于浮点数,例如:a%b和a-((int)(a/b)*b)的语义相同。
这表示a%b的结果是除完后剩下的浮点数部分。
只有单精度操作数的浮点表达式按照单精度运算求值,产生单精度结果。
如果浮点表达式中含有一个或一个以上的双精度操作数,则按双精度运算,结果是双精度浮点数。
数组运算符数组运算符形式如下:[]可给出数组中某个元素的值。
合法的取值范围是从0到数组的长度减1。
取值范围的检查只在运行时刻实。
运算符以String对象实现。
运算符\"+\"完成并操作,如果必要则自动把操作数转换为String型。
如果操作数是一个对象,它可定义一个方法toString()返回该对象的String方式,例如 float a = 1.0 print (\"The value of a is\"+ a +\"\\n\"); +运算符用到?reg;上的例子 String s=\"a=\"+ a; +=运算符也可以用于String。
注意,左边(下例中的s1)仅求值一次。
s1+=a;//s1=s1+a//若a 非String型,自动转换为String型。
对象运算符双目运算符instanceof测试某个对象是否是指定类或其子类的实例。
例如:if(myObject instanceof MyClass) { MyClass anothermyObject=( MyClass) myObject; … } 是判定myObject是否是MyClass的实例或是其子类的实例。
强制和转换Java语言和解释器限制使用强制和转换,以防止出错导致系统崩溃。
整数和浮点数之间可以来回强制转换,但整数不能强制转换成数组或对象。
对象不能被强制为基本类型。
3.1.6 Java流控制下面几个控制结构是从C语言借鉴的。
分支结构if/else分支结构 if (Boolean) { statemanets; } else { statements; } switch分支结构 switch(expr1) { case expr2: statements; break; caseexpr3: statements; break; default: statements; break; }循环结构for循环结构 for (init expr1;test expr2;increment expr3) { statements; }While循环结构While(Boolean) { statements; }Do循环结构 do { statements; } while (Boolean);一般顺序控制break [label] continue [label] reutrn expr; label:statement;for循环例子下面是一个程序例子,画几条线,分别用红,绿,蓝颜色,这段程序可能是Java函数的一部分: int count; for (count=1;count<=12;count++) { switch (count % 3) } case 0: setColor(Color.red); break; case 1: setColor(Color.blue); break; case 2: setColor(Color.green); break; } g.drawLine(10,count*10,80,count*10); }3.2 Java变量和函数的实例Java的类包含变量和函数。