Skip to content

Instantly share code, notes, and snippets.

@editnuki
Created June 4, 2012 00:06
Show Gist options
  • Save editnuki/2865519 to your computer and use it in GitHub Desktop.
Save editnuki/2865519 to your computer and use it in GitHub Desktop.
20120603UserInputNumber
package jp.ac.ca.data.input;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import jp.ac.ca.data.create.CreateRandomNumber;
//import java.text.NumberFormat;
public class UserInputNumber {
/**
* @author nuki このメソッドではユーザからのキーボード入力を受け配列に入力された文字列を代入する
*/
/*
* 入力回数をcountという変数名で宣言。入力は1回目からなので初期化は1で行う
*/
private static int count = 1;
public static void inputKyeboard() {
// 2つのクラスで同じ定数を宣言してるのは隣のクラスで宣言してるのに呼び方がわからないので・・・
final int ARRAY_SIZE = 4;
boolean flag = true;
/*
*
* 引数System.inを取るインスタンスInputStreamReaderを生成し、
* それを引数に取るBufferReadReaderインスタンスにを生成する。
* そのBufferReadReaderインスタンスをBufferReader型のreaderという変数名に代入する
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
// 乱数を生成し、arr[]配列に代入
int arr[] = CreateRandomNumber.randomNumber();
// ユーザからの入力に対して例外処理を行う
while (flag) {
try {
// ユーザからの入力を受け付ける前に文章を表示する。ここのcountは入力が何回目かを数えるものである
System.out.println(ARRAY_SIZE + "桁の数字を入力してください" + count + "回目");
// 変数名countをインクリメントする
count++;
// String型の変数名lineに読み込んだテキスト行を代入します。readerインスタンスのreadLineメソッドを代入
String line = reader.readLine();
// int型のarr2という配列を宣言
int[] arr2;
// arr2にARRAY_SIZEの要素が入る配列を生成
arr2 = new int[ARRAY_SIZE];
// ユーザが入力した文字列を1文字づつsubstringメソッドを用いて配列arr2へ代入する。
// 代入する際にString型からint型に変換している
for (int m = 0; m < ARRAY_SIZE; m++) {
arr2[m] = Integer.parseInt(line.substring(m, m + 1));
}
if (arr[0] == arr2[0]) {
System.out.println("HIT" + "arr[0]");
if (arr[1] == arr2[1]){
System.out.println("HIT" + "arr[1]");
if(arr[2] == arr2[2]){
System.out.println("HIT" + "arr[2]");
if (arr[3] == arr2[3]) {
System.out.println("HIT" + "arr[2]");
System.out.println("good end");
flag = false;
}
}
}
}
// IOエラーなど予期せぬ例外処理に対する実装
} catch (IOException e) {
System.out.println("test");
// 数値以外の入力n例外処理を実装
} catch (NumberFormatException e) {
System.out.println("入力は数値のみです");
// 上記例外処理で拾えなかった例外処理をここで実装
} catch (Exception e) {
System.out.println("4桁の数値を入力してください");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment