JAVA练习题含答案 ANSWERS TO PRACTICE 2.

合集下载

Java 网络编程练习题及答案

Java 网络编程练习题及答案

Java 网络编程练习题及答案Java 网络编程是指利用Java语言进行网络通信和传输数据的技术。

在日常的软件开发和网络应用中,网络编程是一个非常重要的方向。

本文将提供一些Java网络编程的练习题,并给出相应的答案,以帮助读者更好地掌握这一技术。

一、基础练习题1. 编写一个简单的Java程序,实现客户端向服务器端发送消息,并在服务器端打印接收到的消息。

```java// 客户端代码import java.io.*;import .*;public class Client {public static void main(String[] args) throws IOException {Socket socket = new Socket("localhost", 8888);OutputStream outputStream = socket.getOutputStream();PrintWriter out = new PrintWriter(outputStream, true);out.println("Hello, Server!");InputStream inputStream = socket.getInputStream();BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));String response = in.readLine();System.out.println("Server: " + response);out.close();in.close();socket.close();}}// 服务器端代码import java.io.*;import .*;public class Server {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(8888);System.out.println("Server is running...");Socket socket = serverSocket.accept();InputStream inputStream = socket.getInputStream();BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));String request = in.readLine();System.out.println("Client: " + request);OutputStream outputStream = socket.getOutputStream();PrintWriter out = new PrintWriter(outputStream, true);out.println("Hello, Client!");out.close();in.close();socket.close();serverSocket.close();}}```2. 编写一个Java程序,实现多个客户端同时向服务器端发送请求,并在服务器端打印接收到的请求。

Java基础练习题 附答案

