当前位置:文档之家› java程序练习题与答案

java程序练习题与答案

1、定义一个表示水果的类Fruit,要求如下:
(1)类的成员变量:fName表示水果名称,fColor表示水果颜色。
(2)类的成员方法:show_fName ():获得水果名称,show_fColor ():获得水果颜色
参考答案:
public class Fruit
{
private String fName;
private String fColor;
Fruit(String fName,String fColor) {
this.fName=fName;
this.fColor=fColor;
}
void show_fName(){
System.out.println("the Fruit Name is:"+fName);
}
void show_fColor(){
System.out.println("the Fruit Color is:"+fColor);
}
public static void main(String args[]){
Fruit Lee=new Fruit("Apple","Red");
Lee.show_fName();
Lee.show_fColor();
}
}
2.计算个人所得税。设某人月收入为x元,假设个人所得税征收方法如下:
当800当2800当28000
参考答案:
package com.task04;
import javax.swing.*;
public class ComputeTax{
public static void main(String[] args){

double x=0,y=0,tax=0;
x=Double.parseDouble(JOptionPane.showInputDialog("请输入工资收入",new Double(x)));
y=x-800;
if(x<=800)tax=0;
else if((x>800)&&(x<=1300))tax=0.05*y;
else if((x>1300)&&(x<=2800))tax=0.1*y;
else if((x>2800)&&(x<=5800))tax=0.15*y;
else if((x>5800)&&(x<=28000))tax=0.2*y;
else tax=0.3*y;
System.out.println("纳税光荣:");
System.out.println("您的月收入为"+x+"元");
System.out.println("您应交的所得税为"+tax+"元");
}
}
3.编写程序,实现求3个数中最大值的功能。
参考答案如下:
package com.task04;
public class xiti4_3_4{
public static void main(String[] args){
double x=0,y=0,z=0,max=0;
x=Double.parseDouble(args[0]);
y=Double.parseDouble(args[1]);
z=Double.parseDouble(args[2]);
if(x>=y)
{
if(x>z)
max=x;
else
max=z;
}
else
{
if(y>z)
max=y;
else
max=z;
}
System.out.println(max);
}
}
4、求 a+aa+aaa+.......+aaaaaaaaa=?,其中a为1至9之中的一个数,项数也可以指定? 例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
参考答案:
import java.util.*;
public class A {
public static void main(String[] args) {
long a , b = 0, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("输入数字a的值: ");
a = s.nextInt();
System.out.print("输入相加的项数:");
int n = s.nextInt();
int i = 0;
while(i < n) {
b = b + a;
sum = sum + b;
a = a * 10;
++ i;
}
System.out.println(sum);
}
}
5、写一个方法用来生成一个正整数小于100的随机整形数组,该方法返回一个int[] 类型,需要一

个int型参数,数组的大小由传进来的参数决定。
参考答案:
import java.util.*;
public class A {
public int[] createArray(int length){
int[] a = new int[length];
Random rand = new Random();
for(int i=0;ia[i] = rand.nextInt(101);
}
return a;
}
public static void main(String[] args){
int[] b = new A().createArray(5);
for(int i=0;i<5;i++){
System.out.println(b[i]);
}
}
}

6.编写一个程序ComputeArea,当程序运行时,从键盘上输入圆的半径,在控制台输出圆的周长和面积。要求:圆的周长只保留整数部分,舍掉小数部分。

参考答案:
package com.task03;
public class ComputeArea {
public static void main(String[] args){
final double PI=3.1415926; //定义常量PI
double r,perimeter,area;
int int_p;
r=Double.parseDouble(args[0]); //字符串与数值类型数据进行转换
System.out.println("r="+r);
perimeter=2*PI*r;
int_p=(int)perimeter; //强制类型转换
area=PI*r*r;
System.out.println("圆的周长(只保留整数部分)为:"+int_p);
System.out.println("圆的面积为:"+area);
}
}

相关主题
文本预览
相关文档 最新文档