Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 2020/1/12(日)
- // 2020/1/14(火)L8改変
- // HitAndBlow.java
- import java.util.*;
- import java.util.stream.*;
- public class HitAndBlow
- {
- private List<String> answer;
- private int digit;
- private MyArrayList<String> inputnum;
- private Scanner scan = new Scanner(System.in);
- public HitAndBlow(int digit)
- {
- this.digit = digit;
- List<String> strs = IntStream.range(0, 10)
- .mapToObj(Integer::valueOf)
- .map(i -> String.valueOf(i))
- .collect(Collectors.toList());
- Collections.shuffle(strs);
- this.answer = strs.stream().skip(10 - this.digit).collect(Collectors.toList());
- }
- public void playgame()
- {
- System.out.println("ヒットアンドブローをします");
- boolean isCorrectAns = false;
- for (int i = 1; true; i++)
- {
- this.inputnumber();
- int hit = this.inputnum.gethit(this.answer);
- if (hit == this.digit)
- {
- System.out.println("正解です!ゲームを終了します。");
- isCorrectAns = true;
- break;
- }
- System.out.println(i + "回目のトライ " + hit + "ヒット!" + this.inputnum.getblow(this.answer) + "ブロー!です");
- System.out.print("続けますか? 続ける:1を入力 止める:1以外を入力:");
- if (!this.scan.nextLine().equals("1"))
- {
- break;
- }
- }
- if (!isCorrectAns)
- {
- System.out.println("正解は" + String.join("", this.answer) + "でした");
- }
- }
- private void inputnumber()
- {
- do
- {
- System.out.print(this.digit + "桁の数字を入力してください:");
- String line = this.scan.nextLine();
- // 数値に変換可能か
- try
- {
- Integer.parseInt(line);
- }
- catch (NumberFormatException nfex)
- {
- continue;
- }
- // 入力はdigit桁か
- if (line.length() == this.digit)
- {
- this.inputnum = new MyArrayList(Arrays.asList(line.split("")));
- return;
- }
- } while (true);
- }
- public static void main(String[] args)
- {
- new HitAndBlow(4).playgame();
- }
- }
- // MyArrayList.java
- import java.util.*;
- import java.util.stream.*;
- public class MyArrayList<T> extends ArrayList<T>
- {
- public MyArrayList(List<T> other)
- {
- this.addAll(other);
- }
- public int getblow(List<T> other)
- {
- List<T> templist = this.getdigitmatchlist(other);
- List<T> templist2 = (MyArrayList<T>)(this.clone());
- templist2.removeAll(templist);
- int blow = (int)(other.stream()
- .filter(s -> templist2.contains(s))
- .count());
- return blow;
- }
- public int gethit(List<T> other)
- {
- return this.getdigitmatchlist(other).size();
- }
- private List<T> getdigitmatchlist(List<T> other)
- {
- List<T> templist = new ArrayList<T>();
- for (int i = 0; i < other.size(); i++)
- {
- if (this.get(i).equals(other.get(i)))
- {
- templist.add(this.get(i));
- }
- }
- return templist;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement