0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaでのごく単純な入力受取り

Last updated at Posted at 2019-05-20

暫く書いていなかったため,全く忘れておりました.入力受取りを脳死で行うメモです.

共通項

import文でScannerを呼んでくる.

import java.util.*;

ScannerクラスにSystem.inを渡す.

Scanner sc = new Scanner(System.in);

文字列の受取り

$S$を文字列とする.

String S = sc.next();
String S = sc.nextLine();

ただし,nextは入力値を改行まで認識し,nextLineは空白まで認識する.たとえば

$S_1$ $S_2$
$S_3$

という入力があった場合,nextでは$S_1$ $S_2$を読み取り,nextLineでは$S_1$を読み取る.

数値の読み取り

$x$を数値とする.パースをInteger.parseInt()で行うと2倍程度速いらしい.

int x = Integer.parseInt(sc.nextLine());
int x = sc.nextInt();

配列の読み取り

$V_1, V_2, \cdots V_n$を配列Vとする.

Integer V[] = new Integer[N];
for (int i=0; i<N; i++) {
    V[i] = sc.nextInt();
}

以下だと可読性が低い.

String a = sc.nextLine();
String[] b = a.split(" ");
int[] c = Stream.of(b).mapToInt(Integer::parseInt).toArray();

Listの読み取り

$V_1, V_2, \cdots V_n$をListVとする.

ArrayList<String> V = new ArrayList<String>();
for (int i=0; i<N; i++) {
    V[i] = sc.nextInt();
    ary.add(word);
}

Scannerを自作することでより高速化が望めるらしい.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?