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

原文地址:https://www.cnblogs.com/dollarjava/p/12080657.html

时间: 2024-08-01 06:50:17

IN8005 Exercise Session的相关文章

CF1195C Basketball Exercise (dp + 贪心)

题意翻译 给定一个 2×n 的矩阵,现从中选择若干数,且任意两个数不上下或左右相邻,求这些数的和最大是多少? 题目描述 Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 \cdot n2⋅n students have come to Demid's exercise session, and he lined up t

L451 How to Cool down After Exercise

We are taught from childhood that warming up is a must in preparation for any exercise. It allows us to gear our muscles up for the strain we are about to place on them and prevent injury. More importantly, it steadily increases the heart rate and ci

COOKIE+SESSION

cookie的缺点: 因为cookie保存在浏览器上,所以安全性低可控性比较差,只能存放字符串大多数的浏览器对cookie有4K的限制. 下面是cookie在浏览器和服务器中请求与响应的过程: 1.    COOKIE的工作原理 cookie过程描述 网站为了辨别用户身份.进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密) 用户第一次访问你的网站->在服务器端会将用户的信息设置为cookie(可以理解为制造饼干过程)->通过http协议发送给用户(浏览器),在用户端,coo

Nginx做负载均衡时session共享问题详解

用nginx做负载均衡时,同一个IP访问同一个页面会被分配到不同的服务器上,如果session不同步的话,就会出现很多问题,比如说最常见的登录状态. 再者Nginx连接Memcached集群时,Nignx的请求从memcached服务器中根据key获得了value则直接返回value,如果没有获得到value则去MySQL中查询再返回. location / { set $memcached_key "$request_uri"; #设置请求memcached服务器的key memca

会话技术Session&Cookie

一.会话技术简介 1.存储客户端的状态 由一个问题引出今天的内容,例如网站的购物系统,用户将购买的商品信息存储到哪     里?因为Http协议是无状态的,也就是说每个客户访问服务器端资源时,服务器并不知道该客户端是谁,所以需要会话技术识别客户端的状态.会话技术是帮助服务器   记住客户端状态(区分客户端) 举例购物过程: 2.会话技术 从打开一个浏览器访问某个站点,到关闭这个浏览器的整个过程,成为一次会话.会话技术就是记录这次会话中客户端的状态与数据的. 会话技术分为Cookie和Sessio

Hibernate session缓存

一级缓存(执行代码时查看console台上的sql语句)  清空缓存 @Test public void demo03(){ //清空缓存 Session session=factory.openSession(); session.beginTransaction(); //1.查询 User user = (User)session.get(User.class, 1); System.out.println(user); //session.evitc(user) //将执行对象从一级缓存

JavaWeb基础—会话管理之Session

一.什么是session session类似于客户端在服务器端的账户.使用Map存放 一个会话锁定一个用户(一般情况下是一个客户端,即一个浏览器独占一个session对象),即使使用浏览器访问其他程序资源,也可以共享这个session (如何确定是同一个用户?创建session时把sessionID以cookie的形式传给客户端,客户端访问时再把此sessionID传过去进行校验 JSESSIONID ) 二.session和cookie的区别 cookie 把用户的数据保存到浏览器端,sess

session和cookie的区别

原作者:施杨(施杨's Think out)出处:http://shiyangxt.cnblogs.com 二者的定义: 当你在浏览网站的时候,WEB 服务器会先送一小小资料放在你的计算机上,Cookie 会帮你在网站上所打的文字或是一些选择, 都纪录下来.当下次你再光临同一个网站,WEB 服务器会先看看有没有它上次留下的 Cookie 资料,有的话,就会依据 Cookie 里的内容来判断使用者,送出特定的网页内容给你. Cookie 的使用很普遍,许多有提供个人化服务的网站,都是利用 Cook

Redis主从复制实现session共享

一.Redis安装 1. 下载安装扩展源及源码包 yum install -y epel-release jemalloc-devel wget https://codeload.github.com/antirez/redis/tar.gz/2.8.21 tar -zxvf 2.8.21 make:make PREFIX=/usr/local/redis install mkdir -p /usr/local/redis/etc 解决办法: cd deps/ make hiredis lua