Scanner的使用 猜数字 +猜电影

2023-06-26,,

数字
public class Main { public static void main(String[] args) {
int random=(int)(Math.random()*100)+1;
System.out.println("Guess 1 ~100,you have 10 times.");
Scanner scanner=new Scanner(System.in);
boolean success=false; for (int i=10;i>0;i--){
int number=scanner.nextInt();
if (number<random){
System.out.println("small");
}else if(number>random){
System.out.println("big");
} else {
success=true;
break;
}
} if (success){
System.out.println("you win !");
}else {
System.out.println("you lose, Correct number was:"+random);
} }
}
游戏的技巧就是二分搜索法 范围是0~100;
第一次猜测50,如果更小,范围在0~50,猜测25。反之,范围在50~100,猜测75,不断重复。
实际上,最多只需猜测7次。 电影
movies.txt
the shawshank redemption
the godfather
the dark knight
schindler's list
pulp fiction
the lord of the rings
the good the bad and the ugly
fight club
the lord of the rings
forrest gump
star wars
inception
the lord of the rings
the matrix
samurai
star wars
city of god
the silence of the lambs
batman begins
die hard
chinatown
room
dunkirk
fargo
no country for old men
Movie
public class Movie {

    public  static String random(){
List<String> list=new ArrayList<>();
File file=new File("movies.txt");
try {
Scanner scanner=new Scanner(file);
while (scanner.hasNextLine()){
String movieLine=scanner.nextLine();
list.add(movieLine);
}
}catch (FileNotFoundException e){
System.out.println("not found movies.txt");
} String movie=list.get((int)(Math.random()*list.size()));
return movie; }
}
Main.java

public class Main {

    public static void main(String[] args) {

        String randomMovie = Movie.random();
boolean success = false;
StringBuilder guessedLetters = new StringBuilder(" ");
StringBuilder wrongLetters = new StringBuilder();
int length = randomMovie.length();
int wrongLettersCounter = 0;
System.out.println("Guess a letter,You have 10 times. ");
System.out.println("The length is: " + length); while (wrongLettersCounter < 10) {
Scanner scanner = new Scanner(System.in);
String newLetter = scanner.nextLine(); if (randomMovie.contains(newLetter)) {
guessedLetters.append(newLetter);
int location = randomMovie.indexOf(newLetter) + 1;
System.out.println("The position: " + location);
} else {
wrongLetters.append(newLetter);
wrongLettersCounter++;
} String displayHiddenMovie = randomMovie.replaceAll("[^" + guessedLetters + "]", "_");
if (displayHiddenMovie.equals(randomMovie)) {
success = true;
break;
}
System.out.println("You are guessing: " + displayHiddenMovie);
System.out.println("You have guessed " + wrongLettersCounter + " wrong letters: " + wrongLetters); } if (success) {
System.out.println("You win!");
} else {
System.out.println("You Lose! Correct movie was: " + randomMovie);
} } }
游戏的技巧:英语中,出现频率最高的前五个字母依次是:e, t, a, o, i
 

Scanner的使用 猜数字 +猜电影的相关教程结束。

《Scanner的使用 猜数字 +猜电影.doc》

下载本文的Word格式文档,以方便收藏与打印。