0
2

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でよく使うメソッド

Posted at

入力

Scanner

クラス定義は下記のようになっています。

java.lang.Object
┗java.util.Scanner
public final class Scanner extends Object implements Iterator<String>

使用する場合は「import java.util.Scanner;」を行って下さい。

Scannerインスタンスの作成と標準入力(System.in)の読み込み

まずはScannerインスタンスを作成し、標準入力の情報をScannerインスタンスに渡します。
新しくScannerインスタンス「sc」を作成する場合、「Scanner sc = new Scanner();」と記述すればよいです。scに渡す情報を、右辺の括弧の中に引数として入力します。

続いて標準入力ですが、Javaの場合、標準入力はSystemクラスのinフィールドから取得できるので、「System.in」をScannerインスタンスに渡すことで、入力情報が取得できます。

※クラスには、そのクラスから作り出されるモノが持つ機能(メソッド)とデータ(フィールド)を記述していきます。

class クラス名{
  フィールド1
  フィールド2
  ...
  メソッド1
  メソッド2
  ...
}

以上をまとめると、System.inを引数として、Scannerインスタンス「sc」に情報を渡す場合は「Scanner sc = new Scanner(System.in);」と記述。
これで、全入力情報がインスタンスscに渡されます。

区切り文字までの読み込み(5〜11行目)

ここでは改行・スペースが区切り文字となる場合の取得方法を記載します。
文字列を取得する場合は「next」メソッド、整数を取得する場合は「nextInt」メソッドを使用します。
記述としては、「int a = sc.nextInt();」や「String s = sc.next();」のようになります。

引用:<Java> Scannerクラスの使い方(その1:基本編) - 東大ニート

0
2
1

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?