Java基础练习题 附答案
A.1B.2 C.3D.default
11)以下程序的输出结果为
publicclasstest{
publicstaticvoidmain(Stringagrs[]){
charc1=’B’,c2=’C’;
if(c1+1<c2)++c1;
}
}
A.BB.bC.CD.c
12)假设a是int类型变量,并初始化为1,则下列哪个为合法的条件语句?
}
}
A.0B.1 C.5D.4E.24
2)设有如下类
classLoop{
publicstaticvoidmain(String[]agrs){
intx=0;inty=0;
outer:
for(x=0;x<100;x++){
middle:
for(y=0;y<100;y++){
y="+y);
if(y==10){<<<insertcode>>>}
B.第9行出现运行错误;
C.输出True
D.输出False
8)以下程序的编译和运行结果为?
classtest{
staticbooleancheck;
publicstaticvoidmain(Stringargs[]){
inti;
if(check==true)
i=1;
else
i=2;
if(i=2)i=i+2;
E.publicstaticbooleanmain(Stringa[]);
2)编译和运行以下代码的结果为:
publicclassMyMain{

java考试编程题库及答案

java考试编程题库及答案

java考试编程题库及答案Java考试编程题库及答案1. 基础语法题- 题目:编写一个Java程序,实现两个整数的加法运算,并打印结果。

- 答案:```javapublic class Addition {public static void main(String[] args) {int num1 = 5;int num2 = 10;int sum = num1 + num2;System.out.println("The sum is: " + sum);}}```2. 控制结构题- 题目:编写一个Java程序,判断一个整数是否为素数,并打印结果。

- 答案:```javapublic class PrimeCheck {public static void main(String[] args) {int number = 29;if (isPrime(number)) {System.out.println(number + " is a primenumber.");} else {System.out.println(number + " is not a prime number.");}}public static boolean isPrime(int n) {if (n <= 1) return false;for (int i = 2; i <= Math.sqrt(n); i++) {if (n % i == 0) return false;}return true;}}```3. 数组与循环题- 题目:编写一个Java程序,打印数组中所有元素的平方。

- 答案:```javapublic class SquareElements {public static void main(String[] args) {int[] numbers = {1, 2, 3, 4, 5};for (int i = 0; i < numbers.length; i++) {int square = numbers[i] * numbers[i];System.out.println("Square of " + numbers[i] + " is " + square);}}}4. 面向对象题- 题目:定义一个名为`Car`的类,包含属性`color`和`speed`,以及一个方法`increaseSpeed(int increment)`来增加速度。

java基础练习及参考答案

java基础练习及参考答案

java基础练习及参考答案java基础练习编程结构:1.如果一个数从左边念和从右边念都就是同一个数,就称作回文数.比如:686就是一个回文数.编程找到1000以内所有的回文数.packagetext01;importjava.util.*;publicclasst1{publicstaticvoidmain(stringargs[]){inti,n,m,count=0;system.out.p rintln(\);for(i=1;i<=1000;i++){n=i;m=0;while(n!=0){m=m*10+n;n/=10;}if(m==i){sy stem.out.println(m);count++;}}}}2.一位妇女在河边洗碗.邻居们问:\家里去了多少个客人?\她提问:\每两个客人氰化钠一个菜碗,每三个客人氰化钠一个汤碗,每四个客人氰化钠一个饭碗,共用碗65个\反问共去了多少客人?packaget1;publicclasst2{publicstaticvoidmain(stringargs[]){intx=0;while(x<65){inti=x/2;i ntj=x/3;intm=x/4;if(i+j+m==65){system.out.println(x);}x++;}}}字符串:1/51.给定一个字符串“abc123abc”,求:1)将字串全部转为大写abc123abcpackagetext01;importjava.util.*;publicclasst1{publicstaticvoidmain(stringargs[]){stringstr=\;stringstr1=str.to uppercase();system.out.println(str1);}}2)截取字串的前3个字符abcpackagetext01;importjava.util.*;publicclasst1{publicstaticvoidmain(stringargs[]){stringstr=\;stringa[]=str.split(\);system.out.println(a[0]);}}3)去掉字符中两头的空格abc123abcpackagetext01;publicclasst2{publicstaticvoidmain(string[]args){stringstring=\;string=mytrim( string);system.out.println(\+string+\);}publicstaticstringmytrim(stringstring) {intstart=0;intend=string.length()-1;while(start<=end&&string.charat(start)==''){start++;}while(start<=end&&strin g.charat(end)==''){end--;}returnstring.substring(start,end+1);}}4)搜寻字母a发生的边线6packagetext01;importjava.util.*;publicclasst1{publicstaticvoidmain(stringargs[]){stringstr=\;system.out.println(str.indexof(\));}}2.取值一个字符串“helloworld.”,将字符串间的空格换成.2/5(提示信息:需用replaceall或循环方式处置)。

JAVA习题题目及答案

JAVA习题题目及答案

第1章问答题及作业题第1章问答题1、发明Java语言的原因是什么?发明Java语言的主要贡献者是谁?2、“Java编译器将源文件编译生成的字节码是机器码”,这句话正确吗?3、Java程序的主类必须含有怎样的方法?4、“Java应用程序必须含有一个类是public类”,这句话正确吗?5、“Java Applet程序的主类必须是public类”,这句话正确吗?6、请叙述Java源文件的命名规则。

7、源文件生成的字节码在运行时都加载到内存中吗?8、怎样编写加载运行Java Applet的简单网页?9、编译器使用“-source”参数的作用是什么?“-source”参数的默认取值是什么?第1章作业题1.参照例1-1编写一个Java应用程序,程序能在命令行中输出“早上好,Good Morning”。

2.参照例1-2编写一个Java Applet程序,程序能在浏览器中显示“你好,Hello”。

第2章问答题及作业题第2章问答题1、什么是标识符?标识符的规则是什么?2、什么是关键字?请说出5个关键字。

3、Java的基本数据类型是什么?4、下列哪些语句是错误的?int x=120;byte b=120;b=x;5、下列哪些语句是错误的?float x=12.0;float y=12;double d=12;y=d;6、下列两条语句的作用是等价的吗?char x=97;char x=’a’;7、下列语句输出的结果是什么?int a=97;byte b1=(byte)128;byte b2=(byte)-129;System.out.printf(“%c,%d,%d”,a,b1,b2);8、数组是基本数据类型吗?怎样获取一维数组的长度?9、假设有两个int类型数组:int[] a=new int[10];int[] b=new int[8];b=a;a[0]=100;b[0]的值一定是100吗?10、下列两条语句的作用等价吗?int[] a={1,2,3,4,5,6,7,8};int[] a=new int[8];}第2章作业题1.参照例2-1编写一个Java应用程序,输出俄文字母表。

java基础练习题及答案

java基础练习题及答案

java基础练习题及答案1. 编写一个Java程序,计算并打印出1到100之间所有偶数的和。

```javapublic class EvenNumberSum {public static void main(String[] args) {int sum = 0;for (int i = 1; i <= 100; i++) {if (i % 2 == 0) {sum += i;}}System.out.println("1到100之间所有偶数的和为: " + sum);}}```2. 编写一个Java程序,用循环打印出以下图案:```***************``````javapublic class PatternPrinting {public static void main(String[] args) {for (int i = 1; i <= 5; i++) {for (int j = 1; j <= i; j++) {System.out.print("*");}System.out.println();}}}```3. 编写一个Java程序,判断一个给定的整数是否是素数(质数)。

```javapublic class PrimeNumberCheck {public static void main(String[] args) {int number = 29;boolean isPrime = true;for (int i = 2; i <= Math.sqrt(number); i++) {if (number % i == 0) {isPrime = false;break;}}if (isPrime) {System.out.println(number + " 是素数");} else {System.out.println(number + " 不是素数");}}}```4. 编写一个Java程序,找出一个整数数组中的最大值和最小值。

JAVA练习题含答案-answertopratice3

JAVA练习题含答案-answertopratice3

JAVA练习题含答案-answertopratice3Chapter 3Flow of ControlMultiple Choice1)An if selection statement executes if and only if:(a)the Boolean condition evaluates to false.(b)the Boolean condition evaluates to true.(c)the Boolean condition is short-circuited.(d)none of the above.Answer:B (see page 97)2) A compound statement is enclosed between:(a)[ ](b){ }(c)( )(d)< >Answer:B (see page 98)3) A multi-way if-else statement(a)allows you to choose one course of action.(b)always executes the else statement.(c)allows you to choose among alternative courses of action.(d)executes all Boolean conditions that evaluate to true.Answer:C (see page 100)4)The controlling expression for a switch statement includes all of the following types except:(a)char(b)int(c)byte(d)doubleAnswer:D (see page 104)Copyright ? 2006 Pearson Education Addison-Wesley. All rights reserved. 125)To compare two strings lexicographically the String method ____________ should be used.(a)equals(b)equalsIgnoreCase(c)compareTo(d)==Answer:C (see page 112)6)When using a compound Boolean expression joined by an && (AND) in an if statement:(a)Both expressions must evaluate to true for the statement to execute.(b)The first expression must evaluate to true and the second expression must evaluate to false forthe statement to execute.(c)The first expression must evaluate to false and the second expression must evaluate to true forthe statement to execute.(d)Both expressions must evaluate to false for the statement to execute.Answer:A (see page 116)7)The OR operator in Java is represented by:(a)!(b)&&(c)| |(d)None of the aboveAnswer:C (see page 116)8)The negation operator in Java is represented by:(a)!(b)&&(c)| |(d)None of the aboveAnswer:A (see page 116)9)The ____________ operator has the highest precedence.(a)*(b)dot(c)+=(d)decrementAnswer:B (see page 123)10)The looping mechanism that always executes at least once is the _____________ statement.(a)if…else(b)do…while(c)while(d)forAnswer:B (see page 132).Chapter 3 Flow of Control 311) A mixture of programming language and human language is known as:(a)Algorithms(b)Recipes(c)Directions(d)PseudocodeAnswer:D (see page 134)12)When the number of repetitions are known in advance, you should use a ___________ statement.(a)while(b)do…while(c)for(d)None of the aboveAnswer:C (see page 141)13)To terminate a program, use the Java statement:(a)System.quit(0);(b)System.end(0);(c)System.abort(0);(d)System.exit(0);Answer:D (see page 148)True/False1)An if-else statement chooses between two alternative statements based on the value of a Booleanexpression.Answer:True (see page 96)2)You may omit the else part of an if-else statement if no alternative action is required.Answer:True (see page 97)3)In a switch statement, the choice of which branch to execute is determined by an expression given inparentheses after the keyword switch.Answer:True (see page 104)4)In a switch statement, the default case is always executed.Answer:False (see page 104)5)Not including the break statements within a switch statement results in a syntax error.Answer:False (see page 104)6)The equality operator (==) may be used to test if two string objects contain the same value.Answer:False (see page 111)47)Boolean expressions are used to control branch and loop statements.Answer:True (see page 116)8)The for statement, do…while statement and while statement are examples of branching mechanisms.Answer:False (see page 130)9)An algorithm is a step-by-step method of solution.Answer:True (see page 134)10)The three expressions at the start of a for statement are separated by two commas.Answer:False (see page 137)Short Answer/Essay1)What output will be produced by the following code?public class SelectionStatements{public static void main(String[] args){int number = 24;if(number % 2 == 0)System.out.print("The condition evaluated to true!");elseSystem.out.print("The condition evaluated to false!");}}Answer:The condition evaluated to true!.Chapter 3 Flow of Control 52)What would be the output of the code in #1 if number was originally initialized to 25?Answer:The condition evaluated to false!3)Write a multi-way if-else statement that evaluates a persons weight on the following criteria: Aweight less than 115 pounds, output: Eat 5 banana splits! A weight between 116 pounds and 130 pounds, output: Eat a banana split! A weight between 131 pounds and 200 pounds, output: Perfect!A weight greater than 200 pounds, output: Plenty of banana splits have been consumed!Answer:if(weight <= 115)System.out.println("Eat 5 banana splits!");else if(weight <= 130)System.out.println("Eat a banana split!");else if(weight <=200)System.out.println("Perfect!");elseSystem.out.println("Plenty of banana splits have been consumed!");4)Write an if-else statement to compute the amount of shipping due on an online sale. If the cost ofthe purchase is less than $20, the shipping cost is $5.99. If the cost of the purchase over $20 and at most $65, the shipping cost is $10.99. If the cost of the purchase is over $65, the shipping cost is $15.99.Answer:if(costOfPurchase < 20)shippingCost = 5.99;else if((costOfPurchase > 20)&&(costOfPurchase <= 65))shippingCost = 10.99;elseshippingCost = 15.99;5)Evaluate the Boolean equation: !( ( 6 < 5) && (4 < 3))Answer:True66)Write Java code that uses a do…while loop that prints even numbers from 2 through 10.Answer:int evenNumber = 2;do{System.out.println(evenNumber);evenNumber += 2;}while(evenNumber <= 10);7)Write Java code that uses a while loop to print even numbers from 2 through 10.Answer:int evenNumber = 2;while(evenNumber <= 10){System.out.println(evenNumber);evenNumber += 2;}Answer:8)Write Java code that uses a for statement to sum the numbers from 1 through 50. Display the totalsum to the console.Answer:.Chapter 3 Flow of Control 7 int sum = 0;for(int i=1; i <= 50; i++){sum += i;}System.out.println("The total is: " + sum);9)What is the output of the following code segment?public static void main(String[] args){int x = 5;System.out.println("The value of x is:" + x);while(x > 0){x++;}System.out.println("The value of x is:" + x);}Answer:.10)Discuss the differences between the break and the continue statements when used in loopingmechanisms.Answer:When the break statement is encountered within a looping mechanism, the loopimmediately terminates. When the continue statement is encountered within a looping mechanism, the current iteration is terminated, and execution continues with the next iteration of the loop.8Programming projects:1. Write a complete Java program that prompts the user fora series of numbers to determine the smallestvalue entered. Before the program terminates, display the smallest value.Answer:import java.util.Scanner;public class FindMin{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);int smallest = 9999999;String userInput;boolean quit = false;System.out.println("This program finds the smallest number"+ " in a series of numbers");System.out.println("When you want to exit, type Q");.Chapter 3 Flow of Control 9 while(quit != true){System.out.print("Enter a number: ");userInput = keyboard.next();if(userInput.equals("Q") || userInput.equals("q")){quit = true;}else{int userNumber = Integer.parseInt(userInput);if(userNumber < smallest)smallest = userNumber;}}System.out.println("The smallest number is " + smallest);System.exit(0);}10}2. Write a complete Java program that uses a for loop to compute the sum of the even numbers and thesum of the odd numbers between 1 and 25.public class sumEvenOdd{public static void main(String[] args){int evenSum = 0;int oddSum = 0;//loop through the numbersfor(int i=1; i <= 25; i++){if(i % 2 == 0){//even numberevenSum += i;}else{oddSum += i;.Chapter 3 Flow of Control 11 }}//Output the resultsSystem.out.println("Even sum = " + evenSum);System.out.println("Odd sum = " + oddSum);}}/*** Question2.java** This program simulates 10,000 games of craps.* It counts the number of wins and losses and outputs the probability* of winning.** Created: Sat Mar 05, 2005** @author Kenrick Mock* @version 1*/public class Question2{private static final int NUM_GAMES = 10000;/*** This is the main method. It loops 10,000 times, each simulate* a game of craps. Math.random() is used to get a random number,* and we simulate rolling two dice (Math.random() * 6 + 1 simulates* a single die).*/public static void main(String[] args){// Variable declarationsint numWins = 0;12int numLosses = 0;int i;int roll;int point;// Play 10,000 gamesfor (i=0; i<="" p="">{// Simulate rolling the two dice, with values from 1-6roll = (int) (Math.random() * 6) + (int) (Math.random() * 6) + 2;// Check for initial win or lossif ((roll == 7) || (roll == 11)){numWins++;}else if ((roll==2) || (roll==3) || (roll==12)){numLosses++;}else{// Continue rolling until we get the point or 7point = roll;do{roll = (int) (Math.random() * 6) + (int) (Math.random() * 6) +2;if (roll==7){numLosses++;}else if (roll==point){numWins++;}} while ((point != roll) && (roll != 7));}}// Output probability of winningSystem.out.println("In the simulation, we won " + numWins +" times and lost " + numLosses + " times, " +" for a probability of " +(double) (numWins) / (numWins+numLosses));}} // Question2.Chapter 3 Flow of Control 13 /*** Question6.java** Created: Sun Nov 09 16:14:44 2003* Modified: Sat Mar 05 2005, Kenrick Mock** @author Adrienne Decker* @version 2*/import java.util.Scanner;public class Question6{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);while ( true ){System.out.println("Enter the initial size of the green crud" + " in pounds.\nIf you don't want to " +"calculate any more enter -1.");int initialSize = keyboard.nextInt();if ( initialSize == -1){break;} // end of if ()System.out.println("Enter the number of days: ");int numDays = keyboard.nextInt();int numOfRepCycles = numDays / 5;int prevPrevGen = 0;int prevGen = initialSize;int finalAnswer = initialSize;for ( int i = 0; i < numOfRepCycles; i++ ){finalAnswer = prevPrevGen + prevGen;14prevPrevGen = prevGen;prevGen = finalAnswer;} // end of for ()System.out.println("The final amount of green crud will be: "+ finalAnswer + " pounds.\n");} // end of while ()}} // Question6/*** Question7.java** Created: Sun Nov 09 16:14:44 2003* Modified: Sat Mar 05 2005, Kenrick Mock** @author Adrienne Decker* @version 2*/import java.util.Scanner;public class Question7{public static void main(String[] args){Scanner keyboard = new Scanner(System.in);String line;do{System.out.println("Enter the value of X for this calculation."); double x = keyboard.nextDouble();double sum = 1.0;double temp = 1.0;for ( int n = 1; n <= 10; n++){System.out.print("For n equal to: " + n.Chapter 3 Flow of Control 15+ ", the result of calculating e^x is: ");for ( int inner = 1; inner <= n; inner++){temp = 1.0;for ( double z = inner; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);sum = 1.0;} // end of for ()System.out.print("For n equal to 50, the result of " + "calculating e^x is: ");for ( int n = 1; n <= 50; n++){temp = 1.0;for ( double z = n; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);sum = 1;System.out.print("For n equal to 100, the result of " + "calculating e^x is: ");for ( int n = 1; n <= 100; n++){temp = 1.0;for ( double z = n; z > 0; z--){temp = temp * (x/z);} // end of for ()sum += temp;} // end of for ()System.out.println(sum);System.out.println("\nEnter Q to quit or Y to go again.");16keyboard.nextLine(); // Clear bufferline = keyboard.nextLine();} while (line.charAt(0)!='q' && line.charAt(0)!='Q'); // end of while () }} // Question7.。

java的考试题及答案

java的考试题及答案

java的考试题及答案1. 以下哪个选项是Java中的数据类型?A. IntegerB. StringC. Both A and BD. None of the above答案:C2. Java中的方法声明需要包含哪些部分?A. 返回类型、方法名、参数列表、方法体B. 返回类型、方法名、参数列表C. 方法名、参数列表、方法体D. 返回类型、方法名、方法体答案:B3. 在Java中,哪个关键字用于声明一个类?A. classB. structC. functionD. interface答案:A4. Java中哪个关键字用于实现类的继承?A. extendsB. implementsC. inheritsD. uses答案:A5. Java中的多态性是如何实现的?A. 通过方法重载B. 通过方法覆盖C. 通过接口实现D. 通过抽象类和接口答案:D6. 在Java中,以下哪个选项是正确的数组初始化方式?A. int[] myArray = new int[5];B. int myArray[] = new int[5];C. Both A and BD. None of the above答案:C7. Java中,哪个关键字用于声明一个接口?A. classB. structC. interfaceD. enum答案:C8. 在Java中,以下哪个选项是正确的异常处理语句?A. try-catchB. try-finallyC. Both A and BD. None of the above答案:C9. Java中,哪个关键字用于声明一个枚举类型?A. enumB. enumarateC. enumerationD. list答案:A10. 在Java中,以下哪个选项是正确的泛型类声明?A. List<String> myList;B. List myList;C. Both A and BD. None of the above答案:A。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Multiple Choice1Which operator is used to concatenate two strings?(a+(b–(c*(d/Answer:A(see page352Which operator returns the remainder of integer division? (a%(b/(c*(dnone of the aboveAnswer:A(see page263What is the value of the variable c in the statements that follow? String phrase="Make hay while the sun is shining.";char c=phrase.charAt(10;(aw(bh(ci(dNone of the aboveAnswer:B(see page404The escape sequence the represents the new-line character is:(a\r(b\t(c\n(d\\Answer:C(see page435The syntax that declares a Java named constant named SALES_TAX is: (adouble SALES_TAX=7.50;(bpublic double SALES_TAX=7.50;(cpublic static double SALES_TAX=7.50;(dpublic static final double SALES_TAX=7.50;Answer:D(see page476In Java,a block comment is delimited by:(a*//*(b/*/*(c/**/(d*/*/Answer:C(see page507To mark a block comment for inclusion in the Javadoc documentation,the block mustbe delimited by:(a/***/(b*/**/(c**//*(d**/*/Answer:A(see page508Valid arguments to the System.out ob ject’s println method include:(a“Anything with double quotes”(bString variables(cVariables of type int(dAll of the aboveAnswer:D(see page599Which statement or group of statements produces the output:Java programming isfun!(aSystem.out.print(Java programming;System.out.print(is fun!;(bSystem.out.println(Java programming is fun!;(cSystem.out.println(“Java programming”;System.out.println(“is fun!”;(dSystem.out.print(“Java programming”System.out.println(“is fun!”;Answer:D(see page6010If a hyphen is added after the%in a format specifier,the output will be_________. (aLeft justified(bRight justified(cCentered(dNone of the aboveAnswer:A(see page6411The statement:System.out.printf("%6.2f",597.7231;displays:(a597.723(b597.72(c000597.72(dNone of the aboveAnswer:B(see page6412The Java method printf is based on the________language.(aPascal(bC++(cC(dADAAnswer:C(see page6713The class NumberFormat allows you to specify a constant representing which country’scurrency format should be used.To use this constant you must import:(ajava.util.Locale(bjava.util.Currency(cjava.util.Properties(dNone of the above.Answer:A(see page7114Standard code libraries in Java are called:(aMethods(bClasses(cPackages(dStatementsAnswer:C(see page7215What Java package includes the class Scanner?(aawt(bswing(cio(dutilAnswer:D(see page78True/False1Objects of type String are strings of characters that are written within single quotes.Answer:False(see page342In Java,Strings are immutable objects.Immutable objects can be changed.Answer:False(see page443An advantage of using the Unicode character set is that it easily handles languagesother than English.Answer:True(see page444Java uses the ASCII character set.Answer:False(see page441Efficiency is lost in importing the entire package instead of importing the classes youuse.Answer:False(see page732Every Java program automatically imports the java.util package.Answer:False(see page733The new line character is represented as‘\n’.Answer:True(see page614The method printf is used the same way as the method println but has the added featurethat allows you to add formatting instructions.Answer:False(see page615The printf method can be used to output multiple formatted values.Answer:True(see page646The Scanner class has a method next that allows an entire line of string text to be read.Answer:False(see page807Echoing input is good programming practice because it can reveal problems in theinput.Answer:True(see page80Short Answer/Essay1How is the%(modulusoperator used?What is the common use of the modulusoperator?Answer:The modulus operator is used to return the remainder in integer division.For example,the modulus operator is commonly used to determine if a number is an even or an odd value.2What is the output of the following Java statements?//String method examplesString str="Java Programming!";System.out.println(str.equals("Java Programming!";System.out.println(str.toLowerCase(;System.out.println(str.toUpperCase(;System.out.println(str.substring(5,8;System.out.println(stIndexOf("m";Answer:truejava programming!JAVA PROGRAMMING!Pro123 Write a Java statement to access the 7th character in the String variable myString and place it in the char variable c. Answer: c = myString.charAt(6;4 Write a Java statement to determine the length of a string variable called input. Store the result in an integer variable called strLength. Answer: int strLength = input.length(;5 Write ONE Java statement to display your first and last name on two separate lines. Answer: System.out.print("Wally\nWonders";6 Write a complete Java console application that prompts the user for two numbers, multiplies the numbers, and then displays the result to the user. Answer: import java.util.Scanner; public class ConsoleMultiply { public static void main(String[] args { //Create the scanner object for console input Scanner keyboard = new Scanner(System.in; //Prompt the user for the first number System.out.print("Enter the first integer: "; //Read the input int firstNumber = keyboard.nextInt(; //Prompt the user for the second number System.out.print("Enter the second integer: ";//Read the second number int secondNumber = keyboard.nextInt(;System.out.println(firstNumber + "*" + secondNumber + " is " + firstNumber * secondNumber; } } 7 Write a Java statement to create and initialize a Scanner object named input. Answer: Scanner input = new Scanner(System.in; 8 Consider the following code snippet. int i = 10; int n = i++%5; 1)What are the values of i and n after the code is executed? Answer: i is 11, and n is 0. 2)What are the final values of i and n if instead of using the postfix increment operator (i++, you use the prefix version (++i? Answer: i is 11, and n is 1. 9 Programming projects : question 2 and 3 (see page 93 importjava.util.Scanner; public class Question2 { public static void main(String[] args { // Variable declarations Scanner scan = new Scanner(System.in; String first; String last; System.out.println("Enter your first name:"; first = scan.nextLine(;System.out.println("Enter your last name:"; last = scan.nextLine(; System.out.println(first + " " + last + " turned to Pig Latin is:"; // First convert first name to pig latinString pigFirstName = first.substring(1,first.length( + first.substring(0,1 + "ay"; // Then capitalize first letter pigFirstName = pigFirstName.substring(0,1.toUpperCase( +pigFirstName.substring(1,pigFirstName.length(; // Repeat for the last name String pigLastName = last.substring(1,last.length( + last.substring(0,1 + "ay"; // Then capitalize first letter pigLastName = pigLastName.substring(0,1.toUpperCase( + pigLastName.substring(1,pigLastName.length(; System.out.println(pigFirstName + " " + pigLastName; } } // Question2 import java.util.Scanner; public class Question3 { public static void main(String[] args { Scanner keyboard = new Scanner(System.in; System.out.println("Enter first number to add:"; int first = keyboard.nextInt(; System.out.println("Enter second number to add"; int second = keyboard.nextInt(; int result = first + second; System.out.println("Adding " + first + " + " + second + " equals " + result; System.out.println("Subtracting " + first + " - " + second + " equals " + (first - second; System.out.println("Multiplying " + first + " * " + second + " equals " + (first * second; } } // Question3。

相关文档
最新文档