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。

JAVA练习题含答案 ANSWERS TO PRACTICE 2

JAVA练习题含答案 ANSWERS TO PRACTICE 2
2) What is the output of the following Java statements? //String method examples
String 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"));
(b) \t
(c) \n
(d) \\
Answer:
C (see page 43)
5) The syntax that declares a Java named constant named SALES_TAX is:
(a) double SALES_TAX = 7.50;
(b) public double SALES_TAX = 7.50;
multiplies the numbers, and then displays the result to the user. Answer:
Answer:
True (see page 61)
4) The method printf is used the same way as the method println but has the added feature that allows you to add formatting instructions.

JAVA练习题含答案-answerstopractise1

JAVA练习题含答案-answerstopractise1

JAVA练习题含答案-answerstopractise1Chapter 1 Getting StartedMultiple Choice1)Java is an object-oriented programming language. An object-oriented language(a)Uses structured programming.(b)Views a program as consisting of objects which communicate through interactions.(c)Functionally breaks down problems into smaller, more manageable problems.(d)All of the above.Answer:B (see page 3)2)In Java, the equal sign is used as the ___________ operator.(a)increment(b)decrement(c)assignment(d)negationAnswer:C (see page 7)3)In Java, source code is compiled into object code called ______________.(a)Bit-code(b)Class code(c)Method code(d)Byte-codeAnswer:D (see page 9)4)The hardest kind of error to detect in a computer program is a:(a)Syntax error(b)Run-time error(c)Logic error(d)All of the aboveAnswer:C (see page 12)15)Identify the invalid Java identifier.(a)1Week(b)Week1(c)amountDue(d)amount_dueAnswer:A (see page 14)6)What is the value of the variable amountDue? double price = 2.50;double quantity = 5;double amountDue = 0;amountDue = price * quantity;(a)12(b)12.25(c)12.5(d)13Answer:C (see page 19)7)What is the value of 7.52e-5?(a)752000.0(b)0.0000752(c)0.000752(d)0.00752Answer:B (see page 22)8)What is the Java expression for 4a2 + 2b * c?(a)(4 * a) + (2 * b) * c(b)(4 * a * a) + ((2 * b) * c)(c)((4 * a * a) + (2 * b)) * c(d)(4 + a * a) + ((2 + b) * c)Answer:B (see page 25)9)What is the Java expression for 27xy?(a)27 + (x * y)(b)27 * (x + y)(c)27 * x * y(d)27x * yAnswer:C (see page 25)10)The value of the expression (int) 27.6 evaluates to:(a)28(b)27(c)26(d)None of the above.Answer:B (see page 20)True/False1)Java began as a language for home appliances.Answer:True (see page 3)2)Applets were designed to run as stand-alone applications.Answer:False (see 5)3)The Java programming language allows you to concatenate two strings using the plus sign.Answer:True (see page 35)4)Java is an interpreted language.Answer:True (see page 9)5)Java does not require that a variable be declared before it is used within a program.Answer:False (see page 14)6) A variable of type boolean can be explicitly converted to that of type int.Answer:False (see page 21)7)The modulus operator, %, returns the remainder of integer division.Answer:True (see page 26)8)The result of integer division is truncated in Java.Answer:True (see page 27)Short Answer/Essay1)There are two kinds of Java programs, applications and applets. Define and discuss each.Answer:An application is just a regular. An applet is a little Java program that runs in a Webbrowser. Applets and applications are almost identical. The difference is that applications aremeant to be run on your computer like any other program, whereas an applet is meant to be run froma Web browser. An applet can be sent to another location on the Internet and run there.2)What are the values of the variables a, b, c, and d after the execution of the following expressions?int a = 3;int b = 12;int c = 6;int d = 1;d = d * a;c = c + 2 * a;d = d - b / c;c = c * b % c;b = b / 2;Answer:a: 3b: 6c: 0d: 23)what is the output produced by the following code? class TestP{public static void main(String args[]){int x=5,y=32;float a=8.6f,b=4.0f;System.out.println("x="+x+"y="+y);System.out.println("\ta="+a+"\tb="+b);System.out.println("\nx+y="+x+y+"\ta*b="+a*b);}}Answer:x=5y=32a=8.6 b=4.0x+y=532 a*b=34.4。

Java语言程序设计 课后习题+答案

Java语言程序设计 课后习题+答案

