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当中支持实体对象,外键会与实体对象关联起来.如 ...
随机推荐
- vs 远程调试
程序在vs安装目录: D:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Remote Debugge ...
- redis连接池(JedisPool)资源归还及timeout详解
转载. https://blog.csdn.net/yaomingyang/article/details/79043019 一.连接池资源类详解都在注释上 package redis.v1.clie ...
- springboot异步线程
前言 最近项目中出现了一个问题,发现自己的定时器任务在线上没有执行,但是在线下测试时却能执行,最后谷歌到了这篇文章SpringBoot踩坑日记-定时任务不定时了?; 本篇文章主要以自己在项目中遇到的问 ...
- 用NDK生成cURL和OpenSSL库
最近在用Qt开发Android应用时需要获取https页面内容,但Qt内置的QNetworkAccessManager类只支持下面这些协议(调用其supportedSchemes成员函数获取): (& ...
- Stack实现
栈的三种操作算法很简单 STACK-EMPTY(S) 1 if S.top == 0 2 return TRUE 3 else return FALSE PUSH(S, x) 1 S.top = ...
- OracleVM桥接网卡无法获取本地连接网卡
问题现象 VM虚拟机采用桥接网卡时,界面名称为"未指定",无法获取本地连接对应网卡信息: 处理方式: 进入本地连接,选择本地连接右键进入属性设置窗口; 选择安装,单击服务选项后点击 ...
- 记一次redis主从同步失败
zabbix告警突然从某个时间点开始提示CPU使用高,网卡流量也一直居高不下. 首先查看redis日志,发现告警时间点redis主节点被重启了,发生了主备切换,并且在日志中发现这么一段 [3081] ...
- Python与MogoDB交互
睡了大半天,终于有时间整理下拖欠的MongoDB的封装啦. 首先我们先进行下数据库的连接: conn = MongoClient('localhost',27017) # 建立连接 result = ...
- [UOJ #393]【NOI2018】归程
题目大意:有一张$n$个点$m$条边的图,每个边有两个属性$a_i,b_i$.有$Q$个询问,每个询问给出$v,p$,表示所有边中$b_i\leqslant p$的边会被标记,在点$v$,可以通过不被 ...
- ELK学习笔记之使用curl命令操作elasticsearch
0x00 _cat系列 _cat系列提供了一系列查询elasticsearch集群状态的接口.你可以通过执行curl -XGET localhost:9200/_cat 1. 获取所有_cat系列的操 ...