Java课程中心练习题

目录

前言

三、实验三

四、实验四

六、实验六

七、实验七

八、实验八

九、实验九

总结


前言

提示:这是本人平时Java课上作业的练习题


三、实验三

1.第一题

编写一个应用程序,以小时、分、秒读取时间长度,然后全部换算成秒并打印输出结果(例如,1小时28分42秒等于5322秒)。

package demo;
import java.util.Scanner;

public class Demo2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入小时:");
		int num1 = sc.nextInt();
		System.out.println("请输入分钟:");
		int num2 = sc.nextInt();
		System.out.println("请输入秒:");
		int num3 = sc.nextInt();
		int total_S = 0;
		total_S=num1*60*60 + num2*60 +num3;
		System.out.println(""+num1+"小时"+num2+"分"+num3+"秒等于"+total_S+"秒");
		
		
	}

}

2.第二题

编写一个程序,提示输入一个代表总钱数的双精度值,然后确定每种纸币和硬币需要的最少数量以达到输入的总钱数。假设人民币种类如下:佰圆纸钞,伍拾圆纸钞,贰拾圆纸钞,拾圆纸钞,伍圆纸钞,壹圆硬币,伍角硬币,壹角硬币,壹分硬币。(提示:使用求模运算符,自上而下求得每种钱币的数量)。

例如,输入值为127.63元人民币,那么程序应当输出如下结果:

1张佰圆纸钞;

0张伍拾圆纸钞;

1张贰拾圆纸钞;

0张拾圆纸钞;

1张伍圆纸钞;

2个壹圆硬币;

1个伍角硬币;

1个壹角硬币;

3个壹分硬币。

package demo;

import java.util.Scanner;

public class Demo3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		System.out.println("输入值为您想要的人民币:");
		 double money=sc.nextDouble();
//		double money = 127.63;
		final int value1 = 100; //一百
		final int value2 = 50;	//五十
		final int value3 = 20;	//二十
		final int value4 = 10;	//十元
		final int value5 = 5;	//五元
		int a, b, c, d, e, f, g, h, i;
		// 百元
		a = (int) (money / 100);
		// 五十元
		b = (int) ((money - value1 * a) / value2);
		// 二十元
		c = (int) ((money - value1 * a - value2 * b) / value3);
		// 十元
		d = (int) ((money - value1 * a - value2 * b - value3 * c) / value4);
		// 五元
		e = (int) ((money - value1 * a - value2 * b - value3 * c - value4 * d) / value5);
		// 一元
		f = (int) ((money - value1 * a - value2 * b - value3 * c - value4 * d - value5 * e) / 1);

		String[] str = String.valueOf(money).split("\\.");
		int decimal = Integer.parseInt(str[1]);

		// 五角
		g = (decimal / 10) / 5;
		// 一角
		h = (decimal / 10 - 5 * g) / 1;
		// 一分
		i = (decimal % 10);

		System.out.println(""+a+"张百圆纸钞票;\n"
				+ ""+b+"张伍拾圆纸钞票;\n"
						+ ""+c+"张贰拾圆纸钞票;\n"
								+ ""+d+"张拾圆纸钞票;\n"
										+ ""+e+"张伍圆纸钞票;\n"
												+ ""+f+"张壹圆纸钞票;\n"
														+ ""+g+"张伍角纸钞票;\n"
																+ ""+h+"张壹角纸钞票;\n"
																		+ ""+i+"张壹分纸钞票;");
	}

}

四、实验四

按照以下要求修改程序Snowman.java(参照课本)

  1. 将雪人的嘴型变成哭脸的倒弧嘴样;
  2. 把太阳移动到图片的右上角;
  3. 在图片左上角显示你的名字;
  4. 将整个雪人右移50个像素。

package application;
	
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;


