Bom dia pessoal, eu estou tentando entender como é feita a leitura da entrada dos parâmetros nessas competições.
É um simples:
Scanner s = new Scanner(System.in);
String t = s.nextLine();
System.out.println(t);
Ou é algo mais complexo?
Tem algo haver com os arquivo .IN?
Agradeço qualquer ajuda!
vou tentar explicar, mas nao sou bom nisso hehehe
toda leitura e escrita em java eh baseado em duas interfaces InputStream e OutputStream. suponha que vc queira desenvolver uma classe que faz a leitura da retina do olho, qual seria o primeiro passo?
implementar a interface de leitura InputStream.
Sendo assim toda e qualquer classe que vc usar para leitura(IN) ou escrita(OUT) vc vai usar essas interfaces. agora vc pergunta, oq eu ganho com isso?
vc ganha a vantagem de desenvolver classes capazes de ler qualquer coisa e escrever qualquer coisa. e eh exatamente isso que a classe Scanner faz, ela le qualquer InputStream que vc passar para ela, no seu caso vc passou a InputStream padrao do computador (System.in), a que eh responsavem por ler coisas digitadas do teclado.
acho q confundi mais ainda, mas tentei!
[]'s
Sim eu entendi o que você quis dizer, inclusive vou estudar mais sobre essas interfaces, mas minha dúvida é um pouco mais específica.
No caso da maratona, quando você envia um arquivo .java pro servidor pra ser avaliado, o sistema que vai testar seu programa passa os parâmetros como entradas via teclado?
Exemplo de uma entrada:
5
10 123
15 21
???
Basicamente é trabalhar com a leitura do System.in…
Você pode ter um Scanner, ou um BufferedReader desse InputStream.
Porém, quando o tempo é um fator relevante (como em Maratonas de Programação) ou Online Judges, deve ser otimizado o código.
Segue um exemplo, que já venho usando há algum tempo, e costuma minimizar bastante o ‘runtime’.
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
public class Main {
private static int BUFF_SIZE = 4096;
private static InputStream in;
private static PrintStream out;
static int inpos = BUFF_SIZE;
static byte[] input = new byte[BUFF_SIZE];
static int outpos = 0;
static byte[] output = new byte[BUFF_SIZE];
private static int available = 0;
public static void main(String[] args) throws IOException {
in = System.in;
out = System.out;
//Cria bytearray para No Number
byte[] nn = "No Number".getBytes();
//Le numero de entradas
int testCases = _int();
int count = 0;
while (count++ < testCases) {
//Le X e Y
int x = _int();
int y = _int();
//Soma os valores
int r = x+y;
//Imprime "No Number"
w_str(nn);
//Imprime a soma
w_int(r);
//Quebra de linha
ln();
}
//Manda o que está no BUFFER para a stream
_flush();
}
static void _fillIn() throws IOException {
while (in.available() == 0) {}
inpos = 0;
available = in.read(input);
}
static byte _ch() throws IOException {
if (BUFF_SIZE == inpos) {
_fillIn();
}
return input[inpos++];
}
static int _bin() throws IOException {
byte c = _ch();
while (c < '0' || c > '1') {
c = _ch();
}
int res = 0;
while (c >= '0' && c <= '1') {
res <<= 1;
res |= c - '0';
c = _ch();
}
return res;
}
static void ln() {
w_ch((byte) '\n');
}
static void skip(int count) throws IOException {
if (count >= available) {
count -= available;
_fillIn();
}
inpos += count;
available -= count;
}
static int _u_int() throws IOException {
byte c = _ch();
while (c < '0' || c > '9') {
c = _ch();
}
int res = 0;
while (c > '0' - 1) {
res = (res << 3) + (res << 1); // res *= 10
res += c - '0';
c = _ch();
}
return res;
}
static int _int() throws IOException {
boolean f = false;
byte c = _ch();
while (c < '0' || c > '9' || c == '-') {
if (c == '-') {
f = true;
}
c = _ch();
}
int res = 0;
while (c > '0' - 1) {
res = (res << 3) + (res << 1); // res *= 10
res += c - '0';
c = _ch();
}
if (f) {
return -res;
}
return res;
}
static void _flush() {
out.write(output, 0, outpos);
outpos = 0;
}
static void w_ch(byte c) {
if (BUFF_SIZE == outpos) {
_flush();
}
output[outpos++] = c;
}
private static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999 };
static int stringSize(int x) {
for (int i = 0;; i++) {
if (x <= sizeTable[i]) {
return i + 1;
}
}
}
static void w_bin(int bin) {
}
private static byte[] decimalDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private static void w_int(int num) {
if (num < 0) {
w_ch((byte) '-');
w_u_int(-num);
} else {
w_u_int(num);
}
}
private static void w_u_int(int num) {
int strSize = stringSize(num);
if (BUFF_SIZE - outpos < strSize) {
_flush();
}
int i = strSize - 1;
do {
byte c = decimalDigits[num % 10];
num /= 10;
output[outpos + i] = c;
i--;
} while (i > -1);
outpos += strSize;
}
static void w_str(byte[] str) {
for (int i = 0; i < str.length; i++) {
w_ch(str[i]);
}
}
static byte nextUtilChar() throws IOException {
byte b = _ch();
while ((b & 0xE0) == 0) {
b = _ch();
}
return b;
}
static void seekUtilChar() throws IOException {
nextUtilChar();
inpos--;
}
static boolean atUseless() throws IOException {
if (BUFF_SIZE == inpos) {
_fillIn();
}
return (input[inpos] & 0xE0) == 0;
}
}
[quote=Javax2011]Sim eu entendi o que você quis dizer, inclusive vou estudar mais sobre essas interfaces, mas minha dúvida é um pouco mais específica.
No caso da maratona, quando você envia um arquivo .java pro servidor pra ser avaliado, o sistema que vai testar seu programa passa os parâmetros como entradas via teclado?
Exemplo de uma entrada:
5
10 123
15 21
???[/quote]
Sim, ele jogará na sua entrada padrão - System.in, no caso, o Console
O comportamento deve ser o mesmo ele fazendo as entradas automaticamente ou você digitando manualmente.
Valeu Bruno, mas esse seu código basicamente lê dois inteiros e imprime o resultado?
Ele lê um inteiro (testCases) que representa quantas somas ele fará.
Após isso, ele lerá testCases vezes o X e Y, e imprimirá a soma deles.