第一章课后习题1.编译Java程序的命令是什么?2.执行Java程序的命令是什么?3.Java应用程序和小程序的区别是什么?4.编写一个application ,实现在屏幕上打印自己名字的功能。

第一章课后习题答案1.编译Java程序的命令是什么?答案:javac 源文件名2.执行Java程序的命令是什么?java 主类名3.Java应用程序和小程序的区别是什么?Java application⏹由Java解释器独立运行字节码⏹由专门的命令行启动程序执行⏹程序中有定义了main()方法的主类Java applet⏹不能独立运行,字节码必须嵌入HTML文档⏹当浏览器调用含applet的Web页面时执行⏹程序中含有java. applet. Applet 类的子类4.编写一个application ,实现在屏幕上打印自己名字的功能。

class Test{public static void main(String[] args){System.out.println(“张三”);}}第二章课后习题(1)一、选择题1.下列变量定义错误的是。

A) int a; B) double b=4.5; C) boolean b=true; D)float f=9.8;2.下列数据类型的精度由高到低的顺序是:a)float,double,int,longb)double,float,int,bytec)byte,long,double,floatd)double,int,float,long3.执行完下列代码后,int a=3;char b='5';char c=(char)(a+b);c的值是?A)’8’ b)53 c)8 d)564.Unicode是一种_____________A) 数据类型 B)java包 C)字符编码 D)java类5.6+5%3+2的值是___________A)2 B)1 C) 9 D)106.下面的逻辑表达式中合法的是__________A)(7+8)&&(9-5) B)(9*5)||(9*7) C)9>6&&8<10 D)(9%4)&&(8*3) 7.java语言中,占用32位存储空间的是__________。

java基础练习题答案

java基础练习题答案

java基础练习题答案一、选择题1. Java是一种:A. 编译型语言B. 解释型语言C. 汇编语言D. 机器语言答案:B2. 以下哪个是Java的基本数据类型?A. StringB. IntegerC. booleanD. Object答案:C3. Java中的main方法是:A. 程序的入口点B. 程序的结束点C. 程序的循环点D. 程序的异常处理点答案:A4. 在Java中,哪个关键字用于定义类?A. classB. functionC. structD. interface答案:A5. Java中的异常处理是通过以下哪个关键字实现的?A. tryB. catchC. finallyD. A和B答案:D二、填空题1. Java是一种面向________的语言。

答案:对象2. Java程序的执行流程是从________方法开始的。

答案:main3. 在Java中,所有的类都是继承自________类。

答案:Object4. 一个Java程序可以包含多个类,但只有一个________类。

答案:公共(public)5. Java的垃圾回收机制用于________内存。

答案:自动回收三、简答题1. 请简述Java的跨平台特性。

答案:Java的跨平台特性主要得益于它的编译和运行机制。

Java 源代码首先被编译成字节码,这些字节码可以在任何安装了Java虚拟机(JVM)的平台上运行,而不需要重新编译。

2. 什么是Java的封装性?答案:封装性是面向对象编程的一个核心概念,它指的是将对象的数据(属性)和行为(方法)捆绑在一起,并隐藏内部实现细节,只通过公共接口与外部交互。

四、编程题1. 编写一个Java程序,计算并打印1到100的整数之和。

```javapublic class SumCalculator {public static void main(String[] args) {int sum = 0;for (int i = 1; i <= 100; i++) {sum += i;}System.out.println("The sum of numbers from 1 to 100 is: " + sum);}}```2. 编写一个Java程序,实现一个简单的计算器,能够进行加、减、乘、除运算。

java练习题2及答案

java练习题2及答案

java练习题2及答案试题编号:重庆邮电大学××××学年××学期一、选择题(每题1分,共30分)1、下列哪些语句关于内存回收的说明是正确的? ()A:程序员必须创建一个线程来释放内存;B:内存回收程序负责释放无用内存; C:内存回收程序允许程序员直接释放内存; D:内存回收程序可以在指定的时间释放内存对象。