public class Test2 extends Application {
	@Override
	public void start(Stage stage) {
		try {
			Ellipse base =new Ellipse(80,210,80,60);
			base.setFill(Color.WHITE);
			
			Ellipse middle =new Ellipse(80,130,50,40);
			middle.setFill(Color.WHITE);
			
			Circle head = new Circle(80,70,30);
			head.setFill(Color.WHITE);
			
			
			Circle r_eye = new Circle(70,60,5);
			Circle l_eye = new Circle(90,60,5);
			Arc mouth = new Arc(80,85,15,10,360,180);
			mouth.setFill(null);
			mouth.setStrokeWidth(3);
			mouth.setStroke(Color.BLACK);//设置画笔颜色
			
			Circle t_button = new Circle(80,120,6);
			t_button.setFill(Color.RED);
			Circle b_button = new Circle(80,140,6);
			b_button.setFill(Color.RED);
			
			Line l_arm= new Line(110,130,160,130);
			l_arm.setStrokeWidth(3);
			Line r_arm= new Line(50,130,0,100);
			r_arm.setStrokeWidth(3);
			
			Rectangle stovepipe = new Rectangle(60,0,40,50);
			Rectangle brim = new Rectangle(50,45,60,5);
			
			//将图案放入面板
			Group hat = new Group(stovepipe,brim);
			hat.setTranslateX(10);
			hat.setRotate(15);
			
			Group snowman = new Group(base,middle,head,l_eye,r_eye,l_arm,r_arm,mouth,
					t_button,b_button,hat);
			snowman.setTranslateX(170);
			snowman.setTranslateY(50);
			
			Circle sun = new Circle(450,50,30);
			sun.setFill(Color.GOLD);
			
			Rectangle ground = new Rectangle(0,250,500,100);
			ground.setFill(Color.STEELBLUE);
			
			Text text1=new Text();
			text1.setText("理工学院软件学院");
			text1.setX(50);
			text1.setY(50);
			
			Group root = new Group(ground,sun,snowman,text1);
			Scene scene = new Scene(root,500,350,Color.LIGHTBLUE);//画板
			stage.setScene(scene);
			stage.setTitle("Snowman");
			stage.show();
			
			
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		launch(args);
	}
}
  1. Rent and Utilities 35%
  2. Transportation 15%
  3. Food 15%
  4. Education 25%
  5. Miscellaneous 10%

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;

public class Test3 extends Application {
	@Override
	public void start(Stage stage) {
		try {
			Arc arc1 = new Arc(200, 200, 100, 100, 0, 126);// 表示0度开始,逆时针旋转60度。
			arc1.setFill(Color.RED);// 设置填充颜色
			arc1.setStroke(Color.BLACK);// 设置画笔颜色
			arc1.setStrokeWidth(2);// 设置画笔宽度
			arc1.setType(ArcType.ROUND);// 此为弧或扇形开关,此时打开的是扇形

			Arc arc2 = new Arc(200, 200, 100, 100, 126, 54);
			arc2.setFill(Color.GREEN);
			arc2.setStroke(Color.BLACK);
			arc2.setStrokeWidth(2);
			arc2.setType(ArcType.ROUND);
			
			Arc arc3 = new Arc(200, 200, 100, 100, 180, 54);
			arc3.setFill(Color.LIGHTBLUE);
			arc3.setStroke(Color.BLACK);
			arc3.setStrokeWidth(2);
			arc3.setType(ArcType.ROUND);
			
			Arc arc4 = new Arc(200, 200, 100, 100, 234, 90);
			arc4.setFill(Color.BLUE);
			arc4.setStroke(Color.BLACK);
			arc4.setStrokeWidth(2);
			arc4.setType(ArcType.ROUND);
			
			Arc arc5 = new Arc(200, 200, 100, 100, 324, 36);
			arc5.setFill(Color.PINK);
			arc5.setStroke(Color.BLACK);
			arc5.setStrokeWidth(2);
			arc5.setType(ArcType.ROUND);
			
			Text l1=new Text(200, 130, "Rent and Utilities");
			Text l2=new Text(50, 160, "Transportation");
			Text l3=new Text(70, 275, "Food");
			Text l4=new Text(170, 320, "Education");
			Text l5=new Text(280, 230, "Miscellaneous");
			
			// 将图案放入面板
			Group root = new Group(arc1,arc2,arc3,arc4,arc5,l1,l2,l3,l4,l5);
			Scene scene = new Scene(root, 500, 500);// 画板
			stage.setScene(scene);
			stage.setTitle("Test");
			stage.show();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		launch(args);
	}
}

六、实验六

A Bank Account Class

a. 为方法toString补充代码,该方法返回包含姓名,账户号码以及账户余额信息的一段字符串。

b. 为方法chargeFee补充代码,从账户中扣去服务费。

c. 修改chargeFee方法,使其返回一个新的账户余额。

d. 为方法changeName补充代码,该方法有一个参数,为字符串类型,能够变更账户的姓名。

package task;

public class Account {
	private double balance;
	private String name;
	private long acctNum;
	
