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