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当中支持实体对象,外键会与实体对象关联起来.如 ...
随机推荐
- AntDesign vue学习笔记(一)初始化项目
最近学习AntDesign组件使用,官方Pro例子集成度太高,不容易学习,将从最基础组件一个一个搭建. 1.创建Vue Cli项目 2.引入ant design组件 $ cnpm i --save a ...
- SPFA + 链式前向星(详解)
求最短路是图论中最基础的算法,最短路算法挺多,本文介绍SPFA算法. 关于其他最短路算法,请看我另一篇博客最短路算法详解 链式前向星概念 简单的说,就是存储图的一个数据结构.它是按照边来存图,而邻接矩 ...
- 利用MySQL存储过程批量插入100W条测试数据
DROP PROCEDURE IF EXISTS insert_batch; CREATE PROCEDURE insert_batch() BEGIN ; loopname:LOOP '); ; T ...
- Django框架之DRF APIView Serializer
一.APIView 我们在使用DjangoRestfulFramework的时候会将每个视图类继承APIView,取代原生Django的View类 APIView的流程分析: rest_framewo ...
- LeetCode 5214. 最长定差子序列(Java)HashMap
题目: 5214. 最长定差子序列 给你一个整数数组 arr 和一个整数 difference,请你找出 arr 中所有相邻元素之间的差等于给定 difference 的等差子序列,并返回其中最长的等 ...
- xorm-删除和软删除实例
删除数据Delete方法,参数为struct的指针并且成为查询条件.注意:当删除时,如果user中包含有bool,float64或者float32类型,有可能会使删除失败 package main i ...
- centos7 挂载未分配的硬盘空间
=============================================== 2019/7/28_第1次修改 ccb_warlock == ...
- node连接Mysql报错ER_NOT_SUPPORTED_AUTH_MODE
报错信息 本人系统安装的是mysql-installer-community-8.0.18.0.msi这个版本,然后我本地使用node-mysql去连接数据库. test.js文件 var mysql ...
- 仿EXCEL插件,智表ZCELL产品V1.7 版本发布,增加自定义右键菜单功能
详细请移步 智表(ZCELL)官网www.zcell.net 更新说明 这次更新主要应用户要求,主要解决了自定义右键菜单事件的支持,并新增了公式中自定义函数传参.快捷键剪切等功能,欢迎大家体验使用. ...
- ora121 tips
1. 900929 - Linux: STORAGE_PARAMETERS_WRONG_SET and "mmap() failed" Solution Increase the ...