	public Account(double initBal,String owner,long number){
		balance=initBal;
		name=owner;
		acctNum=number;
	}
	
	public void withdraw(double amount){
		if(balance >= amount){
			balance -=amount;
		}else{
			System.out.println("Insufficent funds");
		}
	}
	public void deposit(double amount){
		balance += amount;
	}
	public double getBalance(){
		return balance;
	}
	
	public String toString(){
		return ""+name+","+acctNum+","+balance+"";
	}
	public void chargeFee(){
		balance-=10;
		return;
	}
	public void changeName(String newName){
		this.name=newName;
	}
	
}
package task;

public class ManageAccounts {
	public static void main(String[] args) {
		Account acct1,acct2;
		acct1=new Account(1000,"Sally",1111);
		
		acct2=new Account(500, "Joe", 2222);
		acct2.deposit(100);
		System.out.println(acct2.getBalance());
		acct1.withdraw(50);
		System.out.println(acct1.getBalance());
		acct1.chargeFee();
		acct2.chargeFee();
		acct2.changeName("Joseph");
		
		System.out.println(acct1);
		System.out.println(acct2);
	}
}

1. 编写一个类Name,用于保存某人的名字,中间名字和姓氏,并提供以下方法:

  1. public Name (String first, String middle, String last):构造方法。姓名以给定的格式保存,不要将其全部转换为大写或小写。
  2. public String getFirst():返回名字。
  3. public String getMiddle():返回中间名字。
  4. public String getLast():返回姓氏。
  5. public String firstMiddleLast():返回一个包含某人完整姓名的字符串,格式按照如下例子:Mary Jane Smith
  6. public String lastFirstMiddle():返回一个包含完整姓名的字符串,格式按照如下例子:Smith, Mary Jane
  7. public boolean equals (Name otherName):如果当前姓名与otherName相同,返回值为true;否则返回false。
  8. public String initials():返回姓名的首字母缩写,即由3个字符组成的字符串。该缩写全部为大写字母。提示:使用String类的substring方法获取名字、中间名字和姓氏的第一个字母并将其变为大写的形式。
  9. public int length():返回姓名全称的长度,不要计算空格。

 

2. 编写一个程序TestNames.java,提示用户输入两个姓名(每个姓名都包括名字,中间名字和姓氏),为两个姓名各创建一个Name的对象,使用Name类的方法完成以下操作:

a. 为每一个姓名,打印:

- first-middle-last形式表示的姓名

- last-first-middle形式表示的姓名

- 姓名缩写

- 长度

b. 检查两个姓名是否相同。

package task;

public class Name {
	private String first;
	private String middle;
	private String last;
	
	public Name(String first,String middle,String last){
		this.first=first;
		this.middle=middle;
		this.last=last;
	}
	public String getFirst(){
		return first;
	}
	public String getMiddle(){
		return middle;
	}
	public String getLast(){
		return last;
	}
	//前中后
	public String firstMiddleLast(){
		return first+" "+middle+" "+last;
	}
	//后前中
	public String lastFirstMiddle(){
		return last+" "+first+" "+middle;
	}
	public boolean equals(Name otherName){
		String str=first+middle+last; //原字符串
		//other对象的值通过tostring方式来保存成一段字符串
		String new_str=otherName.toString();  
		if(new_str.equals(str)){
			return true;
		}else{
			return false;
		}
	}
	public String initials(){
		String xzm_sx; //首字母大写
		//获取每个段的首字母
		xzm_sx=first.substring(0,1)+middle.substring(0,1)+last.substring(0,1);
		xzm_sx.toUpperCase();
		return xzm_sx;
	}
	public int length(){
		String all_str;
		all_str=firstMiddleLast();
		//all_str=toString();    //也可以这么写
		//去除空格
		all_str=all_str.replaceAll(" ", "");
		return all_str.length();
	}
	@Override
	public String toString() {
		//编写出前中后格式的样式  为后续通过对象来比较做准备
		return "" + first + "" + middle + "" + last + "";
	}
	
}
package task;

public class TestNames {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Name n1,n2;
		n1=new Name("Mary", "Jane" , "Smith");
		n2=new Name("Mary", "Jane" , "Smith");
		System.out.println(n1.getFirst()); //第一字
		System.out.println(n1.getMiddle());//第二字
		System.out.println(n1.getLast());//第三字
		System.out.println(n1.firstMiddleLast());//前中后
		System.out.println(n1.lastFirstMiddle());//后前中
		System.out.println(n1.equals(n2));//判断相等
		System.out.println(n1.initials());//首字母并且大写
		System.out.println(n1.length());//长度
		
	}

}

七、实验七

我们假设每按下一次按钮,就为候选人Joe的投票数增加一票,例子中按钮和变量的名字都做了适当修改。

1. 编译并运行程序,观察程序的运行结果。

2. 修改程序,使程序包含两个候选人,分别是Joe和Sam。需要作如下修改:

- 为Sam添加一个变量用于保存票数,另外添加按钮和标签。

- 添加一个新的内类SamButtonListener,用于监听对Sam按钮的点击行为。

- 将按钮和标签装载到面板中

3. 编译并运行程序。

ReadOrBlue3.java

package application;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;


//内部类对Sam_Button进行了监听
public class ReadOrBlue3 extends Application {
	private Button JoeButton, SamButton;
	private static int Joe_count,Sam_count;
	private Text Joe_Text,Sam_Text;
	private Pane pane;
	
