initial setup
This commit is contained in:
commit
eb8eb02ba1
57
README.md
Normal file
57
README.md
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
# README #
|
||||||
|
|
||||||
|
See on esimese praktikumi failide hoidla, mida saab kasutada ainult algseks lugemiseks.
|
||||||
|
Töötamiseks looge endale isiklik repositoorium, näiteks privaatne 'fork' bitbucket serverisse, millest saate luua klooni oma arvutisse.
|
||||||
|
|
||||||
|
## Näidete kasutamine käsurealt ##
|
||||||
|
#### Kompileerimine: ####
|
||||||
|
|
||||||
|
```
|
||||||
|
#!bash
|
||||||
|
|
||||||
|
javac -cp src src/Answer.java
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Käivitamine: ####
|
||||||
|
|
||||||
|
```
|
||||||
|
#!bash
|
||||||
|
|
||||||
|
java -cp src Answer
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Testide kasutamine ###
|
||||||
|
#### Testi kompileerimine: ####
|
||||||
|
|
||||||
|
```
|
||||||
|
#!bash
|
||||||
|
|
||||||
|
javac -cp 'src:test:test/junit-4.12.jar:test/hamcrest-core-1.3.jar' test/AnswerTest.java
|
||||||
|
|
||||||
|
```
|
||||||
|
Sama Windows aknas (koolonite asemel peavad olema semikoolonid):
|
||||||
|
|
||||||
|
```
|
||||||
|
#!bash
|
||||||
|
|
||||||
|
javac -cp 'src;test;test/junit-4.12.jar;test/hamcrest-core-1.3.jar' test/AnswerTest.java
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Testi käivitamine: ####
|
||||||
|
|
||||||
|
```
|
||||||
|
#!bash
|
||||||
|
|
||||||
|
java -cp 'src:test:test/junit-4.12.jar:test/hamcrest-core-1.3.jar' org.junit.runner.JUnitCore AnswerTest
|
||||||
|
```
|
||||||
|
|
||||||
|
Sama Windows aknas (koolonite asemel semikoolonid):
|
||||||
|
|
||||||
|
```
|
||||||
|
#!bash
|
||||||
|
|
||||||
|
java -cp 'src;test;test/junit-4.12.jar;test/hamcrest-core-1.3.jar' org.junit.runner.JUnitCore AnswerTest
|
||||||
|
```
|
232
description.html
Normal file
232
description.html
Normal file
@ -0,0 +1,232 @@
|
|||||||
|
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta name="GENERATOR" content="Mozilla/4.76 [en] (Win98; U)
|
||||||
|
[Netscape]">
|
||||||
|
<title>API kordamine</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2 style="margin-left: 40px;">Java API<br>
|
||||||
|
</h2>
|
||||||
|
<div style="margin-left: 40px;">This lab is for practicing Java -
|
||||||
|
you have to find descriptions of the following classes and solve a
|
||||||
|
set of small problems.<br>
|
||||||
|
</div>
|
||||||
|
<p style="margin-left: 40px;"><tt>java.lang.String</tt> <br>
|
||||||
|
<tt>java.lang.StringBuffer/StringBuilder<br>
|
||||||
|
java.lang.Character</tt> <br>
|
||||||
|
<tt>java.lang.Integer (-> Double, ...)</tt> <br>
|
||||||
|
<tt>java.lang.Math</tt> <br>
|
||||||
|
<tt>java.lang.Comparable</tt> </p>
|
||||||
|
<p style="margin-left: 40px;"><tt>java.util.StringTokenizer</tt> <tt><br>
|
||||||
|
java.util.Calendar</tt><br>
|
||||||
|
<tt>java.util.Random</tt> <tt><br>
|
||||||
|
java.util.ArrayList</tt> <tt><br>
|
||||||
|
java.util.HashMap</tt><br>
|
||||||
|
<span style="font-family: monospace;">java.util.Set</span><br>
|
||||||
|
<tt>java.util.List<br>
|
||||||
|
java.util.Collection<br>
|
||||||
|
java.util.TreeSet<br>
|
||||||
|
</tt><tt>java.util.Arrays<br>
|
||||||
|
java.util.Iterator<br>
|
||||||
|
</tt></p>
|
||||||
|
<p style="margin-left: 40px;">...<br>
|
||||||
|
</p>
|
||||||
|
<h3 style="margin-left: 40px;">Problems</h3>
|
||||||
|
<div style="margin-left: 40px;">
|
||||||
|
<ul>
|
||||||
|
<li>Convert a given double number (<span style="font-family:
|
||||||
|
monospace;">double</span>) into String (<span
|
||||||
|
style="font-family: monospace;">String</span>).</li>
|
||||||
|
<li>Convert a string (<span style="font-family: monospace;">String</span>)
|
||||||
|
into an integer number (<span style="font-family: monospace;">int</span>).
|
||||||
|
|
||||||
|
Assume that the string actually represents an integer
|
||||||
|
(Discover what happens, if the string is illegal?).</li>
|
||||||
|
<li>Take the current moment of time from the computers inner
|
||||||
|
clock and form a string "hours:minutes:seconds" (use 24h
|
||||||
|
notation, e.g. "13:25:10").</li>
|
||||||
|
<li>Find a cosine of a given angle that is expressed in degrees.</li>
|
||||||
|
<li>Print a table of square roots for numbers from 0 up to 100
|
||||||
|
using step 5 (print two numbers per line: argument and its
|
||||||
|
square root).</li>
|
||||||
|
<li>Given a string replace in it all uppercase letters with
|
||||||
|
corresponding lowercase letters and all lowercase letters with
|
||||||
|
corresponding uppercase letters. Do not change other symbols (<span
|
||||||
|
style="font-family: monospace;">"ABcd12"</span> -> <span
|
||||||
|
style="font-family: monospace;">"abCD12"</span>). Use <span
|
||||||
|
style="font-family: monospace;">StringBuffer</span> or <span
|
||||||
|
style="font-family: monospace;">StringBuilder</span> class
|
||||||
|
for intermediate result. Create an independent method <code
|
||||||
|
id="yui_3_2_0_1_1314010804247640">String reverseCase (String
|
||||||
|
s) </code>for this task.</li>
|
||||||
|
<li>Given a string find its reverse (<span style="font-family:
|
||||||
|
monospace;">"1234ab"</span> -> <span style="font-family:
|
||||||
|
monospace;">"ba4321"</span>).</li>
|
||||||
|
<li>Given a text (<span style="font-family: monospace;">String</span>)
|
||||||
|
find the number of words in it. Words are separated by any
|
||||||
|
positive number of any kind of whitespaces (like space, tab,
|
||||||
|
...). Create an independent method <code>int countWords
|
||||||
|
(String t) </code>for this task.</li>
|
||||||
|
<li>Register the current time, pause the program for 3 seconds,
|
||||||
|
register the current time again and print the difference
|
||||||
|
between these two moments of time in milliseconds.</li>
|
||||||
|
<li>Create a list (<span style="font-family: monospace;">ArrayList</span>)
|
||||||
|
of 100 random integers (<span style="font-family: monospace;">Integer</span>)
|
||||||
|
in between 0 and 999. Print the result. What is the difference
|
||||||
|
between<span style="font-family: monospace;"> int </span>and
|
||||||
|
<span style="font-family: monospace;">Integer</span>?</li>
|
||||||
|
<li>Find the minimal element of this list. How to find the
|
||||||
|
minimal element of any <span style="font-family: monospace;">List</span>
|
||||||
|
of <span style="font-family: monospace;">Comparable</span>
|
||||||
|
elements (read about interfaces, also consider that <span
|
||||||
|
style="font-family: monospace;">ArrayList implements List </span>and
|
||||||
|
|
||||||
|
<span style="font-family: monospace;">Integer implements
|
||||||
|
Comparable</span>)?</li>
|
||||||
|
<li>Create a hashtable (<span style="font-family: monospace;">HashMap</span>)
|
||||||
|
containing 5 pairs of strings, where "subject code" serves as
|
||||||
|
a key and "subject name" serves as a value (e.g. <span
|
||||||
|
style="font-style: italic;">("I231", "Algorithms and Data
|
||||||
|
Structures")</span> , just choose any subjects you like).</li>
|
||||||
|
<li>Print all the keys of this hashtable (one key per line).</li>
|
||||||
|
<li>Remove one of the subjects from the hashtable.</li>
|
||||||
|
<li>Print all pairs from this hashtable (each pair on separate
|
||||||
|
line).</li>
|
||||||
|
<li>Reverse the order of elements of the list you have created
|
||||||
|
before. Write an independent method<code> </code>to reverse
|
||||||
|
any list. The method signature is</li>
|
||||||
|
</ul>
|
||||||
|
<div style="margin-left: 80px;"><span style="font-family:
|
||||||
|
monospace;">public static <T extends Object> void
|
||||||
|
reverseList (List<T> list)</span><br style="font-family:
|
||||||
|
monospace;">
|
||||||
|
<span style="font-family: monospace;">
|
||||||
|
|
||||||
|
throws UnsupportedOperationException </span><br>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="margin-left: 40px;"><br>
|
||||||
|
<div style="margin-left: 40px;">Output the result and check that
|
||||||
|
it is correct.<br>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="margin-left: 40px;">
|
||||||
|
<ul>
|
||||||
|
<li>Write an independent method to find the maximal element of
|
||||||
|
any Java collection (you can use your list for testing). The
|
||||||
|
method signature is</li>
|
||||||
|
</ul>
|
||||||
|
<div style="margin-left: 40px;">
|
||||||
|
<div style="margin-left: 40px;"><span style="font-family:
|
||||||
|
monospace;">static public <T extends Object &
|
||||||
|
Comparable<? super T>> T</span> <span
|
||||||
|
style="font-family: monospace;">maximum (Collection<?
|
||||||
|
extends T> a) </span><br>
|
||||||
|
<span style="font-family: monospace;">
|
||||||
|
|
||||||
|
throws NoSuchElementException</span><br>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<br>
|
||||||
|
You have to upload your full solution to <a
|
||||||
|
href="https://moodle.hitsa.ee/">Moodle</a> !<br>
|
||||||
|
<br>
|
||||||
|
Git repository address: <a
|
||||||
|
href="https://jpoial@bitbucket.org/i231/lab1.git">https://jpoial@bitbucket.org/i231/lab1.git</a><br>
|
||||||
|
</div>
|
||||||
|
<div style="margin-left: 40px;"> <br>
|
||||||
|
<hr style="width: 100%; height: 2px;"></div>
|
||||||
|
<h3 style="margin-left: 40px;">Oskused, mis tuleks praktikumide
|
||||||
|
käigus omandada:</h3>
|
||||||
|
<ul style="margin-left: 40px;">
|
||||||
|
<li>informatsiooni kiire leidmine API kirjeldusest </li>
|
||||||
|
<li>teisendused ühest tüübist teise, mähisklasside kasutamine</li>
|
||||||
|
<li> lihtsate arvutuste tegemine</li>
|
||||||
|
<li> sõnetöötlus, sõnepuhvri kasutamine</li>
|
||||||
|
<li> aega väljendavate andmetega manipuleerimine</li>
|
||||||
|
<li> juhuslike andmete genereerimine</li>
|
||||||
|
<li> listi ja paisktabeli kasutamine, iteraatorid</li>
|
||||||
|
</ul>
|
||||||
|
<h3 style="margin-left: 40px;"> Ülesanded:</h3>
|
||||||
|
<div style="margin-left: 40px;">Koostage peameetod (<tt>main</tt>),
|
||||||
|
mis sisaldaks lahendust järgmistele probleemidele: </div>
|
||||||
|
<ul style="margin-left: 40px;">
|
||||||
|
<li> Teisendada etteantud reaalarv (<span
|
||||||
|
style="font-family: monospace;">double</span>) sõneks (<tt>String</tt>).</li>
|
||||||
|
<li> Teisendada etteantud sõne täisarvuks (eeldusel, et see
|
||||||
|
sõne väljendab täisarvu).</li>
|
||||||
|
<li> Võtta arvuti kellalt jooksev näit ning moodustada sõne
|
||||||
|
kujul: <i>tunnid:minutid:sekundid </i>(tunnid 24h skaalal).</li>
|
||||||
|
<li> Leida kraadides etteantud nurga koosinus.</li>
|
||||||
|
<li> Väljastada ruutjuurte tabel arvude 0 kuni 100 jaoks
|
||||||
|
sammuga 5.</li>
|
||||||
|
<li> Vahetada etteantud sõnes suurtähed väiketähtedega ja
|
||||||
|
vastupidi jättes muud sümbolid muutmata (<span
|
||||||
|
style="font-family: monospace;">"ABcd12"</span> -> <span
|
||||||
|
style="font-family: monospace;">"abCD12"</span>). Kasutage
|
||||||
|
vahetulemuste salvestamiseks sõnepuhvrit (<tt>StringBuffer</tt>).</li>
|
||||||
|
<li> Muuta etteantud sõne sümbolite järjekord vastupidiseks
|
||||||
|
(<span style="font-family: monospace;">"1234ab"</span> -> <span
|
||||||
|
style="font-family: monospace;">"ba4321"</span>).</li>
|
||||||
|
<li> Leida sõnade arv etteantud sõnes (sõnade eraldajaks
|
||||||
|
olgu vähemalt üks tühik, tabulatsioonimärk vms).</li>
|
||||||
|
<li> Võtta arvuti kellalt jooksev aeg, teha etteantud
|
||||||
|
pikkusega paus (näiteks 3 sek.), võtta uuesti jooksev aeg ning
|
||||||
|
arvutada nende kahe ajahetke tegelik vahe millisekundites.<br>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul style="margin-left: 40px;">
|
||||||
|
<li> Genereerida juhuarvudest vahemikus 0 kuni 999 (<tt>Integer</tt>)
|
||||||
|
koosnev 100-elemendiline list (<tt>ArrayList</tt>) ning
|
||||||
|
väljastada see.</li>
|
||||||
|
<li> Leida selle listi vähim element. Proovige kirjutada
|
||||||
|
eraldi meetod, mis leiaks etteantud <tt>List</tt>-liidest
|
||||||
|
rahuldava objekti vähima elemendi eeldusel, et elemendid on
|
||||||
|
võrreldavad liidese <tt>Comparable</tt> mõttes (mida <tt>Integer</tt>
|
||||||
|
isendid ka on).</li>
|
||||||
|
<li> Moodustada paisktabel (<tt>HashMap</tt>) umbes 5
|
||||||
|
elemendiga, milles võtmeks on õppeaine kood (<tt>String</tt>) ja
|
||||||
|
elemendiks õppeaine nimetus (<tt>String</tt>). Andmed mõelge ise
|
||||||
|
välja.<br>
|
||||||
|
</li>
|
||||||
|
<li> Väljastada selle paisktabeli kõik võtmed.</li>
|
||||||
|
<li> Eemaldada üks ainetest sellest tabelist.</li>
|
||||||
|
<li> Väljastada kõik paarid "võti - väärtus" sellest tabelist.</li>
|
||||||
|
<li> Muuta esimeses ülesandes genereeritud listi (<span
|
||||||
|
style="font-family: monospace;">ArrayList</span>) elementide
|
||||||
|
järjekord vastupidiseks. Väljastada tulemus ja kontrollida selle
|
||||||
|
õigsust.</li>
|
||||||
|
<li> Koostada maksimumi leidmise meetod (eraldi meetodina), mis
|
||||||
|
kasutaks liideseid <tt>Collection</tt> ja <tt>Comparable</tt>
|
||||||
|
(s.t. meetodi parameetriks on <span style="font-family:
|
||||||
|
monospace;">Collection</span>-objekt, mis sisaldab <span
|
||||||
|
style="font-family: monospace;">Comparable</span>-liidest
|
||||||
|
rahuldavaid elemente, meetodi tagastusväärtuseks on maksimaalne
|
||||||
|
element <span style="font-family: monospace;">Comparable</span>-tüüpi
|
||||||
|
|
||||||
|
objektina). Selle meetodi poole pöördumisel võite kasutada
|
||||||
|
esimeses ülesandes loodud listi.<br>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul style="margin-left: 40px;">
|
||||||
|
</ul>
|
||||||
|
<div style="margin-left: 40px;">
|
||||||
|
<div style="margin-left: 40px;"><span style="font-weight: bold;"></span>Programm testida ja
|
||||||
|
|
||||||
|
esitada Moodle kaudu.<br>
|
||||||
|
<br>
|
||||||
|
Git repositoorium: <a
|
||||||
|
href="https://jpoial@bitbucket.org/i231/lab1.git">https://jpoial@bitbucket.org/i231/lab1.git<br>
|
||||||
|
</a><br>
|
||||||
|
</div>
|
||||||
|
<br>
|
||||||
|
<hr style="width: 100%; height: 2px;">Jaanus Pöial<br>
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
17
git_eclipse.txt
Normal file
17
git_eclipse.txt
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
|
||||||
|
Ava Eclipse ja veendu, et egit-moodul on olemas, vajadusel lisa see Eclipse Marketplace kaudu.
|
||||||
|
|
||||||
|
Lisa projekti vaatesse git repositooriumite aken:
|
||||||
|
Window -> Show View -> Other... -> Git -> Git Repositories
|
||||||
|
|
||||||
|
Git Repositories aknas klooni vajalik repositoorium bitbucket-ist.
|
||||||
|
|
||||||
|
Loo Java projekt.
|
||||||
|
|
||||||
|
Kustuta src kataloog.
|
||||||
|
|
||||||
|
vali "Build Path -> Link Source" ja seo projekti source kloonimisest tekkinud
|
||||||
|
lokaalse repositooriumiga, pane Eclipse projektis selle kataloogi nimeks src.
|
||||||
|
|
||||||
|
Majanda versioonihaldusega ainult git repositooriumite aknas.
|
||||||
|
|
89
src/Answer.java
Normal file
89
src/Answer.java
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
public class Answer {
|
||||||
|
|
||||||
|
public static void main (String[] param) {
|
||||||
|
|
||||||
|
// TODO!!! Solutions to small problems
|
||||||
|
// that do not need an independent method!
|
||||||
|
|
||||||
|
// conversion double -> String
|
||||||
|
|
||||||
|
// conversion String -> int
|
||||||
|
|
||||||
|
// "hh:mm:ss"
|
||||||
|
|
||||||
|
// cos 45 deg
|
||||||
|
|
||||||
|
// table of square roots
|
||||||
|
|
||||||
|
String firstString = "ABcd12";
|
||||||
|
String result = reverseCase (firstString);
|
||||||
|
System.out.println ("\"" + firstString + "\" -> \"" + result + "\"");
|
||||||
|
|
||||||
|
// reverse string
|
||||||
|
|
||||||
|
String s = "How many words here";
|
||||||
|
int nw = countWords (s);
|
||||||
|
System.out.println (s + "\t" + String.valueOf (nw));
|
||||||
|
|
||||||
|
// pause. COMMENT IT OUT BEFORE JUNIT-TESTING!
|
||||||
|
|
||||||
|
final int LSIZE = 100;
|
||||||
|
ArrayList<Integer> randList = new ArrayList<Integer> (LSIZE);
|
||||||
|
Random generaator = new Random();
|
||||||
|
for (int i=0; i<LSIZE; i++) {
|
||||||
|
randList.add (new Integer (generaator.nextInt(1000)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// minimal element
|
||||||
|
|
||||||
|
// HashMap tasks:
|
||||||
|
// create
|
||||||
|
// print all keys
|
||||||
|
// remove a key
|
||||||
|
// print all pairs
|
||||||
|
|
||||||
|
System.out.println ("Before reverse: " + randList);
|
||||||
|
reverseList (randList);
|
||||||
|
System.out.println ("After reverse: " + randList);
|
||||||
|
|
||||||
|
System.out.println ("Maximum: " + maximum (randList));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Finding the maximal element.
|
||||||
|
* @param a Collection of Comparable elements
|
||||||
|
* @return maximal element.
|
||||||
|
* @throws NoSuchElementException if <code> a </code> is empty.
|
||||||
|
*/
|
||||||
|
static public <T extends Object & Comparable<? super T>>
|
||||||
|
T maximum (Collection<? extends T> a)
|
||||||
|
throws NoSuchElementException {
|
||||||
|
return null; // TODO!!! Your code here
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Counting the number of words. Any number of any kind of
|
||||||
|
* whitespace symbols between words is allowed.
|
||||||
|
* @param text text
|
||||||
|
* @return number of words in the text
|
||||||
|
*/
|
||||||
|
public static int countWords (String text) {
|
||||||
|
return 0; // TODO!!! Your code here
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Case-reverse. Upper -> lower AND lower -> upper.
|
||||||
|
* @param s string
|
||||||
|
* @return processed string
|
||||||
|
*/
|
||||||
|
public static String reverseCase (String s) {
|
||||||
|
return null; // TODO!!! Your code here
|
||||||
|
}
|
||||||
|
|
||||||
|
/** List reverse. Do not create a new list.
|
||||||
|
* @param list list to reverse
|
||||||
|
*/
|
||||||
|
public static <T extends Object> void reverseList (List<T> list)
|
||||||
|
throws UnsupportedOperationException {
|
||||||
|
// TODO!!! Your code here
|
||||||
|
}
|
||||||
|
}
|
552
src/TextIO.java
Normal file
552
src/TextIO.java
Normal file
@ -0,0 +1,552 @@
|
|||||||
|
|
||||||
|
/*
|
||||||
|
The file defines a class TextIO, which provides a simple interface
|
||||||
|
to Java's standard console input and output. This class defines
|
||||||
|
several static methods for reading and writing
|
||||||
|
values of various type.
|
||||||
|
|
||||||
|
This class will only work with standard, interactive applications.
|
||||||
|
When it is used in such an application, System.out and System.in
|
||||||
|
should not be used directly, since the TextIO class thinks it has
|
||||||
|
exclusive control of System.out and System.in. (Actually, using
|
||||||
|
System.out will probably not cause any problems, but don't use
|
||||||
|
System.in.)
|
||||||
|
|
||||||
|
To use this class in your program, simply include the compiled class
|
||||||
|
file TextIO.class in the same directory with the class file for your
|
||||||
|
main program. (If you are using a development environment such as
|
||||||
|
CodeWarrior or Visual J++, you can include the source file,
|
||||||
|
TextIO.java in your project.) You can then use all the public static methods
|
||||||
|
from the TextIO class in your program. (In your programs, the names
|
||||||
|
of the methods must be prefaced with "TextIO." For example, you should
|
||||||
|
use the name TextIO.getln() rather than simply getln().)
|
||||||
|
|
||||||
|
(This class is for use with my on-line introductory java textbook,
|
||||||
|
which is available at http://math.hws.edu/eck/cs124/notes/index.html.)
|
||||||
|
|
||||||
|
Written by: David Eck
|
||||||
|
Department of Mathematics and Computer Science
|
||||||
|
Hobart and William Smith Colleges
|
||||||
|
Geneva, NY 14456
|
||||||
|
Email: eck@hws.edu
|
||||||
|
WWW: http://math.hws.edu/eck/
|
||||||
|
|
||||||
|
July 16, 1998
|
||||||
|
|
||||||
|
Modified February, 2000; getChar() now skips blanks and CR's, and getAnyChar()
|
||||||
|
can be used to read the next char even if it's a blank or CR.
|
||||||
|
|
||||||
|
*/
|
||||||
|
import java.io.*;
|
||||||
|
|
||||||
|
public class TextIO {
|
||||||
|
|
||||||
|
// *************************** I/O Methods *********************************
|
||||||
|
|
||||||
|
// Methods for writing the primitive types, plus type String,
|
||||||
|
// to the console, with no extra spaces.
|
||||||
|
//
|
||||||
|
// Note that the real-number data types, float
|
||||||
|
// and double, a rounded version is output that will
|
||||||
|
// use at most 10 or 11 characters. If you want to
|
||||||
|
// output a real number with full accuracy, use
|
||||||
|
// "TextIO.put(String.valueOf(x))", for example.
|
||||||
|
|
||||||
|
public static void put(int x) { put(x,0); } // Note: also handles byte and short!
|
||||||
|
public static void put(long x) { put(x,0); }
|
||||||
|
public static void put(double x) { put(x,0); } // Also handles float.
|
||||||
|
public static void put(char x) { put(x,0); }
|
||||||
|
public static void put(boolean x) { put(x,0); }
|
||||||
|
public static void put(String x) { put(x,0); }
|
||||||
|
|
||||||
|
|
||||||
|
// Methods for writing the primitive types, plus type String,
|
||||||
|
// to the console,followed by a carriage return, with
|
||||||
|
// no extra spaces.
|
||||||
|
|
||||||
|
public static void putln(int x) { put(x,0); newLine(); } // Note: also handles byte and short!
|
||||||
|
public static void putln(long x) { put(x,0); newLine(); }
|
||||||
|
public static void putln(double x) { put(x,0); newLine(); } // Also handles float.
|
||||||
|
public static void putln(char x) { put(x,0); newLine(); }
|
||||||
|
public static void putln(boolean x) { put(x,0); newLine(); }
|
||||||
|
public static void putln(String x) { put(x,0); newLine(); }
|
||||||
|
|
||||||
|
|
||||||
|
// Methods for writing the primitive types, plus type String,
|
||||||
|
// to the console, with a minimum field width of w,
|
||||||
|
// and followed by a carriage return.
|
||||||
|
// If output value is less than w characters, it is padded
|
||||||
|
// with extra spaces in front of the value.
|
||||||
|
|
||||||
|
public static void putln(int x, int w) { put(x,w); newLine(); } // Note: also handles byte and short!
|
||||||
|
public static void putln(long x, int w) { put(x,w); newLine(); }
|
||||||
|
public static void putln(double x, int w) { put(x,w); newLine(); } // Also handles float.
|
||||||
|
public static void putln(char x, int w) { put(x,w); newLine(); }
|
||||||
|
public static void putln(boolean x, int w) { put(x,w); newLine(); }
|
||||||
|
public static void putln(String x, int w) { put(x,w); newLine(); }
|
||||||
|
|
||||||
|
|
||||||
|
// Method for outputting a carriage return
|
||||||
|
|
||||||
|
public static void putln() { newLine(); }
|
||||||
|
|
||||||
|
|
||||||
|
// Methods for writing the primitive types, plus type String,
|
||||||
|
// to the console, with minimum field width w.
|
||||||
|
|
||||||
|
public static void put(int x, int w) { dumpString(String.valueOf(x), w); } // Note: also handles byte and short!
|
||||||
|
public static void put(long x, int w) { dumpString(String.valueOf(x), w); }
|
||||||
|
public static void put(double x, int w) { dumpString(realToString(x), w); } // Also handles float.
|
||||||
|
public static void put(char x, int w) { dumpString(String.valueOf(x), w); }
|
||||||
|
public static void put(boolean x, int w) { dumpString(String.valueOf(x), w); }
|
||||||
|
public static void put(String x, int w) { dumpString(x, w); }
|
||||||
|
|
||||||
|
|
||||||
|
// Methods for reading in the primitive types, plus "words" and "lines".
|
||||||
|
// The "getln..." methods discard any extra input, up to and including
|
||||||
|
// the next carriage return.
|
||||||
|
// A "word" read by getlnWord() is any sequence of non-blank characters.
|
||||||
|
// A "line" read by getlnString() or getln() is everything up to next CR;
|
||||||
|
// the carriage return is not part of the returned value, but it is
|
||||||
|
// read and discarded.
|
||||||
|
// Note that all input methods except getAnyChar(), peek(), the ones for lines
|
||||||
|
// skip past any blanks and carriage returns to find a non-blank value.
|
||||||
|
// getln() can return an empty string; getChar() and getlnChar() can
|
||||||
|
// return a space or a linefeed ('\n') character.
|
||||||
|
// peek() allows you to look at the next character in input, without
|
||||||
|
// removing it from the input stream. (Note that using this
|
||||||
|
// routine might force the user to enter a line, in order to
|
||||||
|
// check what the next character is.)
|
||||||
|
// Acceptable boolean values are the "words": true, false, t, f, yes,
|
||||||
|
// no, y, n, 0, or 1; uppercase letters are OK.
|
||||||
|
// None of these can produce an error; if an error is found in input,
|
||||||
|
// the user is forced to re-enter.
|
||||||
|
// Available input routines are:
|
||||||
|
//
|
||||||
|
// getByte() getlnByte() getShort() getlnShort()
|
||||||
|
// getInt() getlnInt() getLong() getlnLong()
|
||||||
|
// getFloat() getlnFloat() getDouble() getlnDouble()
|
||||||
|
// getChar() getlnChar() peek() getAnyChar()
|
||||||
|
// getWord() getlnWord() getln() getString() getlnString()
|
||||||
|
//
|
||||||
|
// (getlnString is the same as getln and is only provided for consistency.)
|
||||||
|
|
||||||
|
public static byte getlnByte() { byte x=getByte(); emptyBuffer(); return x; }
|
||||||
|
public static short getlnShort() { short x=getShort(); emptyBuffer(); return x; }
|
||||||
|
public static int getlnInt() { int x=getInt(); emptyBuffer(); return x; }
|
||||||
|
public static long getlnLong() { long x=getLong(); emptyBuffer(); return x; }
|
||||||
|
public static float getlnFloat() { float x=getFloat(); emptyBuffer(); return x; }
|
||||||
|
public static double getlnDouble() { double x=getDouble(); emptyBuffer(); return x; }
|
||||||
|
public static char getlnChar() { char x=getChar(); emptyBuffer(); return x; }
|
||||||
|
public static boolean getlnBoolean() { boolean x=getBoolean(); emptyBuffer(); return x; }
|
||||||
|
public static String getlnWord() { String x=getWord(); emptyBuffer(); return x; }
|
||||||
|
public static String getlnString() { return getln(); } // same as getln()
|
||||||
|
public static String getln() {
|
||||||
|
StringBuffer s = new StringBuffer(100);
|
||||||
|
char ch = readChar();
|
||||||
|
while (ch != '\n') {
|
||||||
|
s.append(ch);
|
||||||
|
ch = readChar();
|
||||||
|
}
|
||||||
|
return s.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static byte getByte() { return (byte)readInteger(-128L,127L); }
|
||||||
|
public static short getShort() { return (short)readInteger(-32768L,32767L); }
|
||||||
|
public static int getInt() { return (int)readInteger((long)Integer.MIN_VALUE, (long)Integer.MAX_VALUE); }
|
||||||
|
public static long getLong() { return readInteger(Long.MIN_VALUE, Long.MAX_VALUE); }
|
||||||
|
|
||||||
|
public static char getAnyChar(){ return readChar(); }
|
||||||
|
public static char peek() { return lookChar(); }
|
||||||
|
|
||||||
|
public static char getChar() { // skip spaces & cr's, then return next char
|
||||||
|
char ch = lookChar();
|
||||||
|
while (ch == ' ' || ch == '\n') {
|
||||||
|
readChar();
|
||||||
|
if (ch == '\n')
|
||||||
|
dumpString("? ",0);
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
return readChar();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static float getFloat() {
|
||||||
|
float x = 0.0F;
|
||||||
|
while (true) {
|
||||||
|
String str = readRealString();
|
||||||
|
if (str.equals("")) {
|
||||||
|
errorMessage("Illegal floating point input.",
|
||||||
|
"Real number in the range " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Float f = null;
|
||||||
|
try { f = Float.valueOf(str); }
|
||||||
|
catch (NumberFormatException e) {
|
||||||
|
errorMessage("Illegal floating point input.",
|
||||||
|
"Real number in the range " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (f.isInfinite()) {
|
||||||
|
errorMessage("Floating point input outside of legal range.",
|
||||||
|
"Real number in the range " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
x = f.floatValue();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static double getDouble() {
|
||||||
|
double x = 0.0;
|
||||||
|
while (true) {
|
||||||
|
String str = readRealString();
|
||||||
|
if (str.equals("")) {
|
||||||
|
errorMessage("Illegal floating point input",
|
||||||
|
"Real number in the range " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Double f = null;
|
||||||
|
try { f = Double.valueOf(str); }
|
||||||
|
catch (NumberFormatException e) {
|
||||||
|
errorMessage("Illegal floating point input",
|
||||||
|
"Real number in the range " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (f.isInfinite()) {
|
||||||
|
errorMessage("Floating point input outside of legal range.",
|
||||||
|
"Real number in the range " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
x = f.doubleValue();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getWord() {
|
||||||
|
char ch = lookChar();
|
||||||
|
while (ch == ' ' || ch == '\n') {
|
||||||
|
readChar();
|
||||||
|
if (ch == '\n')
|
||||||
|
dumpString("? ",0);
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
StringBuffer str = new StringBuffer(50);
|
||||||
|
while (ch != ' ' && ch != '\n') {
|
||||||
|
str.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
return str.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean getBoolean() {
|
||||||
|
boolean ans = false;
|
||||||
|
while (true) {
|
||||||
|
String s = getWord();
|
||||||
|
if ( s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t") ||
|
||||||
|
s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("y") ||
|
||||||
|
s.equals("1") ) {
|
||||||
|
ans = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else if ( s.equalsIgnoreCase("false") || s.equalsIgnoreCase("f") ||
|
||||||
|
s.equalsIgnoreCase("no") || s.equalsIgnoreCase("n") ||
|
||||||
|
s.equals("0") ) {
|
||||||
|
ans = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
errorMessage("Illegal boolean input value.",
|
||||||
|
"one of: true, false, t, f, yes, no, y, n, 0, or 1");
|
||||||
|
}
|
||||||
|
return ans;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ***************** Everything beyond this point is private *******************
|
||||||
|
|
||||||
|
// ********************** Utility routines for input/output ********************
|
||||||
|
|
||||||
|
private static InputStream in = System.in; // rename standard input stream
|
||||||
|
private static PrintStream out = System.out; // rename standard output stream
|
||||||
|
|
||||||
|
private static String buffer = null; // one line read from input
|
||||||
|
private static int pos = 0; // position of next char in input line that has
|
||||||
|
// not yet been processed
|
||||||
|
|
||||||
|
|
||||||
|
private static String readRealString() { // read chars from input following syntax of real numbers
|
||||||
|
StringBuffer s=new StringBuffer(50);
|
||||||
|
char ch=lookChar();
|
||||||
|
while (ch == ' ' || ch == '\n') {
|
||||||
|
readChar();
|
||||||
|
if (ch == '\n')
|
||||||
|
dumpString("? ",0);
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
if (ch == '-' || ch == '+') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
while (ch == ' ') {
|
||||||
|
readChar();
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (ch >= '0' && ch <= '9') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
if (ch == '.') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
while (ch >= '0' && ch <= '9') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ch == 'E' || ch == 'e') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
if (ch == '-' || ch == '+') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
while (ch >= '0' && ch <= '9') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long readInteger(long min, long max) { // read long integer, limited to specified range
|
||||||
|
long x=0;
|
||||||
|
while (true) {
|
||||||
|
StringBuffer s=new StringBuffer(34);
|
||||||
|
char ch=lookChar();
|
||||||
|
while (ch == ' ' || ch == '\n') {
|
||||||
|
readChar();
|
||||||
|
if (ch == '\n')
|
||||||
|
dumpString("? ",0);
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
if (ch == '-' || ch == '+') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
while (ch == ' ') {
|
||||||
|
readChar();
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (ch >= '0' && ch <= '9') {
|
||||||
|
s.append(readChar());
|
||||||
|
ch = lookChar();
|
||||||
|
}
|
||||||
|
if (s.equals("")){
|
||||||
|
errorMessage("Illegal integer input.",
|
||||||
|
"Integer in the range " + min + " to " + max);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
String str = s.toString();
|
||||||
|
try {
|
||||||
|
x = Long.parseLong(str);
|
||||||
|
}
|
||||||
|
catch (NumberFormatException e) {
|
||||||
|
errorMessage("Illegal integer input.",
|
||||||
|
"Integer in the range " + min + " to " + max);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (x < min || x > max) {
|
||||||
|
errorMessage("Integer input outside of legal range.",
|
||||||
|
"Integer in the range " + min + " to " + max);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String realToString(double x) {
|
||||||
|
// Goal is to get a reasonable representation of x in at most
|
||||||
|
// 10 characters, or 11 characters if x is negative.
|
||||||
|
if (Double.isNaN(x))
|
||||||
|
return "undefined";
|
||||||
|
if (Double.isInfinite(x))
|
||||||
|
if (x < 0)
|
||||||
|
return "-INF";
|
||||||
|
else
|
||||||
|
return "INF";
|
||||||
|
if (Math.abs(x) <= 5000000000.0 && Math.rint(x) == x)
|
||||||
|
return String.valueOf( (long)x );
|
||||||
|
String s = String.valueOf(x);
|
||||||
|
if (s.length() <= 10)
|
||||||
|
return s;
|
||||||
|
boolean neg = false;
|
||||||
|
if (x < 0) {
|
||||||
|
neg = true;
|
||||||
|
x = -x;
|
||||||
|
s = String.valueOf(x);
|
||||||
|
}
|
||||||
|
if (x >= 0.00005 && x <= 50000000 && (s.indexOf('E') == -1 && s.indexOf('e') == -1)) { // trim x to 10 chars max
|
||||||
|
s = round(s,10);
|
||||||
|
s = trimZeros(s);
|
||||||
|
}
|
||||||
|
else if (x > 1) { // construct exponential form with positive exponent
|
||||||
|
long power = (long)Math.floor(Math.log(x)/Math.log(10));
|
||||||
|
String exp = "E" + power;
|
||||||
|
int numlength = 10 - exp.length();
|
||||||
|
x = x / Math.pow(10,power);
|
||||||
|
s = String.valueOf(x);
|
||||||
|
s = round(s,numlength);
|
||||||
|
s = trimZeros(s);
|
||||||
|
s += exp;
|
||||||
|
}
|
||||||
|
else { // constuct exponential form
|
||||||
|
long power = (long)Math.ceil(-Math.log(x)/Math.log(10));
|
||||||
|
String exp = "E-" + power;
|
||||||
|
int numlength = 10 - exp.length();
|
||||||
|
x = x * Math.pow(10,power);
|
||||||
|
s = String.valueOf(x);
|
||||||
|
s = round(s,numlength);
|
||||||
|
s = trimZeros(s);
|
||||||
|
s += exp;
|
||||||
|
}
|
||||||
|
if (neg)
|
||||||
|
return "-" + s;
|
||||||
|
else
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String trimZeros(String num) { // used by realToString
|
||||||
|
if (num.indexOf('.') >= 0 && num.charAt(num.length() - 1) == '0') {
|
||||||
|
int i = num.length() - 1;
|
||||||
|
while (num.charAt(i) == '0')
|
||||||
|
i--;
|
||||||
|
if (num.charAt(i) == '.')
|
||||||
|
num = num.substring(0,i);
|
||||||
|
else
|
||||||
|
num = num.substring(0,i+1);
|
||||||
|
}
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String round(String num, int length) { // used by realToString
|
||||||
|
if (num.indexOf('.') < 0)
|
||||||
|
return num;
|
||||||
|
if (num.length() <= length)
|
||||||
|
return num;
|
||||||
|
if (num.charAt(length) >= '5' && num.charAt(length) != '.') {
|
||||||
|
char[] temp = new char[length+1];
|
||||||
|
int ct = length;
|
||||||
|
boolean rounding = true;
|
||||||
|
for (int i = length-1; i >= 0; i--) {
|
||||||
|
temp[ct] = num.charAt(i);
|
||||||
|
if (rounding && temp[ct] != '.') {
|
||||||
|
if (temp[ct] < '9') {
|
||||||
|
temp[ct]++;
|
||||||
|
rounding = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
temp[ct] = '0';
|
||||||
|
}
|
||||||
|
ct--;
|
||||||
|
}
|
||||||
|
if (rounding) {
|
||||||
|
temp[ct] = '1';
|
||||||
|
ct--;
|
||||||
|
}
|
||||||
|
// ct is -1 or 0
|
||||||
|
return new String(temp,ct+1,length-ct);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return num.substring(0,length);
|
||||||
|
|
||||||
|
}
|
||||||
|
private static void dumpString(String str, int w) { // output string to console
|
||||||
|
for (int i=str.length(); i<w; i++)
|
||||||
|
out.print(' ');
|
||||||
|
for (int i=0; i<str.length(); i++)
|
||||||
|
if ((int)str.charAt(i) >= 0x20 && (int)str.charAt(i) != 0x7F) // no control chars or delete
|
||||||
|
out.print(str.charAt(i));
|
||||||
|
else if (str.charAt(i) == '\n' || str.charAt(i) == '\r')
|
||||||
|
newLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void errorMessage(String message, String expecting) {
|
||||||
|
// inform user of error and force user to re-enter.
|
||||||
|
newLine();
|
||||||
|
dumpString(" *** Error in input: " + message + "\n", 0);
|
||||||
|
dumpString(" *** Expecting: " + expecting + "\n", 0);
|
||||||
|
dumpString(" *** Discarding Input: ", 0);
|
||||||
|
if (lookChar() == '\n')
|
||||||
|
dumpString("(end-of-line)\n\n",0);
|
||||||
|
else {
|
||||||
|
while (lookChar() != '\n')
|
||||||
|
out.print(readChar());
|
||||||
|
dumpString("\n\n",0);
|
||||||
|
}
|
||||||
|
dumpString("Please re-enter: ", 0);
|
||||||
|
readChar(); // discard the end-of-line character
|
||||||
|
}
|
||||||
|
|
||||||
|
private static char lookChar() { // return next character from input
|
||||||
|
if (buffer == null || pos > buffer.length())
|
||||||
|
fillBuffer();
|
||||||
|
if (pos == buffer.length())
|
||||||
|
return '\n';
|
||||||
|
return buffer.charAt(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static char readChar() { // return and discard next character from input
|
||||||
|
char ch = lookChar();
|
||||||
|
pos++;
|
||||||
|
return ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void newLine() { // output a CR to console
|
||||||
|
out.println();
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean possibleLinefeedPending = false;
|
||||||
|
|
||||||
|
private static void fillBuffer() { // Wait for user to type a line and press return,
|
||||||
|
// and put the typed line into the buffer.
|
||||||
|
StringBuffer b = new StringBuffer();
|
||||||
|
out.flush();
|
||||||
|
try {
|
||||||
|
int ch = in.read();
|
||||||
|
if (ch == '\n' && possibleLinefeedPending)
|
||||||
|
ch = in.read();
|
||||||
|
possibleLinefeedPending = false;
|
||||||
|
while (ch != -1 && ch != '\n' && ch != '\r') {
|
||||||
|
b.append((char)ch);
|
||||||
|
ch = in.read();
|
||||||
|
}
|
||||||
|
possibleLinefeedPending = (ch == '\r');
|
||||||
|
if (ch == -1) {
|
||||||
|
System.out.println("\n*** Found an end-of-file while trying to read from standard input!");
|
||||||
|
System.out.println("*** Maybe your Java system doesn't implement standard input?");
|
||||||
|
System.out.println("*** Program will be terminated.\n");
|
||||||
|
throw new RuntimeException("End-of-file on standard input.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
System.out.println("Unexpected system error on input.");
|
||||||
|
System.out.println("Terminating program.");
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
buffer = b.toString();
|
||||||
|
pos = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void emptyBuffer() { // discard the rest of the current line of input
|
||||||
|
buffer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
} // end of class TextIO
|
108
test/AnswerTest.java
Normal file
108
test/AnswerTest.java
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import org.junit.Test;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Tests.
|
||||||
|
* @author jaanus
|
||||||
|
*/
|
||||||
|
public class AnswerTest {
|
||||||
|
|
||||||
|
String s = null;
|
||||||
|
ArrayList<Integer> l = null;
|
||||||
|
ArrayList<String> sl = null;
|
||||||
|
ArrayList<Double> dl = null;
|
||||||
|
|
||||||
|
@Test (timeout=1000)
|
||||||
|
public void testReverseCase1() {
|
||||||
|
s = "AAAbbb";
|
||||||
|
assertEquals (Aout.toString(s), "aaaBBB", Answer.reverseCase(s));
|
||||||
|
s = "AaB,xX123";
|
||||||
|
assertEquals (Aout.toString(s), "aAb,Xx123", Answer.reverseCase(s));
|
||||||
|
s = "JÜriöÖülestõus1Ää";
|
||||||
|
assertEquals (Aout.toString(s), "jüRIÖöÜLESTÕUS1äÄ",
|
||||||
|
Answer.reverseCase(s));
|
||||||
|
} // test1
|
||||||
|
|
||||||
|
@Test (timeout=1000)
|
||||||
|
public void testCountWords2() {
|
||||||
|
s = "four words are here";
|
||||||
|
assertEquals (Aout.toString(s), 4, Answer.countWords(s));
|
||||||
|
s = "three" + "\t" + "words here";
|
||||||
|
assertEquals (Aout.toString(s), 3, Answer.countWords(s));
|
||||||
|
s = "\t\ttwo\t here\t ";
|
||||||
|
assertEquals (Aout.toString(s), 2, Answer.countWords(s));
|
||||||
|
} // test2
|
||||||
|
|
||||||
|
@Test (timeout=1000)
|
||||||
|
public void testMaximum3() {
|
||||||
|
l = new ArrayList<Integer> (Arrays.asList (new Integer[]{1}));
|
||||||
|
assertEquals (l.toString(), new Integer(1), Answer.maximum (l));
|
||||||
|
l = new ArrayList<Integer> (Arrays.asList (
|
||||||
|
new Integer[]{1, -1, 0, -1, 2}));
|
||||||
|
assertEquals (l.toString(), new Integer(2), Answer.maximum (l));
|
||||||
|
l = new ArrayList<Integer> (Arrays.asList (
|
||||||
|
new Integer[]{-1, -1, -10, -1, -2}));
|
||||||
|
assertEquals (l.toString(), new Integer(-1), Answer.maximum (l));
|
||||||
|
} // test3
|
||||||
|
|
||||||
|
@Test (expected=RuntimeException.class)
|
||||||
|
public void testMaximum4() {
|
||||||
|
l = new ArrayList<Integer>();
|
||||||
|
Answer.maximum (l);
|
||||||
|
} // test4
|
||||||
|
|
||||||
|
@Test (expected=RuntimeException.class)
|
||||||
|
public void testMaximum5() {
|
||||||
|
l = null;
|
||||||
|
Answer.maximum (l);
|
||||||
|
} // test5
|
||||||
|
|
||||||
|
@Test (timeout=1000)
|
||||||
|
public void testMaximum6() {
|
||||||
|
sl = new ArrayList<String> (Arrays.asList (new String[]{"A"}));
|
||||||
|
assertEquals (sl.toString(), "A", Answer.maximum (sl));
|
||||||
|
dl = new ArrayList<Double> (Arrays.asList (
|
||||||
|
new Double[]{1., -1., 0., -1., 2.}));
|
||||||
|
assertEquals (dl.toString(), new Double(2.), Answer.maximum (dl));
|
||||||
|
sl = new ArrayList<String> (Arrays.asList (
|
||||||
|
new String[]{"A", "C", "B"}));
|
||||||
|
assertEquals (sl.toString(), "C", Answer.maximum (sl));
|
||||||
|
} // test6
|
||||||
|
|
||||||
|
@Test (timeout=1000)
|
||||||
|
public void testReverseList7() {
|
||||||
|
dl = new ArrayList<Double> (Arrays.asList (
|
||||||
|
new Double[]{1., -1., 0., -1., 2.}));
|
||||||
|
ArrayList<Double> cdl = new ArrayList<Double>(dl); // copy
|
||||||
|
Answer.reverseList (dl); // dl = 2 -1 0 -1 1
|
||||||
|
assertEquals (cdl.toString(), new ArrayList<Double> (Arrays.asList (
|
||||||
|
new Double[]{2., -1., 0., -1., 1.})), dl);
|
||||||
|
sl = new ArrayList<String> (Arrays.asList (
|
||||||
|
new String[]{"A", "C", "B"}));
|
||||||
|
ArrayList<String> cl = new ArrayList<String>(sl); // copy
|
||||||
|
Answer.reverseList (sl); // sl = B C A
|
||||||
|
assertEquals (cl.toString(), new ArrayList<String> (Arrays.asList (
|
||||||
|
new String[]{"B", "C", "A"})), sl);
|
||||||
|
sl = new ArrayList<String> (Arrays.asList (
|
||||||
|
new String[]{"A", "B"}));
|
||||||
|
cl = new ArrayList<String>(sl); // copy
|
||||||
|
Answer.reverseList (sl); // sl = B A
|
||||||
|
assertEquals (cl.toString(), new ArrayList<String> (Arrays.asList (
|
||||||
|
new String[]{"B", "A"})), sl);
|
||||||
|
sl = new ArrayList<String> (Arrays.asList (
|
||||||
|
new String[]{"A"}));
|
||||||
|
cl = new ArrayList<String>(sl); // copy
|
||||||
|
Answer.reverseList (sl); // sl = A
|
||||||
|
assertEquals (cl.toString(), new ArrayList<String> (Arrays.asList (
|
||||||
|
new String[]{"A"})), sl);
|
||||||
|
} // test7
|
||||||
|
|
||||||
|
@Test (expected=RuntimeException.class)
|
||||||
|
public void testReverseList8() {
|
||||||
|
l = null;
|
||||||
|
Answer.reverseList (l);
|
||||||
|
} // test8
|
||||||
|
|
||||||
|
} // AnswerTest
|
||||||
|
|
261
test/Aout.java
Normal file
261
test/Aout.java
Normal file
@ -0,0 +1,261 @@
|
|||||||
|
|
||||||
|
/** Helper methods.
|
||||||
|
* Arrays converted to array expressions (toString(...))
|
||||||
|
* and prettyprinting (toPrettyString(...)).
|
||||||
|
* @author Jaanus
|
||||||
|
*/
|
||||||
|
public class Aout {
|
||||||
|
|
||||||
|
/** Just testing. */
|
||||||
|
public static void main (String[] args) {
|
||||||
|
System.out.println (toString (new String[]
|
||||||
|
{null, "", "0", "a\nb", " ", " ", "\t", "möäüÕga", "\"", "\\", "\'"}));
|
||||||
|
} // main
|
||||||
|
|
||||||
|
/** Conversion for int[][] . */
|
||||||
|
public static String toString (int[][] m) {
|
||||||
|
if (m == null) return "(int[][])null";
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
sb.append ("new int[][]{");
|
||||||
|
for (int i=0; i < m.length; i++) {
|
||||||
|
if (i > 0) sb.append (", ");
|
||||||
|
if (m[i] == null)
|
||||||
|
sb.append ("null");
|
||||||
|
else {
|
||||||
|
sb.append ("{");
|
||||||
|
for (int j=0; j < m[i].length; j++) {
|
||||||
|
if (j > 0) sb.append (", ");
|
||||||
|
sb.append (String.valueOf (m[i][j]));
|
||||||
|
} // for j
|
||||||
|
sb.append ("}");
|
||||||
|
}
|
||||||
|
} // for i
|
||||||
|
sb.append ("}");
|
||||||
|
return sb.toString();
|
||||||
|
} // toString int[][]
|
||||||
|
|
||||||
|
/** Conversion for double[][] . */
|
||||||
|
public static String toString (double[][] m) {
|
||||||
|
if (m == null) return "(double[][])null";
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
sb.append ("new double[][]{");
|
||||||
|
for (int i=0; i < m.length; i++) {
|
||||||
|
if (i > 0) sb.append (", ");
|
||||||
|
if (m[i] == null)
|
||||||
|
sb.append ("null");
|
||||||
|
else {
|
||||||
|
sb.append ("{");
|
||||||
|
for (int j=0; j < m[i].length; j++) {
|
||||||
|
if (j > 0) sb.append (", ");
|
||||||
|
sb.append (String.valueOf (m[i][j]));
|
||||||
|
} // for j
|
||||||
|
sb.append ("}");
|
||||||
|
}
|
||||||
|
} // for i
|
||||||
|
sb.append ("}");
|
||||||
|
return sb.toString();
|
||||||
|
} // toString double[][]
|
||||||
|
|
||||||
|
/** Conversion for int[] . */
|
||||||
|
public static String toString (int[] m) {
|
||||||
|
if (m == null) return "(int[])null";
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
sb.append ("new int[]{");
|
||||||
|
for (int i=0; i < m.length; i++) {
|
||||||
|
if (i > 0) sb.append (", ");
|
||||||
|
sb.append (String.valueOf (m[i]));
|
||||||
|
} // for i
|
||||||
|
sb.append ("}");
|
||||||
|
return sb.toString();
|
||||||
|
} // toString int[]
|
||||||
|
|
||||||
|
/** Conversion for double[] . */
|
||||||
|
public static String toString (double[] m) {
|
||||||
|
if (m == null) return "(double[])null";
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
sb.append ("new double[]{");
|
||||||
|
for (int i=0; i < m.length; i++) {
|
||||||
|
if (i > 0) sb.append (", ");
|
||||||
|
sb.append (String.valueOf (m[i]));
|
||||||
|
} // for i
|
||||||
|
sb.append ("}");
|
||||||
|
return sb.toString();
|
||||||
|
} // toString double[]
|
||||||
|
|
||||||
|
/** Conversion for int . */
|
||||||
|
public static String toString (int n) {
|
||||||
|
return String.valueOf (n);
|
||||||
|
} // toString int
|
||||||
|
|
||||||
|
/** Conversion for double . */
|
||||||
|
public static String toString (double d) {
|
||||||
|
return String.valueOf (d);
|
||||||
|
} // toString double
|
||||||
|
|
||||||
|
/** Conversion for String . */
|
||||||
|
public static String toString (String s) {
|
||||||
|
if (s == null)
|
||||||
|
return "null";
|
||||||
|
StringBuffer tmp = new StringBuffer();
|
||||||
|
for (int k=0; k < s.length(); k++) {
|
||||||
|
char c = s.charAt (k);
|
||||||
|
switch (c) {
|
||||||
|
case '\n': { tmp.append ("\\n"); break; }
|
||||||
|
case '\t': { tmp.append ("\\t"); break; }
|
||||||
|
case '\b': { tmp.append ("\\b"); break; }
|
||||||
|
case '\f': { tmp.append ("\\f"); break; }
|
||||||
|
case '\r': { tmp.append ("\\r"); break; }
|
||||||
|
case '\\': { tmp.append ("\\\\"); break; }
|
||||||
|
case '\'': { tmp.append ("\\\'"); break; }
|
||||||
|
case '\"': { tmp.append ("\\\""); break; }
|
||||||
|
// TODO!!! add more escapes if needed
|
||||||
|
default: tmp.append (c);
|
||||||
|
} // switch
|
||||||
|
} // for k
|
||||||
|
return "\"" + tmp.toString() + "\"";
|
||||||
|
} // toString String
|
||||||
|
|
||||||
|
/** Conversion for String[] . */
|
||||||
|
public static String toString (String[] m) {
|
||||||
|
if (m == null)
|
||||||
|
return "(String[])null";
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
sb.append ("new String[]{");
|
||||||
|
for (int i=0; i < m.length; i++) {
|
||||||
|
if (i > 0)
|
||||||
|
sb.append (", ");
|
||||||
|
sb.append (toString (m[i]));
|
||||||
|
} // for i
|
||||||
|
sb.append ("}");
|
||||||
|
return sb.toString();
|
||||||
|
} // toString String[]
|
||||||
|
|
||||||
|
/** Double number as string with the given length.
|
||||||
|
* @param d argument
|
||||||
|
* @param len length
|
||||||
|
* @return d as string
|
||||||
|
*/
|
||||||
|
public static String fString (double d, int len) {
|
||||||
|
if (len<1)
|
||||||
|
return "";
|
||||||
|
// pad on ruum punkti ja v6imaliku miinusm2rgi jaoks
|
||||||
|
int pad = 1 + ((d<0)?1:0);
|
||||||
|
// loga on t2isosa numbrikohtade arv
|
||||||
|
int loga = (int)Math.max (0., Math.log10 (Math.abs (d))) + 1;
|
||||||
|
// kk on punkti j2rel olevate kohtade arv
|
||||||
|
int kk = (int)Math.max (len-pad-loga, 0);
|
||||||
|
String fs = "%" + String.valueOf (len) + "." +
|
||||||
|
String.valueOf (kk) + "f";
|
||||||
|
String res = "";
|
||||||
|
try {
|
||||||
|
res = String.format ((java.util.Locale)null, fs, d);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
res = String.valueOf (d);
|
||||||
|
} // try
|
||||||
|
return res;
|
||||||
|
} // fString
|
||||||
|
|
||||||
|
/** Prettyprint for double[][] .
|
||||||
|
* @param m array to print
|
||||||
|
* @param fs format string for element
|
||||||
|
* @return m array as multiline string
|
||||||
|
*/
|
||||||
|
public static String toPrettyString (double[][] m, String fs) {
|
||||||
|
String nl = System.getProperty ("line.separator");
|
||||||
|
if (m == null)
|
||||||
|
return "nullpointer instead of this matrix" + nl;
|
||||||
|
// throw new NullPointerException ("(double[][])null"); // alternative
|
||||||
|
if (m.length == 0)
|
||||||
|
return "this matrix is empty" + nl;
|
||||||
|
StringBuffer sb = new StringBuffer(nl);
|
||||||
|
for (int i=0; i < m.length; i++) {
|
||||||
|
if (m[i] == null)
|
||||||
|
sb.append ("nullpointer instead of this row" + nl);
|
||||||
|
else {
|
||||||
|
if (m[i].length == 0)
|
||||||
|
sb.append ("this row is empty");
|
||||||
|
else {
|
||||||
|
for (int j=0; j < m[i].length; j++) {
|
||||||
|
String elem = "";
|
||||||
|
if (fs == null || fs.length() < 1) {
|
||||||
|
// TODO!!! keera siit, kui tahad pilti muuta
|
||||||
|
elem = fString (m[i][j], 6) + "\t";
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
elem = String.format ((java.util.Locale)null,
|
||||||
|
fs, m[i][j]) + " "; // remove space if needed
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
elem = fString (m[i][j], 6) + "\t";
|
||||||
|
} // try
|
||||||
|
}
|
||||||
|
sb.append (elem);
|
||||||
|
} // for j
|
||||||
|
} // nonempty row
|
||||||
|
sb.append (nl);
|
||||||
|
} // non-null row
|
||||||
|
} // for i
|
||||||
|
return sb.toString();
|
||||||
|
} // toPrettyString double[][]
|
||||||
|
|
||||||
|
/** Version of double[][] prettyprint without format string. */
|
||||||
|
public static String toPrettyString (double[][] m) {
|
||||||
|
return toPrettyString (m, null);
|
||||||
|
} // toPrettyString double[][]
|
||||||
|
|
||||||
|
/** Prettyprint for int[][] .
|
||||||
|
* @param m array to print
|
||||||
|
* @param fs format string for element
|
||||||
|
* @return m array as a multiline string
|
||||||
|
*/
|
||||||
|
public static String toPrettyString (int[][] m, String fs) {
|
||||||
|
String nl = System.getProperty ("line.separator");
|
||||||
|
if (m == null)
|
||||||
|
return "nullpointer instead of this matrix" + nl;
|
||||||
|
// throw new NullPointerException ("(double[][])null"); // alternative
|
||||||
|
if (m.length == 0)
|
||||||
|
return "this matrix is empty" + nl;
|
||||||
|
StringBuffer sb = new StringBuffer(nl);
|
||||||
|
for (int i=0; i < m.length; i++) {
|
||||||
|
if (m[i] == null)
|
||||||
|
sb.append ("nullpointer instead of this row" + nl);
|
||||||
|
else {
|
||||||
|
if (m[i].length == 0)
|
||||||
|
sb.append ("this row is empty");
|
||||||
|
else {
|
||||||
|
for (int j=0; j < m[i].length; j++) {
|
||||||
|
String elem = "";
|
||||||
|
if (fs == null || fs.length() < 1)
|
||||||
|
fs = "%5d"; // TODO!!! keera siit, kui vaja
|
||||||
|
try {
|
||||||
|
elem = String.format ((java.util.Locale)null,
|
||||||
|
fs, m[i][j]) + " "; // remove space if needed
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
elem = String.valueOf (m[i][j]) + "\t";
|
||||||
|
} // try
|
||||||
|
sb.append (elem);
|
||||||
|
} // for j
|
||||||
|
} // nonempty row
|
||||||
|
sb.append (nl);
|
||||||
|
} // non-null row
|
||||||
|
} // for i
|
||||||
|
return sb.toString();
|
||||||
|
} // toPrettyString int[][]
|
||||||
|
|
||||||
|
/** Version of int[][] prettyprint without format string. */
|
||||||
|
public static String toPrettyString (int[][] m) {
|
||||||
|
return toPrettyString (m, null);
|
||||||
|
} // toPrettyString int[][]
|
||||||
|
|
||||||
|
/** Prettyprint for String[] . */
|
||||||
|
public static String toPrettyString (String[] m) {
|
||||||
|
String nl = System.getProperty ("line.separator");
|
||||||
|
if (m == null) return "(String[])null";
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
for (int i=0; i < m.length; i++) {
|
||||||
|
sb.append (toString (m[i]) + nl);
|
||||||
|
} // for i
|
||||||
|
return sb.toString();
|
||||||
|
} // toPrettyString String[]
|
||||||
|
|
||||||
|
} // Aout
|
||||||
|
|
BIN
test/hamcrest-core-1.3.jar
Normal file
BIN
test/hamcrest-core-1.3.jar
Normal file
Binary file not shown.
BIN
test/junit-4.12.jar
Normal file
BIN
test/junit-4.12.jar
Normal file
Binary file not shown.
Loading…
Reference in New Issue
Block a user