Scanner的使用 猜數字 +猜電影

猜數字
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
相關文章
相關標籤/搜索