COMP248 Object-Oriented Programming I 《面向对象编程I》是康大计算机专业的一门核心专业课。和一些大学讲授C的普遍做法不同,康大CS专业学习的第一门编程语言是Java,而且之后的算法及操作系统等课程的作业也是用Java实现的。
本专栏旨在通过课程作业的实现过程,复习JavaSE的相关内容。
ANNOUNCEMENT
This documnet is my solution of COMP248 Assignment 1 in Fall 2019. I have submitted this file in the assignment system. Please do not copy the code directlty.
Thank you for your cooperation and comprehension.
General Guidelines When Writing Programs:
Include the following comments at the top of your source codes
// -------------------------------------------------------
// Assignment (include number)
// Written by: (include your name and student id)
// For COMP 248 Section (your section) – Fall 2019
// --------------------------------------------------------
• In a comment, give a general explanation of what your program does. As the programming questions get more complex, the explanations will get lengthier.
• Include comments in your program describing the main steps in your program. Focus in your comments rather on the why than the how.
• Display a welcome message.
• Display clear prompts for users when you are expecting the user to enter data from the keyboard.
• All output should be displayed with clear messages and in an easy to read format.
• End your program with a closing message so that the user knows that the program has terminated.
业务需求
通过此作业练习Java的标识符(包名,类名,方法名等),赋值,输入/输入和if/else语句。
问题一 信息的展示
编写一个Java程序输出和示例完全一致的内容。注意,程序中只能使用一个System.out.println()语句。
问题分析
在Java中,如果我们想在控制台中输出信息,可以使用System.out.println()语句。println()方法具有自动换行的效果。此问题的难点在于用一个println()语句。
为了解决这个问题,我们可以使用"转义字符",在一个字符串内部实现换行等格式化的操作。
常用的转义字符
/n 换行 /t 插入4个空格
代码
/**
* This program is uesd to display a message.
* date:2019/9/14 Sat
*/
public class FirstQuestionOfA1 {
public static void main(String[] args) {
/*
* We can use the method "System.out.println()" to display a message on the screen.
* As we can use it only once in the assignment, we can use control character to format.
* e.g. \n is used to begin a new line; \t is usesd to make more space before sth. is displayed.
*/
System.out.println(""
+ "Welcome to COMP 248 Java Programming!\n"
+ "Let's use programming to have some coffee when you work!\n"
+ "while (Working)\n"
+ "{\n"
+ "\t CoffeeMug.Drink();\n"
+ "\t workTask.Execute();\n"
+ "\t if (coffeeMug == \"Empty\")\n"
+ "\t {\n"
+ "\t \t if (coffePot == \"Empty\")\n"
+ "\t \t \t coffeePot.Make();\n"
+ "\t \t coffeeMug.Refill();\n"
+ "\t }\n"
+ "\t Enjoy your coffee!\n"
+ "}");
}
}
问题二 时间转换程序
编写一个Java程序:
1) 提示用户输入一个5位的数字来表示秒数;
2) 计算对应的小时,分钟及秒数,按照示例的格式进行输出;
3) 如果用户输入的数字合法(在00:00:00~24:00:00范围内),则输出对应的时间;
注意:如果对应的时间是0,则输出00
4) 如果用户输入的时间是非法的,则交换第一个和最后一个数字,计算并输出对应的时分秒。
用两个常量存储一个小时的分钟数和一个小时中的秒数。无需对用户的输入进行校验。