summaryrefslogtreecommitdiff
path: root/java
diff options
context:
space:
mode:
Diffstat (limited to 'java')
-rw-r--r--java/.gitignore1
-rw-r--r--java/atividades/Atividade1.java27
-rw-r--r--java/atividades/Contas.java29
-rw-r--r--java/atividades/Decisao1.java40
-rw-r--r--java/atividades/ExLoop.java36
-rw-r--r--java/atividades/Exercise1.java18
-rw-r--r--java/atividades/Primeiro.java16
-rw-r--r--java/atividades/Programa03.java26
-rw-r--r--java/atividades/Segundo.java13
-rw-r--r--java/atividades/dados.java18
-rw-r--r--java/atividades/loop_while.java51
-rw-r--r--java/atividades/test_swing.java49
-rw-r--r--java/qfind/QuickFindUF.java39
-rw-r--r--java/qfind/QuickUnionUF.java47
-rw-r--r--java/qfind/WeightedQuickUnionUF.java62
-rw-r--r--java/qfind/qfind.java5
-rw-r--r--java/stacks/StackClient.java14
-rw-r--r--java/stacks/StackOfStrings.java39
-rw-r--r--java/stacks/StdIn.java670
19 files changed, 1200 insertions, 0 deletions
diff --git a/java/.gitignore b/java/.gitignore
new file mode 100644
index 0000000..6b468b6
--- /dev/null
+++ b/java/.gitignore
@@ -0,0 +1 @@
+*.class
diff --git a/java/atividades/Atividade1.java b/java/atividades/Atividade1.java
new file mode 100644
index 0000000..e620ccc
--- /dev/null
+++ b/java/atividades/Atividade1.java
@@ -0,0 +1,27 @@
+import javax.swing.*;
+
+class Atividade1
+{
+ public static void main(String args[])
+ {
+ int num1, num2;
+ double div, pow;
+ String msg = "";
+
+ num1 = Integer.parseInt(JOptionPane.showInputDialog("Digite o primeiro numero:"));
+ num2 = Integer.parseInt(JOptionPane.showInputDialog("Digite o segundo numero:"));
+
+ div = (int)num1 / (int)num2;
+ pow = Math.pow(num1, num2);
+
+ msg = msg + " Resultado das operacoes: \n";
+ msg = msg + "Quociente: " + div + "\n";
+ msg = msg + "Potencia de " + num1 + " elevado a " + num2 + ": " + pow + "\n";
+ msg = msg + "\n";
+
+ JOptionPane.showMessageDialog(null, msg);
+
+ System.exit(0);
+
+ }
+}
diff --git a/java/atividades/Contas.java b/java/atividades/Contas.java
new file mode 100644
index 0000000..9fac5cf
--- /dev/null
+++ b/java/atividades/Contas.java
@@ -0,0 +1,29 @@
+class Contas
+{
+ public static void main(String args[])
+ {
+ int n1, n2;
+ int mod, div;
+ double raiz, pow;
+ String msg = "";
+
+ n1 = Integer.parseInt(args[0]);
+ n2 = Integer.parseInt(args[1]);
+
+ mod = n1 % n2;
+ div = (int)n1 / (int)n2;
+ raiz = Math.sqrt(n1);
+ pow = Math.pow(n1, n2);
+
+ // Saida
+
+ msg = "n1 = " + n1 + " n2 = " + n2 + "\n";
+ msg = msg + "mod n1 % n2 = " + mod + "\n";
+ msg = msg + "quociente: " + div + "\n";
+ msg = msg + "sqr: " + raiz + "\n";
+ msg = msg + "Power: " + pow + "\n";
+
+ System.out.println(msg);
+ System.exit(0);
+ }
+}
diff --git a/java/atividades/Decisao1.java b/java/atividades/Decisao1.java
new file mode 100644
index 0000000..421bd08
--- /dev/null
+++ b/java/atividades/Decisao1.java
@@ -0,0 +1,40 @@
+import javax.swing.*;
+
+class Decisao1
+{
+ public static void main(String args[])
+ {
+ int num;
+ char op = 0;
+ String msg = "", msgEntr = "Digite 1 p/ par/impar\nDigite 2 para positivo/negativo";
+
+ num = Integer.parseInt(JOptionPane.showInputDialog("Digite um numero inteiro"));
+ op = (JOptionPane.showInputDialog(msgEntr)).charAt(0);
+
+ switch(op) {
+ case '1':
+ if (num % 2 == 0) {
+ msg = msg + num + " eh par.\n";
+ }
+ else {
+ msg = msg + num + " eh impar.\n";
+ }
+ break;
+
+ case '2':
+ if (num > 0) {
+ msg = msg + num + " eh positivo.\n";
+ }
+ else {
+ msg = msg + num + " eh negativo.\n";
+ }
+ break;
+
+ default: JOptionPane.showMessageDialog(null, "Opcao invalida");
+ }
+ if (op == '1' | op == '2') {
+ JOptionPane.showMessageDialog(null, msg);
+ }
+ System.exit(0);
+ }
+}
diff --git a/java/atividades/ExLoop.java b/java/atividades/ExLoop.java
new file mode 100644
index 0000000..98664a2
--- /dev/null
+++ b/java/atividades/ExLoop.java
@@ -0,0 +1,36 @@
+import javax.swing.*;
+
+class ExLoop {
+ public static void main(String args[])
+ {
+ int a = 0, b = 0, soma = 1;
+ char op = 0;
+ String msg = "", msgEntr = "1 para adicao - 2 para somatoria\n\n";
+ a = Integer.parseInt(JOptionPane.showInputDialog("Numero 1:"));
+ b = Integer.parseInt(JOptionPane.showInputDialog("Numero 2:"));
+ op = (JOptionPane.showInputDialog(msgEntr)).charAt(0);
+
+ switch(op) {
+ case '1': {
+ if ( a > 0 && b > 0) {
+ soma = a * b;
+ msg = msg + "Produto: " + soma + "\n\n";
+ }
+ break;
+ }
+ case '2': {
+ for (int i = 1; i <= b; i++) {
+ soma = soma * a;
+ }
+ msg = msg + "Produtoria: " + soma + "\n\n";
+ break;
+ }
+ default: JOptionPane.showMessageDialog(null, "Opcao invalida\n");
+ }
+
+ if (op >= '1' && op <= '2') {
+ JOptionPane.showMessageDialog(null, msg);
+ }
+ System.exit(0);
+ }
+}
diff --git a/java/atividades/Exercise1.java b/java/atividades/Exercise1.java
new file mode 100644
index 0000000..1430670
--- /dev/null
+++ b/java/atividades/Exercise1.java
@@ -0,0 +1,18 @@
+class Exercise1
+{
+ public static void main(String args[])
+ {
+ String nome = "Foo Bar";
+ String curso = "Engenharia de computacao";
+ int idade = 38;
+ char sex = '?';
+ double peso = 38;
+
+ System.out.println("Nome: " + nome);
+ System.out.println("Curso: " + curso);
+ System.out.println("idade: " + idade);
+ System.out.println("Genero: " + sex);
+ System.out.println("peso" + peso + " quilos");
+
+ }
+}
diff --git a/java/atividades/Primeiro.java b/java/atividades/Primeiro.java
new file mode 100644
index 0000000..1febd1e
--- /dev/null
+++ b/java/atividades/Primeiro.java
@@ -0,0 +1,16 @@
+class Primeiro {
+ public static void main (String args[]) {
+ int inteiro = 47;
+ char caracter = 'F';
+ double real = 1.65;
+ String frase = "Lucy Mari";
+ boolean VF = true;
+
+ if (VF == true) {
+ System.out.println("Eu sou o " + frase + " tenho "
+ + inteiro + " anos, e tenho " + real + "m de altura");
+ }
+
+ System.exit(0);
+ }
+}
diff --git a/java/atividades/Programa03.java b/java/atividades/Programa03.java
new file mode 100644
index 0000000..55dde95
--- /dev/null
+++ b/java/atividades/Programa03.java
@@ -0,0 +1,26 @@
+import javax.swing.*;
+
+class Programa03
+{
+ public static void main (String args[])
+ {
+ int n1, n2, mod;
+ double raiz1, raiz2;
+ String msg = "";
+
+ n1 = Integer.parseInt(JOptionPane.showInputDialog("Numero 1:"));
+ n2 = Integer.parseInt(JOptionPane.showInputDialog("Numero 2:"));
+
+ mod = n1 % n2;
+ raiz1 = Math.sqrt(n1);
+ raiz2 = Math.sqrt(n2);
+
+ msg = msg + "remainder: " + mod + "\n";
+ msg = msg + "Square n1: " + raiz1 + "\n";
+ msg = msg + "Square n2; " + raiz2 + "\n";
+
+ JOptionPane.showMessageDialog(null, msg);
+
+ System.exit(0);
+ }
+}
diff --git a/java/atividades/Segundo.java b/java/atividades/Segundo.java
new file mode 100644
index 0000000..35ba173
--- /dev/null
+++ b/java/atividades/Segundo.java
@@ -0,0 +1,13 @@
+class Segundo {
+ public static void main (String args[]) {
+ int n1, n2, soma;
+
+ n1 = Integer.parseInt(args[0]);
+ n2 = Integer.parseInt(args[1]);
+
+ soma = n1 + n2;
+
+ System.out.println(n1 + " + " + n2 + " = " + soma);
+ System.exit(0);
+ }
+}
diff --git a/java/atividades/dados.java b/java/atividades/dados.java
new file mode 100644
index 0000000..50e4f26
--- /dev/null
+++ b/java/atividades/dados.java
@@ -0,0 +1,18 @@
+class DadosNoJava {
+ public static void main (String args[])
+ {
+ int NumInt;
+ double NumReal, soma;
+ char caracter;
+
+ NumInt = Integer.parseInt(args[0]);
+ NumReal = Double.parseDouble(args[1]);
+ caracter = (args[2]).charAt(0);
+
+ soma = (double)NumInt + NumReal;
+
+ System.out.println((double)NumInt + " + " + NumReal + " = "
+ + soma + " sinal " + caracter);
+ System.exit(0);
+ }
+}
diff --git a/java/atividades/loop_while.java b/java/atividades/loop_while.java
new file mode 100644
index 0000000..cc7f2e7
--- /dev/null
+++ b/java/atividades/loop_while.java
@@ -0,0 +1,51 @@
+import javax.swing.*;
+
+class loop_while
+{
+ public static void main(String args[])
+ {
+ int Tabuada;
+ char op = 0;
+ String msg = "", msgEntr = "1: For - 2: While - 3: do_while\n";
+
+ Tabuada = Integer.parseInt(JOptionPane.showInputDialog("Numero inteiro:"));
+ op = (JOptionPane.showInputDialog(msgEntr)).charAt(0);
+
+ switch(op) {
+ case '1': {
+ msg = msg + "Tabuada do " + Tabuada + " pelo for: \n\n";
+ for (int i=1; i<=10; i++) {
+ msg = msg + Tabuada + " x " + i + " = " +
+ Tabuada*i + "\n";
+ }
+ break;
+ }
+ case '2': {
+ msg = msg + "Tabuada do " + Tabuada + " pelo while: \n\n";
+ int i = 1;
+ while (i <= 10) {
+ msg = msg + Tabuada + " x " + i + " = " +
+ Tabuada*i + "\n";
+ i++;
+ }
+ break;
+ }
+ case '3':
+ msg = msg + "Tabuada do " + Tabuada + " pelo while: \n\n";
+ int i = 1;
+ do {
+ msg = msg + Tabuada + " x " + i + " = " +
+ Tabuada*i + "\n";
+ i++;
+ }while(i <= 10);
+ break;
+ default:
+ }
+
+ if (op >= '1' && op <= '3') {
+ JOptionPane.showMessageDialog(null, msg);
+ }
+
+ System.exit(0);
+ }
+}
diff --git a/java/atividades/test_swing.java b/java/atividades/test_swing.java
new file mode 100644
index 0000000..ea94070
--- /dev/null
+++ b/java/atividades/test_swing.java
@@ -0,0 +1,49 @@
+import javax.swing.*;
+
+
+class test_swing
+
+{
+
+ public static void main(String args[])
+
+ {
+
+ int num1, num2;
+
+ double div, pow;
+
+ String msg = "";
+
+
+ num1 = Integer.parseInt(JOptionPane.showInputDialog("Digite o primeiro numero:"));
+
+ num2 = Integer.parseInt(JOptionPane.showInputDialog("Digite o segundo numero:"));
+
+
+ div = (int)num1 / (int)num2;
+
+ pow = Math.pow(num1, num2);
+
+
+ msg = msg + " Resultado das operacoes: \n";
+
+ msg = msg + "Quociente: " + div + "\n";
+
+ msg = msg + "Potencia de " + num1 + " elevado a " + num2 + ": " + pow + "\n";
+
+ msg = msg + "\n";
+
+
+ JOptionPane.showMessageDialog(null, msg);
+
+
+ System.exit(0);
+
+
+ }
+
+}
+
+
+
diff --git a/java/qfind/QuickFindUF.java b/java/qfind/QuickFindUF.java
new file mode 100644
index 0000000..4018515
--- /dev/null
+++ b/java/qfind/QuickFindUF.java
@@ -0,0 +1,39 @@
+/*
+ * Quick Find algorithm
+ *
+ * Very slow as it uses N^2 time as it needs to access the whole array twice.
+ *
+ * If we have a 10^9 union commands on 10^9 objects, we'll need 10^18 operations
+ * to actually finish the algorithm.
+ * 30+ years of computer time.
+ *
+ * Quadratic algorithms don't scale with technology.
+ */
+
+public class QuickFindUF {
+ private int[] id;
+
+ /* Constructor */
+ public QuickFindUF(int N) {
+ id = new int[N];
+
+ for (int i = 0; i < N; i++)
+ id[i] = i;
+ }
+
+ /* Are the objects connected */
+ public boolean connected(int p, int q) {
+ return id[p] == id[q];
+ }
+
+ /* Connect two objects */
+ public void union(int p, int q) {
+ int pid = id[p];
+ int qid = id[q];
+
+ for (int i = 0; i < id.length; i++) {
+ if (id[i] == pid)
+ id[i] = qid;
+ }
+ }
+}
diff --git a/java/qfind/QuickUnionUF.java b/java/qfind/QuickUnionUF.java
new file mode 100644
index 0000000..aab4fb4
--- /dev/null
+++ b/java/qfind/QuickUnionUF.java
@@ -0,0 +1,47 @@
+/*
+ * Quick Union algorithm
+ *
+ * Slightly better than quickfind
+ *
+ * treats each element in the array as a node in a tree and trees may be
+ * connected together or not. Essentially each element might be its own tree.
+ *
+ * Find: Check if p and q have the same root
+ *
+ * Union. Merge components containing p and q, set the id of p's root to the id
+ * of q's root.
+ *
+ * Still too slow though. Trees can get too tall, where the worst case is a tree
+ * where one element points to a single one until the end of the tree,
+ * essentially creating an array.
+ */
+
+public class QuickUnionUF {
+ private int[] id;
+
+ /* Constructor */
+ public QuickUnionUF(int N) {
+ id = new int[N];
+
+ for (int i = 0; i < N; i++)
+ id[i] = i;
+ }
+
+ /* Return root of 'i' */
+ private int root(int i) {
+ while (i != id[i])
+ i = id[i];
+ return i;
+ }
+
+ /* Are the objects connected */
+ public boolean connected(int p, int q) {
+ return root(p) == root(q);
+ }
+
+ /* Connect two objects */
+ public void union(int p, int q) {
+ int proot = root(p);
+ id[proot] = root(q);
+ }
+}
diff --git a/java/qfind/WeightedQuickUnionUF.java b/java/qfind/WeightedQuickUnionUF.java
new file mode 100644
index 0000000..45f8ba7
--- /dev/null
+++ b/java/qfind/WeightedQuickUnionUF.java
@@ -0,0 +1,62 @@
+/*
+ * Weighted Quick Union algorithm
+ *
+ * Adds weight to the quick union.
+ *
+ * Find: Check if p and q have the same root
+ *
+ * Union. Merge trees, but the merge is done depending on the size of each tree.
+ * The smaller one will be merged into the larger one.
+ *
+ * The downside is we need to keep a new extra array to keep track of the
+ * number of elements on each node.
+ *
+ */
+
+public class WeightedQuickUnionUF {
+ private int[] id;
+ private int[] sz;
+
+ /* Constructor */
+ public WeightedQuickUnionUF(int N) {
+ id = new int[N];
+ sz = new int[N];
+
+ for (int i = 0; i < N; i++)
+ id[i] = i;
+
+ /* Every node starts with a single item, itself */
+ for (int i = 0; i < N; i++)
+ sz[i] = 1;
+ }
+
+ /* Return root of 'i' */
+ private int root(int i) {
+ while (i != id[i]) {
+ /* Compress paths, by pointing the current node to the
+ * root of its parent */
+ id[i] = id[id[i]];
+ i = id[i];
+ }
+ return i;
+ }
+
+ /* Are the objects connected */
+ public boolean connected(int p, int q) {
+ return root(p) == root(q);
+ }
+
+ /* Connect two objects */
+ public void union(int p, int q) {
+ int proot = root(p);
+ int qroot = root(q);
+
+ if (sz[proot] < sz[qroot]) {
+ id[proot] = qroot;
+ sz[proot] += sz[qroot];
+ } else {
+ id[qroot] = proot;
+ sz[qroot] += sz[proot];
+ }
+ }
+}
diff --git a/java/qfind/qfind.java b/java/qfind/qfind.java
new file mode 100644
index 0000000..eb274c0
--- /dev/null
+++ b/java/qfind/qfind.java
@@ -0,0 +1,5 @@
+public class qfind {
+ public static void main(String args[]) {
+ System.out.println("Hello World");
+ }
+}
diff --git a/java/stacks/StackClient.java b/java/stacks/StackClient.java
new file mode 100644
index 0000000..d2a55cc
--- /dev/null
+++ b/java/stacks/StackClient.java
@@ -0,0 +1,14 @@
+import java.Stdin.*;
+public class StackClient {
+ public static void main(String[] args) {
+ StackOfStrings stack = new StackOfStrings();
+
+ while (!StdIn.isEmpty) {
+ String s = StdIn.readString();
+ if (s.equals("-"))
+ StdOut.print(stack.pop());
+ else
+ stack.push(s);
+ }
+}
+}
diff --git a/java/stacks/StackOfStrings.java b/java/stacks/StackOfStrings.java
new file mode 100644
index 0000000..d6a9e3b
--- /dev/null
+++ b/java/stacks/StackOfStrings.java
@@ -0,0 +1,39 @@
+public class StackOfStrings {
+
+ private class Node {
+ String item;
+ Node next;
+ }
+
+ private Node first = null;
+ private int size = 0;
+
+ public boolean isEmpty() {
+ return first == null;
+ }
+/*
+ public void STackOfStrings() {
+
+ }
+*/
+
+ public void push(String item) {
+ Node oldfirst = first;
+ first = new Node();
+ first.item = item;
+ first.next = oldfirst;
+ size++;
+ }
+
+ public String pop() {
+ String i = first.item;
+ first = first.next;
+ size--;
+ return i;
+ }
+
+ public int size() {
+ return size;
+ }
+
+}
diff --git a/java/stacks/StdIn.java b/java/stacks/StdIn.java
new file mode 100644
index 0000000..d023aa9
--- /dev/null
+++ b/java/stacks/StdIn.java
@@ -0,0 +1,670 @@
+/******************************************************************************
+ * Compilation: javac StdIn.java
+ * Execution: java StdIn (interactive test of basic functionality)
+ * Dependencies: none
+ *
+ * Reads in data of various types from standard input.
+ *
+ ******************************************************************************/
+
+import java.util.ArrayList;
+import java.util.InputMismatchException;
+import java.util.Locale;
+import java.util.NoSuchElementException;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+/**
+ * <p><b>Overview.</b>
+ * The {@code StdIn} class provides static methods for reading strings
+ * and numbers from standard input.
+ * These functions fall into one of four categories:
+ * <ul>
+ * <li>those for reading individual tokens from standard input, one at a time,
+ * and converting each to a number, string, or boolean
+ * <li>those for reading characters from standard input, one at a time
+ * <li>those for reading lines from standard input, one at a time
+ * <li>those for reading a sequence of values of the same type from standard input,
+ * and returning the values in an array
+ * </ul>
+ * <p>
+ * Generally, it is best not to mix functions from the different
+ * categories in the same program.
+ * <p>
+ * <b>Getting started.</b>
+ * To use this class, you must have {@code StdIn.class} in your
+ * Java classpath. If you used our autoinstaller, you should be all set.
+ * Otherwise, either download
+ * <a href = "https://introcs.cs.princeton.edu/java/code/stdlib.jar">stdlib.jar</a>
+ * and add to your Java classpath or download
+ * <a href = "https://introcs.cs.princeton.edu/java/stdlib/StdIn.java">StdIn.java</a>
+ * and put a copy in your working directory.
+ * <p>
+ * <b>Reading tokens from standard input and converting to numbers and strings.</b>
+ * You can use the following methods to read numbers, strings, and booleans
+ * from standard input one at a time:
+ * <ul>
+ * <li> {@link #isEmpty()}
+ * <li> {@link #readInt()}
+ * <li> {@link #readDouble()}
+ * <li> {@link #readString()}
+ * <li> {@link #readShort()}
+ * <li> {@link #readLong()}
+ * <li> {@link #readFloat()}
+ * <li> {@link #readByte()}
+ * <li> {@link #readBoolean()}
+ * </ul>
+ * <p>
+ * The first method returns true if standard input has no more tokens.
+ * Each other method skips over any input that is whitespace. Then, it reads
+ * the next token and attempts to convert it into a value of the specified
+ * type. If it succeeds, it returns that value; otherwise, it
+ * throws an {@link InputMismatchException}.
+ * <p>
+ * <em>Whitespace</em> includes spaces, tabs, and newlines; the full definition
+ * is inherited from {@link Character#isWhitespace(char)}.
+ * A <em>token</em> is a maximal sequence of non-whitespace characters.
+ * The precise rules for describing which tokens can be converted to
+ * integers and floating-point numbers are inherited from
+ * <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#number-syntax">Scanner</a>,
+ * using the locale {@link Locale#US}; the rules
+ * for floating-point numbers are slightly different
+ * from those in {@link Double#valueOf(String)},
+ * but unlikely to be of concern to most programmers.
+ * <p>
+ * As an example, the following code fragment reads integers from standard input,
+ * one at a time, and prints them one per line.
+ * <pre>
+ * while (!StdIn.isEmpty()) {
+ * double value = StdIn.readDouble();
+ * StdOut.println(value);
+ * }
+ * </pre>
+ * <p>
+ * <b>Reading characters from standard input.</b>
+ * You can use the following two methods to read characters from standard input one at a time:
+ * <ul>
+ * <li> {@link #hasNextChar()}
+ * <li> {@link #readChar()}
+ * </ul>
+ * <p>
+ * The first method returns true if standard input has more input (including whitespace).
+ * The second method reads and returns the next character of input on standard
+ * input (possibly a whitespace character).
+ * <p>
+ * As an example, the following code fragment reads characters from standard input,
+ * one character at a time, and prints it to standard output.
+ * <pre>
+ * while (StdIn.hasNextChar()) {
+ * char c = StdIn.readChar();
+ * StdOut.print(c);
+ * }
+ * </pre>
+ * <p>
+ * <b>Reading lines from standard input.</b>
+ * You can use the following two methods to read lines from standard input:
+ * <ul>
+ * <li> {@link #hasNextLine()}
+ * <li> {@link #readLine()}
+ * </ul>
+ * <p>
+ * The first method returns true if standard input has more input (including whitespace).
+ * The second method reads and returns the remaining portion of
+ * the next line of input on standard input (possibly whitespace),
+ * discarding the trailing line separator.
+ * <p>
+ * A <em>line separator</em> is defined to be one of the following strings:
+ * {@code \n} (Linux), {@code \r} (old Macintosh),
+ * {@code \r\n} (Windows),
+ * {@code \}{@code u2028}, {@code \}{@code u2029}, or {@code \}{@code u0085}.
+ * <p>
+ * As an example, the following code fragment reads text from standard input,
+ * one line at a time, and prints it to standard output.
+ * <pre>
+ * while (StdIn.hasNextLine()) {
+ * String line = StdIn.readLine();
+ * StdOut.println(line);
+ * }
+ * </pre>
+ * <p>
+ * <b>Reading a sequence of values of the same type from standard input.</b>
+ * You can use the following methods to read a sequence numbers, strings,
+ * or booleans (all of the same type) from standard input:
+ * <ul>
+ * <li> {@link #readAllDoubles()}
+ * <li> {@link #readAllInts()}
+ * <li> {@link #readAllLongs()}
+ * <li> {@link #readAllStrings()}
+ * <li> {@link #readAllLines()}
+ * <li> {@link #readAll()}
+ * </ul>
+ * <p>
+ * The first three methods read of all of remaining token on standard input
+ * and converts the tokens to values of
+ * the specified type, as in the corresponding
+ * {@code readDouble}, {@code readInt}, and {@code readString()} methods.
+ * The {@code readAllLines()} method reads all remaining lines on standard
+ * input and returns them as an array of strings.
+ * The {@code readAll()} method reads all remaining input on standard
+ * input and returns it as a string.
+ * <p>
+ * As an example, the following code fragment reads all of the remaining
+ * tokens from standard input and returns them as an array of strings.
+ * <pre>
+ * String[] words = StdIn.readAllStrings();
+ * </pre>
+ * <p>
+ * <b>Differences with Scanner.</b>
+ * {@code StdIn} and {@link Scanner} are both designed to parse
+ * tokens and convert them to primitive types and strings.
+ * The main differences are summarized below:
+ * <ul>
+ * <li> {@code StdIn} is a set of static methods and reads
+ * reads input from only standard input. It is suitable for use before
+ * a programmer knows about objects.
+ * See {@link In} for an object-oriented version that handles
+ * input from files, URLs,
+ * and sockets.
+ * <li> {@code StdIn} uses whitespace as the delimiter pattern
+ * that separates tokens.
+ * {@link Scanner} supports arbitrary delimiter patterns.
+ * <li> {@code StdIn} coerces the character-set encoding to UTF-8,
+ * which is the most widely used character encoding for Unicode.
+ * <li> {@code StdIn} coerces the locale to {@link Locale#US},
+ * for consistency with {@link StdOut}, {@link Double#parseDouble(String)},
+ * and floating-point literals.
+ * <li> {@code StdIn} has convenient methods for reading a single
+ * character; reading in sequences of integers, doubles, or strings;
+ * and reading in all of the remaining input.
+ * </ul>
+ * <p>
+ * Historical note: {@code StdIn} preceded {@code Scanner}; when
+ * {@code Scanner} was introduced, this class was re-implemented to use {@code Scanner}.
+ * <p>
+ * <b>Using standard input.</b>
+ * Standard input is a fundamental operating system abstraction on Mac OS X,
+ * Windows, and Linux.
+ * The methods in {@code StdIn} are <em>blocking</em>, which means that they
+ * will wait until you enter input on standard input.
+ * If your program has a loop that repeats until standard input is empty,
+ * you must signal that the input is finished.
+ * To do so, depending on your operating system and IDE,
+ * use either {@code <Ctrl-d>} or {@code <Ctrl-z>}, on its own line.
+ * If you are redirecting standard input from a file, you will not need
+ * to do anything to signal that the input is finished.
+ * <p>
+ * <b>Known bugs.</b>
+ * Java's UTF-8 encoding does not recognize the optional
+ * <a href = "http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058">byte-order mask</a>.
+ * If the input begins with the optional byte-order mask, {@code StdIn}
+ * will have an extra character {@code \}{@code uFEFF} at the beginning.
+ * <p>
+ * <b>Reference.</b>
+ * For additional documentation,
+ * see <a href="https://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
+ * <em>Computer Science: An Interdisciplinary Approach</em>
+ * by Robert Sedgewick and Kevin Wayne.
+ *
+ * @author Robert Sedgewick
+ * @author Kevin Wayne
+ * @author David Pritchard
+ */
+public final class StdIn {
+
+ /*** begin: section (1 of 2) of code duplicated from In to StdIn. */
+
+ // assume Unicode UTF-8 encoding
+ private static final String CHARSET_NAME = "UTF-8";
+
+ // assume language = English, country = US for consistency with System.out.
+ private static final Locale LOCALE = Locale.US;
+
+ // the default token separator; we maintain the invariant that this value
+ // is held by the scanner's delimiter between calls
+ private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+");
+
+ // makes whitespace significant
+ private static final Pattern EMPTY_PATTERN = Pattern.compile("");
+
+ // used to read the entire input
+ private static final Pattern EVERYTHING_PATTERN = Pattern.compile("\\A");
+
+ /*** end: section (1 of 2) of code duplicated from In to StdIn. */
+
+ private static Scanner scanner;
+
+ // it doesn't make sense to instantiate this class
+ private StdIn() { }
+
+ //// begin: section (2 of 2) of code duplicated from In to StdIn,
+ //// with all methods changed from "public" to "public static"
+
+ /**
+ * Returns true if standard input is empty (except possibly for whitespace).
+ * Use this method to know whether the next call to {@link #readString()},
+ * {@link #readDouble()}, etc. will succeed.
+ *
+ * @return {@code true} if standard input is empty (except possibly
+ * for whitespace); {@code false} otherwise
+ */
+ public static boolean isEmpty() {
+ return !scanner.hasNext();
+ }
+
+ /**
+ * Returns true if standard input has a next line.
+ * Use this method to know whether the
+ * next call to {@link #readLine()} will succeed.
+ * This method is functionally equivalent to {@link #hasNextChar()}.
+ *
+ * @return {@code true} if standard input has more input (including whitespace);
+ * {@code false} otherwise
+ */
+ public static boolean hasNextLine() {
+ return scanner.hasNextLine();
+ }
+
+ /**
+ * Returns true if standard input has more input (including whitespace).
+ * Use this method to know whether the next call to {@link #readChar()} will succeed.
+ * This method is functionally equivalent to {@link #hasNextLine()}.
+ *
+ * @return {@code true} if standard input has more input (including whitespace);
+ * {@code false} otherwise
+ */
+ public static boolean hasNextChar() {
+ scanner.useDelimiter(EMPTY_PATTERN);
+ boolean result = scanner.hasNext();
+ scanner.useDelimiter(WHITESPACE_PATTERN);
+ return result;
+ }
+
+
+ /**
+ * Reads and returns the next line, excluding the line separator if present.
+ *
+ * @return the next line, excluding the line separator if present;
+ * {@code null} if no such line
+ */
+ public static String readLine() {
+ String line;
+ try {
+ line = scanner.nextLine();
+ }
+ catch (NoSuchElementException e) {
+ line = null;
+ }
+ return line;
+ }
+
+ /**
+ * Reads and returns the next character.
+ *
+ * @return the next {@code char}
+ * @throws NoSuchElementException if standard input is empty
+ */
+ public static char readChar() {
+ try {
+ scanner.useDelimiter(EMPTY_PATTERN);
+ String ch = scanner.next();
+ assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ + " Please contact the authors.";
+ scanner.useDelimiter(WHITESPACE_PATTERN);
+ return ch.charAt(0);
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attempts to read a 'char' value from standard input, "
+ + "but no more tokens are available");
+ }
+ }
+
+ /**
+ * Reads and returns the remainder of the input, as a string.
+ *
+ * @return the remainder of the input, as a string
+ * @throws NoSuchElementException if standard input is empty
+ */
+ public static String readAll() {
+ if (!scanner.hasNextLine())
+ return "";
+
+ String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
+ // not that important to reset delimiter, since now scanner is empty
+ scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
+ return result;
+ }
+
+
+ /**
+ * Reads the next token from standard input and returns it as a {@code String}.
+ *
+ * @return the next {@code String}
+ * @throws NoSuchElementException if standard input is empty
+ */
+ public static String readString() {
+ try {
+ return scanner.next();
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attempts to read a 'String' value from standard input, "
+ + "but no more tokens are available");
+ }
+ }
+
+ /**
+ * Reads the next token from standard input, parses it as an integer, and returns the integer.
+ *
+ * @return the next integer on standard input
+ * @throws NoSuchElementException if standard input is empty
+ * @throws InputMismatchException if the next token cannot be parsed as an {@code int}
+ */
+ public static int readInt() {
+ try {
+ return scanner.nextInt();
+ }
+ catch (InputMismatchException e) {
+ String token = scanner.next();
+ throw new InputMismatchException("attempts to read an 'int' value from standard input, "
+ + "but the next token is \"" + token + "\"");
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attemps to read an 'int' value from standard input, "
+ + "but no more tokens are available");
+ }
+
+ }
+
+ /**
+ * Reads the next token from standard input, parses it as a double, and returns the double.
+ *
+ * @return the next double on standard input
+ * @throws NoSuchElementException if standard input is empty
+ * @throws InputMismatchException if the next token cannot be parsed as a {@code double}
+ */
+ public static double readDouble() {
+ try {
+ return scanner.nextDouble();
+ }
+ catch (InputMismatchException e) {
+ String token = scanner.next();
+ throw new InputMismatchException("attempts to read a 'double' value from standard input, "
+ + "but the next token is \"" + token + "\"");
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attempts to read a 'double' value from standard input, "
+ + "but no more tokens are available");
+ }
+ }
+
+ /**
+ * Reads the next token from standard input, parses it as a float, and returns the float.
+ *
+ * @return the next float on standard input
+ * @throws NoSuchElementException if standard input is empty
+ * @throws InputMismatchException if the next token cannot be parsed as a {@code float}
+ */
+ public static float readFloat() {
+ try {
+ return scanner.nextFloat();
+ }
+ catch (InputMismatchException e) {
+ String token = scanner.next();
+ throw new InputMismatchException("attempts to read a 'float' value from standard input, "
+ + "but the next token is \"" + token + "\"");
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attempts to read a 'float' value from standard input, "
+ + "but there no more tokens are available");
+ }
+ }
+
+ /**
+ * Reads the next token from standard input, parses it as a long integer, and returns the long integer.
+ *
+ * @return the next long integer on standard input
+ * @throws NoSuchElementException if standard input is empty
+ * @throws InputMismatchException if the next token cannot be parsed as a {@code long}
+ */
+ public static long readLong() {
+ try {
+ return scanner.nextLong();
+ }
+ catch (InputMismatchException e) {
+ String token = scanner.next();
+ throw new InputMismatchException("attempts to read a 'long' value from standard input, "
+ + "but the next token is \"" + token + "\"");
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attempts to read a 'long' value from standard input, "
+ + "but no more tokens are available");
+ }
+ }
+
+ /**
+ * Reads the next token from standard input, parses it as a short integer, and returns the short integer.
+ *
+ * @return the next short integer on standard input
+ * @throws NoSuchElementException if standard input is empty
+ * @throws InputMismatchException if the next token cannot be parsed as a {@code short}
+ */
+ public static short readShort() {
+ try {
+ return scanner.nextShort();
+ }
+ catch (InputMismatchException e) {
+ String token = scanner.next();
+ throw new InputMismatchException("attempts to read a 'short' value from standard input, "
+ + "but the next token is \"" + token + "\"");
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attempts to read a 'short' value from standard input, "
+ + "but no more tokens are available");
+ }
+ }
+
+ /**
+ * Reads the next token from standard input, parses it as a byte, and returns the byte.
+ *
+ * @return the next byte on standard input
+ * @throws NoSuchElementException if standard input is empty
+ * @throws InputMismatchException if the next token cannot be parsed as a {@code byte}
+ */
+ public static byte readByte() {
+ try {
+ return scanner.nextByte();
+ }
+ catch (InputMismatchException e) {
+ String token = scanner.next();
+ throw new InputMismatchException("attempts to read a 'byte' value from standard input, "
+ + "but the next token is \"" + token + "\"");
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attempts to read a 'byte' value from standard input, "
+ + "but no more tokens are available");
+ }
+ }
+
+ /**
+ * Reads the next token from standard input, parses it as a boolean,
+ * and returns the boolean.
+ *
+ * @return the next boolean on standard input
+ * @throws NoSuchElementException if standard input is empty
+ * @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}:
+ * {@code true} or {@code 1} for true, and {@code false} or {@code 0} for false,
+ * ignoring case
+ */
+ public static boolean readBoolean() {
+ try {
+ String token = readString();
+ if ("true".equalsIgnoreCase(token)) return true;
+ if ("false".equalsIgnoreCase(token)) return false;
+ if ("1".equals(token)) return true;
+ if ("0".equals(token)) return false;
+ throw new InputMismatchException("attempts to read a 'boolean' value from standard input, "
+ + "but the next token is \"" + token + "\"");
+ }
+ catch (NoSuchElementException e) {
+ throw new NoSuchElementException("attempts to read a 'boolean' value from standard input, "
+ + "but no more tokens are available");
+ }
+
+ }
+
+ /**
+ * Reads all remaining tokens from standard input and returns them as an array of strings.
+ *
+ * @return all remaining tokens on standard input, as an array of strings
+ */
+ public static String[] readAllStrings() {
+ // we could use readAll.trim().split(), but that's not consistent
+ // because trim() uses characters 0x00..0x20 as whitespace
+ String[] tokens = WHITESPACE_PATTERN.split(readAll());
+ if (tokens.length == 0 || tokens[0].length() > 0)
+ return tokens;
+
+ // don't include first token if it is leading whitespace
+ String[] decapitokens = new String[tokens.length-1];
+ for (int i = 0; i < tokens.length - 1; i++)
+ decapitokens[i] = tokens[i+1];
+ return decapitokens;
+ }
+
+ /**
+ * Reads all remaining lines from standard input and returns them as an array of strings.
+ * @return all remaining lines on standard input, as an array of strings
+ */
+ public static String[] readAllLines() {
+ ArrayList<String> lines = new ArrayList<String>();
+ while (hasNextLine()) {
+ lines.add(readLine());
+ }
+ return lines.toArray(new String[0]);
+ }
+
+ /**
+ * Reads all remaining tokens from standard input, parses them as integers, and returns
+ * them as an array of integers.
+ * @return all remaining integers on standard input, as an array
+ * @throws InputMismatchException if any token cannot be parsed as an {@code int}
+ */
+ public static int[] readAllInts() {
+ String[] fields = readAllStrings();
+ int[] vals = new int[fields.length];
+ for (int i = 0; i < fields.length; i++)
+ vals[i] = Integer.parseInt(fields[i]);
+ return vals;
+ }
+
+ /**
+ * Reads all remaining tokens from standard input, parses them as longs, and returns
+ * them as an array of longs.
+ * @return all remaining longs on standard input, as an array
+ * @throws InputMismatchException if any token cannot be parsed as a {@code long}
+ */
+ public static long[] readAllLongs() {
+ String[] fields = readAllStrings();
+ long[] vals = new long[fields.length];
+ for (int i = 0; i < fields.length; i++)
+ vals[i] = Long.parseLong(fields[i]);
+ return vals;
+ }
+
+ /**
+ * Reads all remaining tokens from standard input, parses them as doubles, and returns
+ * them as an array of doubles.
+ * @return all remaining doubles on standard input, as an array
+ * @throws InputMismatchException if any token cannot be parsed as a {@code double}
+ */
+ public static double[] readAllDoubles() {
+ String[] fields = readAllStrings();
+ double[] vals = new double[fields.length];
+ for (int i = 0; i < fields.length; i++)
+ vals[i] = Double.parseDouble(fields[i]);
+ return vals;
+ }
+
+ //// end: section (2 of 2) of code duplicated from In to StdIn
+
+ // do this once when StdIn is initialized
+ static {
+ resync();
+ }
+
+ /**
+ * If StdIn changes, use this to reinitialize the scanner.
+ */
+ private static void resync() {
+ setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME));
+ }
+
+ private static void setScanner(Scanner scanner) {
+ StdIn.scanner = scanner;
+ StdIn.scanner.useLocale(LOCALE);
+ }
+
+ /**
+ * Reads all remaining tokens, parses them as integers, and returns
+ * them as an array of integers.
+ * @return all remaining integers, as an array
+ * @throws InputMismatchException if any token cannot be parsed as an {@code int}
+ * @deprecated Replaced by {@link #readAllInts()}.
+ */
+ @Deprecated
+ public static int[] readInts() {
+ return readAllInts();
+ }
+
+ /**
+ * Reads all remaining tokens, parses them as doubles, and returns
+ * them as an array of doubles.
+ * @return all remaining doubles, as an array
+ * @throws InputMismatchException if any token cannot be parsed as a {@code double}
+ * @deprecated Replaced by {@link #readAllDoubles()}.
+ */
+ @Deprecated
+ public static double[] readDoubles() {
+ return readAllDoubles();
+ }
+
+ /**
+ * Reads all remaining tokens and returns them as an array of strings.
+ * @return all remaining tokens, as an array of strings
+ * @deprecated Replaced by {@link #readAllStrings()}.
+ */
+ @Deprecated
+ public static String[] readStrings() {
+ return readAllStrings();
+ }
+
+
+ /**
+ * Interactive test of basic functionality.
+ *
+ * @param args the command-line arguments
+ */
+ public static void main(String[] args) {
+
+ StdOut.print("Type a string: ");
+ String s = StdIn.readString();
+ StdOut.println("Your string was: " + s);
+ StdOut.println();
+
+ StdOut.print("Type an int: ");
+ int a = StdIn.readInt();
+ StdOut.println("Your int was: " + a);
+ StdOut.println();
+
+ StdOut.print("Type a boolean: ");
+ boolean b = StdIn.readBoolean();
+ StdOut.println("Your boolean was: " + b);
+ StdOut.println();
+
+ StdOut.print("Type a double: ");
+ double c = StdIn.readDouble();
+ StdOut.println("Your double was: " + c);
+ StdOut.println();
+ }
+
+}
+