栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java语言程序设计 例题3.2(游戏:将三个数相加)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java语言程序设计 例题3.2(游戏:将三个数相加)

*3.2(Game: add three numbers) The program in Listing 3.1, AdditionQuiz.java, generates two integers and prompts the user to enter the summation of these two integers. Revise the program to generate three single-digit integers and prompt the user to enter the summation of these three integers.

alter  from 3.1:


boolean  lightsOn = true;
true and fal se are literals, just like a number such as 10.They are treated as reserved words and cannot be used as identifiers in the program.
  Suppose you want to develop a program to let a firstgrader practice addition.The program randomly generates two single digit integers,number l and number2, and displays to the student a question such as “What is 1 + 7?,"as shown in the sample run in Listing 3.1.After the student types the answer, the program displays a message to indicate whether it is true or false. There are several ways to generate random numbers. For now,generate the first integer using System.currentTimeMillis() % 10 and the second using System.current-TimeMillis()/7 % 10. Listing 3.1 gives the program. Lines 5-6 generate two numbers,number1 and number2. Line 14 obtains an answer from the user.The answer is graded in line 18 using a Boolean expression number1+ number2==answer
3.2(游戏:将三个数相加)程序清单3-1中的程序产生两个整数,并提示用户输入这两个整数的和。修改该程序使之能产生三个个位数整数,然后提示用户输入这三个整数的和。

修改自3.1:

3
取值:true或false。例如,下面的语句将true赋值给变量lightsOn:
boolean lightsOn =true;

True和false是字面量,就像10这样的数字一样。它们被视为保留字Boolea,不能在程序中用作标识符。
假设您想开发一个程序来让一年级学生练习加法。程序随机生成两个个位数,number1和number2,并向学生显示一个问题,如“1+7是多少?”,如清单3.1中的示例运行所示。后的学生 见输入答案,程序将显示一条消息来指示答案是真还是假。有几种方法可以生成随机数。现在,使用System.currentTimeMillisC)%10生成第一个整数,使用System.currentTimeMillis()/7%10生成第二个整数。清单3.1给出了该程序。第5-6行生成两个数字,numberl和number2。第14行获取用户的应答。答案在第18行使用布尔表达式numberl+ number2==answer进行分级。

代码如下:

import java.util.Scanner;
public class Unite3Test2 {
	public static void main(String[] args)
	{
		int number1=(int)(System.currentTimeMillis()%10);
		int number2=(int)(System.currentTimeMillis()/10%10);
		int number3=(int)(System.currentTimeMillis()%1000/10);
		//Create a Scanner
		Scanner input=new Scanner(System.in);
		System.out.print("what is"+number1+"+"+number2+"+"+number3+"=?");
		int answer=input.nextInt();
		System.out.println(
	
				number1+"+"+number2+"+"+number3+"="+answer+"is"+(number1+number2+number3==answer));
		
	}

}

 运行结果如下:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876558.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号