	public void start(Stage primaryStage) throws Exception {
		JoeButton = new Button("Joe");
		
		SamButton = new Button("Sam");
		SamButton.setOnAction(new SamButtonListener());
		
		Joe_Text=new Text("0");
		Sam_Text=new Text("0");
		
		//自定义空间位置
		JoeButton.relocate(200, 100);
		SamButton.relocate(300, 100);
		Joe_Text.relocate(210,130);
		Sam_Text.relocate(310,130);
		pane=new Pane(JoeButton,SamButton,Joe_Text,Sam_Text);
		Scene scene = new Scene(pane, 500, 200);
		
		//利用网格布局
//		GridPane grid = new GridPane();
//		grid.add(JoeButton, 0, 0);
//		grid.add(SamButton, 1, 0);
//		grid.add(Joe_Text, 0, 1);
//		grid.add(Sam_Text, 1, 1);
//		grid.setAlignment(Pos.CENTER);
//		grid.setHgap(20);
//		grid.setStyle("-fx-background-color: white");
//		Scene scene = new Scene(grid, 500, 200);
		
		
		
		primaryStage.setTitle("Joe or Sam?");
		primaryStage.setScene(scene);
		primaryStage.show();
	}
	
	public static void main(String[] args) {
		launch(args);
	}
	class SamButtonListener implements EventHandler<ActionEvent>{
		@Override
		public void handle(ActionEvent event) {
			// TODO Auto-generated method stub
			if(event.getSource() == SamButton){
				Sam_count++;
				Sam_Text.setText(String.valueOf(Sam_count));
			}
		}
	}
}

八、实验八

1.

你在Lake LazyDays度假村的工作是按照天气状况给客人提供活动建议。以下是一个活动列表:

temp >= 80: swimming;

60 <= temp < 80: tennis;

40 <= temp < 60: golf;

temp < 40: skiing.

1. 编写一段程序,提示用户输入一个气温值,然后打印出适合该气温的活动。提示:使用if-else语句,并确保你的条件设定不必过于复杂。

2. 修改程序,在temp>95或者temp < 20的情况下,打印“Visit our shops!"。提示:在条件表达式中使用布尔运算符。

Activities_at_Lake_LazyDays .java

package exam8;

import java.util.Scanner;

public class Activities_at_Lake_LazyDays {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		int temp=sc.nextInt();
		
		if(temp>95 || temp<20){
			System.out.println("Visit our shops!");
		}else if(temp>=80){
			System.out.println("swimming");
		}else if(temp>=60&&temp<80){
			System.out.println("tennis");
		}else if(temp>=40&&temp<60){
			System.out.println("golf");
		}else if(temp<40){
			System.out.println("skiing");
		}
	}

}

2.

n的阶乘(n!)表示整数从1到n的乘积。比如,4!=1*2*3*4=24。另外,0!=1。阶乘不适用于负数。

1. 编写一段程序,请用户输入一个非负整数,然后打印该整数的阶乘。请使用while循环语句编写程序。请考虑用户输入0的情况。

2. 修改程序,检查用户是否输入非负整数。如果输入的负数,则提示用户输入非负整数,并请用户重新输入,直到用户输入非负整数为止。

