IN8005 Exercise Session
Exercise Session for Introduction
into Computer Science
(for non Informatics studies, TUM BWL)
(IN8005), WS 2019/2020
Sheet 8
• Homework are to be worked out independently.
• Submission is done via moodle.
https://www.moodle.tum.de/course/view.php?id=49786
• Deadline for submission is 24:00 o clock on 22.12.2018.
• If you have any questions regarding your solution after comparison with the sample solutions,
you may post them in a comprehensive way in the moodle forum.
• Each assignment is marked to give an estimation of its difficulty and/or necessary effort.
– * Simple and little effort,
– ** Difficult or at least requires some work,
– *** Very Difficult or extensive.
Overview Java
Object-oriented programming basic concepts
• Objects, classes
• Inheritance
• Interfaces
Language basics
• Variables
• Arrays
• Operators
• Expressions, statements, blocks
• Control flow
Object-oriented programming advanced concepts
• Overloading
• Overriding
• Hiding
• Polymorphism
Data structures and algorithms
1
• Complexity
• Dynamic arrays
• Lists
• Hashing
• Sorting
Prerequisites to work with Java
• Java SE Development Kit (JDK)
– Download at
http://www.oracle.com/technetwork/java/javase/downloads/index.html
– Installation (see moodle for installation instructions)
– Test installation
∗ Open terminal and type java -version
∗ If you receive information about the java installation, everything is fine
• Integrated Development Environment (IDE) — eclipse
– Any text editor is fine to write Java code, but life gets much easier with an appropriate
tool.
∗ Syntax highlighting
∗ Auto complete
∗ Error recognition
∗ A debugger that lets you interrupt the execution of your code in order to find errors.
– Download at
https://www.eclipse.org/downloads/
Literature
The structure and contents of our course is guided by the official Java tutorial by oracle.
https://docs.oracle.com/javase/tutorial/java/TOC.html
OOP Concepts
• Objects are items of the real world. Objects have state and behavior.
Example:
– Maya the bee
∗ State: called Maya, full of energy, ...
∗ Behavior: flies around slowly
– Willy the bee
∗ State: called Willy, lazy with little energy, ...
∗ Behavior: eats
• Classes are templates/blueprints for objects. They describe the state and behavior that objects
of its type support.
– State is stored in so-called fields (database counterpart: attributes).
2
– Behavior is made accessible by so-called methods.
∗ Methods may use and change the state of the object.
∗ Methods serve to communicate between objects.
∗ There first methods look like this
void saySomething () {
System . out . prinln (" Hello ") // prints hello into the terminal
}
– Example: Flying insect
∗ Fields (state): name, energy
∗ Methods (behavior): fly slow, eat, print information
public class FlyingInsect {
String name ;
double energy = 0.0;
void setName ( String n ) {
name = n ;
}
void flySlow () {
// the following prints the given String into the terminal
System . out . println (" Bsssssssssss .");
energy = energy - 0.1;
}
void eat () {
System . out . println (" Mampf .");
energy = energy + 1.0;
}
void printInfo () {
// concatenate Strings and print into terminal
System . out . println ( name + " has " + energy + " energy ");
}
}
– A Java program is executed sequentially and always starts with a main-method, that always
looks like this
public static void main ( String [] args ) {
// Java program
} // end of Java program
In general the main-method can be located in any class.
– The FlyingInsect class does not contain a main method. It is not a complete program. It
is merely a blueprint for objects of a flying insect type that can be used in a Java program
and that program is executed starting at a main-method.
– Create Objects Maya and Willy
public static void main ( String [] args ) {
// the new operator creates a new object of a class
FlyingInsect m = new FlyingInsect ();
3
// methods and fields of an object are accessed
// with the variable name followed by a dot
m . setName (" Maya ");
m . eat ();
m . flySlow ();
m . printInfo ();
FlyingInsect w = new FlyingInsect ();
w . setName (" Willy ");
w . eat ();
w . eat ();
m . printInfo ();
}
• Inheritance: one class, called subclass (derived class, child class), acquires the properties (methods
and fields) of another, called superclass (base class, parent class).
Example:
– Superclass: FlyingInsect
– Subclass: LittleBee
∗ Fields: quantity of collected pollen
∗ Methods: collect pollen
public class LittleBee extends FlyingInsect {
int collectedPollen = 0;
void collectPollen () {
collectedPollen = collectedPollen + 1;
System . out . println ("Ei , da hab ich so schoen Pollen gesammelt !");
}
}
– Subclass: AngryHornet
∗ Fields: aggressive
∗ Methods: Fly fast
public class AngryHornet extends FlyingInsect {
public void flyFast () {
System . out . println (" MEGABRUMM !");
}
}
• An Interface is a collection of methods without method bodies (abstract methods). A class
that implements the interface must implement the methods as defined in the interface. Thus,
interfaces constitute a contract between the class and the rest of the world.
Example:
– Interface: CanSting
– is implemented by classes Bee and Hornet
public interface CanSting {
public void sting ();
}
4
public class LittleBee extends FlyingInsect implements CanSting {
int collectedPollen = 0;
public void collectPollen () {
collectedPollen = collectedPollen + 1;
System . out . println ("Ei , da hab ich so schoen Pollen gesammelt !");
}
public void sting () {
System . out . println (" Pieks .");
}
}
public class AngryHornet extends FlyingInsect implements CanSting {
boolean aggressive ;
public void flyFast () {
System . out . println (" MEGABRUMM !");
}
public void sting () {
System . out . println (" MEGAPIEKS !");
}
}
• Packages organize classes and interfaces hierarchically into groups, just like folders in a file
system.
Tutorial 8: Java — Bingo ***
Develop an easy software to play Bingo. This version of Bingo works in the following way. Before the
session starts, every player is given a ticket with some numbers from 1 to 10. Once the Bingo session
IN8005留学生作业代做、代写Computer Science作业、Java编程语言作业调试、Java作业代做
begins, random numbers are drawn. Every player who has such a number on their ticket has to mark
it. The first player to mark all the numbers on their ticket wins. It is possible to have more than one
winner at a time, in case the drawn number is the last to mark for more than one player.
1. Create a project
(a) start eclipse, File -> New -> Java Project. Name it Bingo.
2. Create package for all future files in the src folder and name it tutorial.
3. Create the class BingoNumber, which represents a single number on the Bingo ticket
(a) Attributes (always set the attributes to private!)
i. int value, corresponds to the number on the ticket.
ii. boolean marked, true if the number is marked, false otherwise.
(b) Constructor BingoNumber(int value), initializes the attributes (marked is initialized to
false).
(c) Methods
i. void mark(), called to mark the number, sets marked to true.
ii. boolean getMarked(), returns marked.
iii. int getValue(), returns value.
5
4. Create the class Ticket, which represents a ticket of a player
(a) Attributes
i. BingoNumbers[] numbers, vector of type BingoNumber, contains the numbers on the
ticket.
ii. String player, contains the name of the player.
(b) Constructor Ticket(String player, int[] assignedNumbers)
Initialize player, initialize numbers and populate it with new objects of type BingoNumber,
using the values in assignedNumber.
(c) Methods
i. boolean checkAndMark(int drawnNumber), checks if the attribute numbers contains
a BingoNumber of value drawnNumber. If found, the BingoNumber is marked and the
method returns true, else it returns false.
ii. boolean isWinner(), returns true if all the numbers are marked, false otherwise.
iii. String getPlayer(), returns player.
5. Create the class BingoSession, which represents a single session of Bingo
(a) Attributes
i. Ticket[] tickets, vector of tickets taking part in the session.
ii. int ticketsIndex, value of smallest free element index in tickets.
(b) Constructor BingoSession(), initializes tickets with a vector of type Ticket and lenght
10, and sets ticketsIndex to 0 (the vector is empty, therefore the first free element is at
position 0).
(c) Methods
i. void addTicket(Ticket t), adds t to tickets (and increment ticketsIndex!)
ii. void runSession(), launches the session. Create a loop that terminates when one of
the tickets is a winner. Inside the loop generate a casual number (see below), print it
out and check whether is appears in any of the tickets. At the end of the session the
winner(s) must be printed out.
To generate a casual integer number between 1 and 10 do the following:
int n = (int) Math . ceil ( Math . random () * 10);
6. Create the class BingoMain and do the following in the public static void main(String[]
args) method
(a) Create new tickets.
(b) Create a new BingoSession.
(c) Add the tickets to the session.
(d) Call runSession() on the session.
7. Run the program.
Homework 8: Java — Easy Trumps ***
Develop a software to play Easy Trumps, a famous one vs. one card game. At the beginning of the
game, every player is given 10 cards. Easy Tumps cards have two values: attack and defense. Every
turn of a match of Easy Trump works as following. One player is the attacker and the other one is
the defender. Both players draw one card from the top of their deck. If the attack value of attacker’s
card is higher that the defense value of the defender’s card, the turn is won by the attacker, otherwise
it is won by the defender (ties are won by the defender). Who wins the turn puts both played cards
6
on the bottom of their deck. In the following turn attacker and defender switch roles. The game goes
on until one of the two players is left with no cards.
Parts of the software have already been implemented. Download the Java project from Moodle and
import it in Eclipse (see below). All the classes have already been created, but some methods are
completely missing and need to be added, and some others are defined but need to be implemented
(they contain a TO-DO label). The code contains a lot of comments and this makes the classes look
huge, but don’t worry, the actual code is not much.
1. Download the “Exercise8.zip” file from Moodle and import it in Eclipse
(a) start Eclipse -> File -> Import -> General -> Existing Projects into Workspace
(b) Select “Select archive file:” and click on “Browse...”
(c) Select “Exercise8.zip” from the folder you saved it in when you downloaded it
(d) Click on “Finish”
(e) Open the imported project and then open the “src” folder
(f) You are now ready to start!
2. Open class TrumpCard and add the following methods
(a) int getAttack(), returns attack.
(b) int getDefense(), return defense.
3. Open class Player, read the comments to understand what the class is meant for and add
implementation to the following methods
(a) TrumpCard playCard(), removes the card on top of the deck and returns it. Remeber to
update cardsIndex! (Do not worry about the case where there is no card)
(b) void addCard(TrumpCard c), adds a card to the bottom of the deck. You will have to
move all the elements one position higher (one by one) before you can add the new card
at position 0 (Suggestion: start moving the elements from the top of the deck and don’t
forget to update cardsIndex)
(c) int cardsNumber(), returns the number of cards (Suggestion: cardsIndex can be helpful
here)
4. Open class Match, read the comments to understand what the class is meant for and add implementation
to the following method
void playTurn(Player attacker, Player defenser), corresponds to a turn of Easy Trumps.
The following steps have to be taken.
(a) Draw a card from the attacker’s deck.
(b) Draw a card from the defender’s deck.
(c) Print out the values of attack and defense (please format the string in a nice human-readable
way).
(d) Add the cards to the winner’s deck.
5. Open class TrumpMain and add the following to the main method
(a) Create two new players of type Player named Tom and Jerry
(b) Create a new match of type Match with the two players.
(c) Call the launchMatch() method on the match variable.
6. Run the code.
If you did some mistakes you will probably get a java.lang.NullPointerException. This will most
likely mean that you messed up with the arrays indices. Don’t give up and check the logic you used
in the methods involving arrays!
7
因为专业,所以值得信赖。如有需要,请加QQ:99515681 或 微信:codehelp
IN8005 Exercise Session的更多相关文章
- CF1195C Basketball Exercise (dp + 贪心)
题解出处:https://www.luogu.org/problemnew/solution/CF1195C 很水的一道C题……目测难度在黄~绿左右.请各位切题者合理评分. 注意到可以选择的球员编号是 ...
- C. Basketball Exercise dp
C. Basketball Exercise time limit per test 2 seconds memory limit per test 256 megabytes input stand ...
- 自动生成数学题型一 (框架Struts2) 题型如(a+b=c)
1. 加减乘除 1.1 随机生成制定范围的整数 /** * 随机产生一个被限定范围的整数 * * @param num1 * 定义起始范围 num1 * @param num2 * 定义终止范围 nu ...
- Spark版本发布历史,及其各版本特性
2016年11月5日 We are proud to announce that Apache Spark won the 2016 CloudSort Benchmark (both Dayto ...
- psp0级报告
计划 1.1需求描述: 现在市场上有很多的面向小学生的题卡,但是这习题卡不但价格昂贵,而且每次做题的内容基本都是固定.针对这些问题,开发出了这款网页在线答题系统,每次的题目都有所不同,可以跟快更好提高 ...
- Codeforce Round #574(Div.2)
...
- session实现购物车
为实现简单的购物功能(购物车添加.账户查看.购物车商品删除.实时的购物商品数量及价格的计算显示.购物车商品数量可手动输入等),用session实现了一简单的以php语言为基础.连接MySQL数据库的购 ...
- Asp.net Core中使用Session
前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. 元旦放假在家写了个Asp.net Core验证码登录, 做demo的过程中遇到两个小问题,第一是在Asp.net Cor ...
- 懒加载session 无法打开 no session or session was closed 解决办法(完美解决)
首先说明一下,hibernate的延迟加载特性(lazy).所谓的延迟加载就是当真正需要查询数据时才执行数据加载操作.因为hibernate当中支持实体对象,外键会与实体对象关联起来.如 ...
随机推荐
- MD5用户密码加密工具类 MD5Util
一般记录用户密码,我们都是通过MD5加密配置的形式.这里记录一下,MD5加密的工具类. package com.mms.utils; import java.security.MessageDiges ...
- 【笔试题】Overloading in Java
笔试题 Overloading in Java Question 1 以下程序的输出结果为( ). public class Test { public int getData() { return ...
- 用NDK生成cURL和OpenSSL库
最近在用Qt开发Android应用时需要获取https页面内容,但Qt内置的QNetworkAccessManager类只支持下面这些协议(调用其supportedSchemes成员函数获取): (& ...
- 学Python要避免哪些坑,如何巩固好基础
学Python要避免哪些坑?零基础怎么入门Python?Python入门简单.语法简洁.功能强大,非常适合零基础入门IT行业的人学习.随着人工智能时代的来临,企业纷纷选择使用Python进行开发,Py ...
- 解决kali安装成功后没有声音的问题
Kali Linux系统默认状态下,root用户是无法使用声卡的,也就没有声音.启用的方法如下: (1)在终端执行命令:systemctl --user enable pulseaudio (2)在/ ...
- sublime_python编译_输出台中文为乱码
Evernote Export sublime_python编译_输出台中文为乱码 创建时间: 2019-10-17 星期四 10:52 作者: 苏苏 标签: sublime, 乱码 问题 ...
- AJAX调用数据,滚动到底部
最近一个小项目里面,需要使用AJAX去拉取数据,并且直接显示最后一条信息,也就是滚动到底部.实现脚本如下: var scrollHeight = $('.txtBox3').prop("sc ...
- 记一次node爬虫经历,手把手教你爬虫
今天业务突然来了个爬虫业务,爬出来的数据以Excel的形式导出,下班前一个小时开始做,加班一个小时就做好了.因为太久没做爬虫了!做这个需求都是很兴奋! 需求说明 访问网站 (循环)获取页面指定数据源 ...
- windows桌面远程连接突然不能双向复制文件
远程桌面连接windows 2008,突然无法在本地和服务器之间互相复制文件.根据微软的说明,由rdpclip.exe进程来控制,打开远程服务器的任务管理器,看到rdpclip.exe进程存在,即可进 ...
- pathlib的使用
目录 一. Python2与Python3的路径处理的对比 二. pathlib的几个使用示例 1. 最简单的使用 2. 追加路径到Python的sys.path中 3. 生成目录树的技巧 4. 递归 ...