2、有下列程序:public class aa{public static void main(String[ ] args) {String s = "18.03";try {double number1 = Double.parseDouble(s);System.out.print(number1);int number2 = Integer.parseInt(s);System.out.println(" " + number2);}catch(NumberFormatException nfe) {System.out.println(" Sorry");}catch(Exception e){}}}执行结果是()A:18.03 B:SorryC:18.03 Sorry D:出现编译错误3、下面哪个选项可以将“hello”字符写入文件file.txt的末尾?()A:OutputStream out= new FileOutputStream ("file.txt");Out.writeBytes ("hello");B:OutputStream os= new FileOutputStream ("file.txt", true); DataOutputStream out = new DataOutputStream(os);out.writeBytes ("hello");C:OutputStream os= new FileOutputStream ("file.txt");DataOutputStream out = new DataOutputStream(os);out.writeBytes ("hello");D:OutputStream os= new OutputStream ("file.txt", true); DataOutputStream out = new DataOutputStream(os);×××××试卷第1页(共××页)out.writeBytes ("hello");4、3. 在启动Java应用程序时可以通过main( )方法一次性地传递多个参数。

java基础笔试题题库及答案

java基础笔试题题库及答案

java基础笔试题题库及答案1. Java中,`int`类型变量默认的初始值是多少?答案:Java中,`int`类型变量默认的初始值是0。

2. 在Java中,`String`类型是可变的还是不可变的?答案:在Java中,`String`类型是不可变的。

3. Java中,`==`和`equals()`方法的区别是什么?答案:在Java中,`==`用于比较两个引用是否指向同一对象(对于基本数据类型是比较值),而`equals()`是一个方法,用于比较对象内容是否相等。

4. Java中,`ArrayList`和`LinkedList`的主要区别是什么?答案:`ArrayList`是基于动态数组实现的,支持快速随机访问;而`LinkedList`是基于双向链表实现的,支持快速的插入和删除操作。

5. Java中,`try-catch-finally`语句块的作用是什么?答案:`try-catch-finally`语句块用于异常处理。

`try`块用于捕获异常,`catch`块用于处理异常,`finally`块用于执行清理操作,无论是否发生异常都会执行。

6. Java中,`HashMap`和`Hashtable`的主要区别是什么?答案:`HashMap`允许键和值为null,是非同步的;而`Hashtable`不允许键和值为null,是同步的。

7. Java中,什么是垃圾回收?它是如何工作的?答案:垃圾回收是Java中自动释放不再使用的对象所占内存的过程。

它通过识别不再被任何引用指向的对象来进行回收。

8. Java中,`synchronized`关键字的作用是什么?答案:`synchronized`关键字用于实现多线程同步,确保同一时间只有一个线程可以访问某个特定的资源或代码段。

9. Java中,`final`关键字可以修饰哪些元素?答案:`final`关键字可以修饰变量、方法和类。

被`final`修饰的变量称为常量,其值在初始化后不能被改变;被`final`修饰的方法不能被重写;被`final`修饰的类不能被继承。

java考试题及答案

java考试题及答案

java考试题及答案一、选择题(每题2分,共20分)1. Java语言的标识符可以包含以下哪些字符?A. 数字B. 下划线C. 美元符号D. 空格答案:B2. 下列哪个选项是Java中的关键字?A. classB. mainC. publicD. all of the above答案:D3. Java中,哪个修饰符表示成员变量或方法是私有的?A. publicB. privateC. protectedD. static答案:B4. Java中,哪个关键字用于捕获异常?A. tryB. catchC. finallyD. throw答案:B5. 在Java中,下列哪个数据类型是基本数据类型?A. StringB. intC. ArrayListD. HashMap答案:B6. 下列哪个选项不是Java集合框架的一部分?A. ListB. MapC. SetD. String答案:D7. Java中,哪个关键字用于定义接口?A. classB. interfaceC. abstractD. final答案:B8. 在Java中,下列哪个选项不是线程安全的?A. VectorB. ArrayListC. LinkedListD. HashMap答案:B9. Java中,下列哪个选项是正确的继承关系?A. Object is a subclass of StringB. String is a subclass of ObjectC. Object is a superclass of StringD. String is a superclass of Object答案:B10. 下列哪个选项不是Java中的访问修饰符?A. publicB. privateC. protectedD. global答案:D二、填空题(每题2分,共20分)1. Java中,用于定义类的关键字是______。

答案:class2. Java中,用于定义接口的关键字是______。

java编程练习题及答案

java编程练习题及答案

java编程练习题及答案Java 编程练习题及答案在学习 Java 编程的过程中,进行练习是非常重要的一步。