Factorials.java

package exam8;

import java.util.Scanner;

public class Factorials {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int n;
		int result = 1;
		String str;
		boolean flag=true;
		System.out.println("请输入一个非负整数:");
		while (flag) {
			n = sc.nextInt();
			if (n < 0) {
				System.out.println("请重新输入一个非负整数:");
			}else if(n==0){
				System.out.println("0!=1");
			} 
			else {
				System.out.print(""+n+"!=");
				for(int i=1;i<=n;i++){
					System.out.print(i);
					result*=i;
					if(i<n){
						System.out.print("*");
					}
				}
				System.out.println("="+result);
			}
		}
	}
}

九、实验九

1.

程序Rock.java是石头剪子布游戏的一个框架。将该程序保存至本地目录,按照提示补充程序语句。该程序允许用户输入一个项目,计算机随机产生一个项目,对两个项目对比,给出胜负结果。

用户可以输入R, P, S或者r, p, s来表示石头,布,剪刀三个项目。用户输入的项目保存在字符串变量中,以便于大小写的转换。使用一个switch语句将一个随机整数转换为游戏中计算机给出的项目。

Rock_Paper_Scissors.java

package exam9;

import java.util.Random;
import java.util.Scanner;

public class Rock_Paper_Scissors {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String personPlay;
		String computerPlay="";
		int computerInt;
		
		Scanner sc=new Scanner(System.in);
		Random generator = new Random();
		
		computerInt=generator.nextInt(3);
		System.out.println("Enter your play:R,P or S");
		personPlay=sc.next();
		personPlay=personPlay.toUpperCase();//转换成大写
		
		switch(computerInt){
			case 0:
				computerPlay="R";
				break;
			case 1:
				computerPlay="P";
				break;
			case 2:
				computerPlay="S";
				break;
			default:
				break;
		}
		//R 石头 	Rock
		//P	布	Paper
		//S 剪刀	scissors
		System.out.println("Computer play is "+computerPlay);
		if(personPlay.equals(computerPlay)){
			System.out.println("It's a tie!");
		}else if(personPlay.equals("R")){
			if(computerPlay.equals("S")){
				System.out.println("Rock crushes scissors. You win!!");
			}else{
				System.out.println("scissors crushes Rock. You lose!!");
			}
		}else if(personPlay.equals("P")){
			if(computerPlay.equals("R")){
				System.out.println("Paper crushes Rock. You win!!");
			}else{
				System.out.println("scissors crushes Paper. You lose!!");
			}
		}else if(personPlay.equals("S")){
			if(computerPlay.equals("P")){
				System.out.println("scissors crushes Paper. You win!!");
			}else{
				System.out.println("Rock crushes scissors. You lose!!");
			}
		}
	}

}

2.

编写一段程序,连续投掷硬币100次,查找并记录连续为HEAD的投掷次数的最大值。程序框架如Runs.java所示。具体步骤如下:

1. 创建一个coin对象;

2. 在循环语句中,使用flip方法投掷硬币,使用getFace方法查看结果是否为HEADS。记录当前连续投掷结果为HEADS的次数,并记录其中的最大值。

3. 在循环结束后打印最大值结果。

Coin.java

package exam9;

public class Coin {

	public final int HEADS = 0;
	public final int TAILS=1;
	
	private int face;
	
	public Coin(){
		flip();
	}
	
	public void flip(){
		face=(int)(Math.random()*2);
	}
	
	public boolean isHeads(){
		return (face==HEADS);
	}
	
	@Override
	public String toString() {
		String faceName;
		if(face == HEADS){
			faceName="Heads";
		}else{
			faceName="Tails";
		}
		return faceName;
	}

}

Runs.java

package exam9;

public class Runs {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		final int FLIPS=100;
		
		int currentRun=0;
		int maxRun=0;
		
		int temp=0;
		
		Coin c=new Coin();
		for(int i=0;i<FLIPS;i++){
			c.flip();
			System.out.println(c);
			if(c.isHeads()){
				temp++;
				if(maxRun<temp){
					maxRun=temp;
				}
			}else{
				temp=0;
			}
			currentRun=i+1;
			System.out.println("currentRun:"+currentRun);
		}
		System.out.println("连续出现Head最大次数为:"+maxRun);
	}

}

 


总结

以上是本人的解题方式,仅供参考~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值