通过编程练习,可以巩固对 Java 语言的理解,提高编程技巧。

下面我们将提供一些 Java 编程练习题及其答案,供您参考。

一、基本语法练习题1. 编写一个 Java 程序,打印输出 "Hello, World!"。

答案:```public class HelloWorld {public static void main(String[] args) {System.out.println("Hello, World!");}}```2. 编写一个 Java 程序,求解 1 到 100 的所有偶数之和。

答案:```public class SumOfEvenNumbers {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); }}```3. 编写一个 Java 程序,判断一个整数是否为素数。

答案:```public class PrimeNumberChecker {public static void main(String[] args) {int num = 29;boolean isPrime = true;for (int i = 2; i <= num / 2; i++) {if (num % i == 0) {isPrime = false;break;}}if (isPrime && num > 1) {System.out.println(num + " 是素数。

java练习题+答案

java练习题+答案

java练习题+答案1、在下列说法中,选出最正确的一项是( )。

1.Java语言是以类为程序的基本单位的2.Java语言是不区分大小写的3.多行注释语句必须以//开始4.在Java语言中,类的源文件名和该类名可以不相同2、下列选项中不属于Java虚拟机的执行特点的一项是( )。

1.异常处理2.多线程3.动态链接4.简单易学3、下列选项中属于Java语言的垃圾回收机制的一项是( )。

1.语法检查2.堆栈溢出检查3.跨平台4.内存跟踪4、下列选项中属于 Java语言的安全性的一项是( )。

1.动态链接2.高性能3.访问权限4.内存跟踪5、下列选项中,属丁JVM执行过程中的特点的一项是( )。

1.编译执行2.多进程3.异常处理4.静态链接6、在Java语言中,那一个是最基本的元素?()1.方法2.包3.对象4.接口7、如果有2个类A和B,A类基于 B类,则下列描述中正确的一个是( )。

1.这2个类都是子类或者超类2.A是B超类的子类3.B是A超类的子类4.这2个类郡是对方的子类8、使用如下哪个保留字可以使只有在定义该类的包中的其他类才能访问该类?()1.abstract2.private3.protected4.不使用保留字9、编译一个定义了3个类和10个办法的Java源文件后,会产生多少个字符码文件,扩展名是什么?()1.13个字节码文件,扩展名是.class2.1个字节码文件,扩展名是.class3.3个字节码文件,扩展名是.java4.3个字节码文件,扩展名是.class10、下列属于Java语言的特点的一项是( )。

1.运算符重载2.类间多重继承3.指针操作4.垃圾回收11、在创建Applet应用程序时,需要用户考虑的问题是( )。

1.窗口如何创建2.绘制的图形在窗口中的位置3.程序的框架4.事件处理12、于Java语言的内存回收机制,下列选项中最正确的一项是( )。

1.Java程序要求用户必须手工创建一个线程来释放内存2.Java程序允许用户使用指针来释放内存3.内存回收线程负责释放无用内存4.内存回收线程不能释放内存对象13、下列关于Java程序结构的描述中,不正确的一项是( )。

java语言试题及答案

java语言试题及答案

java语言试题及答案一、选择题1. Java语言是______。

A. 编译型语言B. 解释型语言C. 编译解释型语言D. 汇编语言答案:C2. 下列哪个是Java语言的关键字?A. ObjectB. ClassC. StringD. Method答案:B3. Java语言中,哪个不是基本数据类型?A. intB. doubleC. StringD. char答案:C4. Java程序的入口点是:A. main()B. start()C. run()D. init()答案:A5. 在Java中,哪个修饰符可以用来声明类、接口、方法或变量,并且只在同一个包中可见?A. privateB. protectedC. defaultD. public答案:C二、填空题6. Java语言的跨平台特性主要得益于______机制。

答案:JVM(Java虚拟机)7. 在Java中,一个类可以继承多个类,但只能继承一个父类,这是因为Java不支持______。

答案:多重继承8. Java中,一个类可以有多个构造函数,这些构造函数之间的区别在于它们的______。

答案:参数列表9. Java中的异常处理是通过______关键字来实现的。

答案:try-catch10. Java语言中,______关键字用于定义接口。

答案:interface三、简答题11. 简述Java语言的垃圾回收机制。

答案:Java语言的垃圾回收机制是指Java运行时环境会自动检测无用对象,并将它们占用的内存释放掉。

垃圾回收器会定期运行,检查对象是否还有引用指向它们,如果没有,就会回收这些对象占用的内存。

12. 描述Java中的集合框架。

答案:Java中的集合框架是一个统一的架构,用于表示和操作集合对象。

它包括接口(如List、Set、Map等)和实现这些接口的类(如ArrayList、HashSet、HashMap等)。

集合框架提供了一种高效的方式来存储、访问和管理数据集合。

Java-2实用教程习题解答

Java-2实用教程习题解答

Java-2实⽤教程习题解答习题解答习题1(第1章)⼀、问答题1.Java语⾔的主要贡献者是谁?2.开发Java应⽤程序需要经过哪些主要步骤?3.Java源⽂件是由什么组成的?⼀个源⽂件中必须要有public类吗?4.如果JDK的安装⽬录为D:\jdk,应当怎样设置path和classpath的值?5.Java源⽂件的扩展名是什么?Java字节码的扩展名是什么?6.如果Java应⽤程序主类的名字是Bird,编译之后,应当怎样运⾏该程序?7.有哪两种编程风格,在格式上各有怎样的特点?1.James Gosling2.需3个步骤:1)⽤⽂本编辑器编写源⽂件。

2)使⽤javac编译源⽂件,得到字节码⽂件。

3)使⽤解释器运⾏程序。

3.源⽂件由若⼲个类所构成。

对于应⽤程序,必须有⼀个类含有public static void main(String args[])的⽅法,含有该⽅法的类称为应⽤程序的主类。

不⼀定,但⾄多有⼀个public类。

4.set classpath=D:\jdk\jre\lib\;.;5. java和class6. java Bird7.独⾏风格(⼤括号独占⾏)和⾏尾风格(左⼤扩号在上⼀⾏⾏尾,右⼤括号独占⾏)⼆、选择题1.B。

2.D。

1.下列哪个是JDK提供的编译器?A)B)C)D)2.下列哪个是Java应⽤程序主类中正确的main⽅法?A) public void main (String args[ ])B) static void main (String args[ ])C) public static void Main (String args[])D) public static void main (String args[ ])三、阅读程序阅读下列Java源⽂件,并回答问题。

public class Person {void speakHello() {"您好,很⾼兴认识您");" nice to meet you");}}class Xiti {public static void main(String args[]) {Person zhang = new Person();();}}(a)上述源⽂件的名字是什么?(b)编译上述源⽂件将⽣成⼏个字节码⽂件?这些字节码⽂件的名字都是什么?(c)在命令⾏执⾏java Person得到怎样的错误提⽰?执⾏java xiti得到怎样的错误提⽰?执⾏java 得到怎样的错误提⽰?执⾏java Xiti得到怎样的输出结果?1.(a)。

java2实用教程课后习题答案(第三版编程题)

java2实用教程课后习题答案(第三版编程题)

java2实用教程课后习题答案(第三版编程题)3. 编写应用程序,求1!+2!+…+10!。

答:class Fact{public static void main(String args[]){int fact,sum=0;for(int i=1;i<=10;i++){fact=1;for(int j=1;j<=i;j++)fact*=j;sum+=fact;}System.out.println("1到10的阶乘之和是:"+sum);}}4. 编写一个应用程序,求100以内的全部素数。

答:class Primes{ public static void main(String args[]){ int w=1;for(int i=2;i<=100;i++){ for(int j=2;j<i;j++){ w=i%j;if(w==0)break;}if(w!=0)System.out.println(i+"是素数");}}}5. 分别用do―while和for循环计算1+1/2!+1/3!+1/4!+…的前20项和。

答: ①for循环class Sum{public static void main(String args[]){int fact;double sum=0;for(int i=1;i<=20;i++){fact=1;for(int j=1;j<=i;j++)fact*=j;sum+=1.0/fact;}System.out.println(sum);}}②do―while循环long sum=0,data=8;for(int i=1;i<=10;i++){sum=sum+data;data=data*10+8;}System.out.println(sum);}}②while循环class TheSum{public static void main(String args[]){long sum=0,data=8,i=0;while(++i<=10){sum=sum+data;data=data*10+8;}System.out.println(sum);}}8. 编写应用程序,输出满足1+2+3+…+n<8888的最大正整数n。

  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。

相关文档
最新文档