นี่เป็นครั้งแรกของฉันที่นี่ ฉันเริ่มเรียนรู้วิธีการเขียนโค้ด ดังนั้นฉันหวังว่าคำถามนี้ที่ฉันมีจะไม่ใช่สิ่งที่ฉันจะหาได้จากที่นี่! (ฉันสัญญาว่าจะค้นหามาระยะหนึ่งแล้ว แต่เนื่องจากฉันเป็นมือใหม่ในหัวข้อนี้ ฉันจึงไม่พบสิ่งใดที่เข้าใจได้สำหรับฉันเพื่อแก้ไขข้อสงสัยของฉัน)
ฉันกำลังเล่นเกมง่ายๆ ใน JAVA ซึ่งโปรแกรมจะสร้างตัวเลขสุ่มและผู้เล่นจะต้องเดาตัวเลขที่สร้างขึ้น เมื่อผู้เล่นกรอกตัวเลข เกมจะแสดงคำใบ้ว่าสูงหรือต่ำกว่าตัวเลขที่สร้างขึ้นแบบสุ่ม
โปรแกรมทำงานได้ดีหากคุณป้อนเพียงตัวเลข แต่ฉันต้องการเพิ่มคำสั่ง try-catch เพื่อจัดการกับอินพุตของผู้ใช้ที่ไม่ถูกต้อง
ฉันลองใช้คำสั่งตามที่แสดงในโค้ดของฉัน แต่ฉันไม่เข้าใจว่าทำไมมันถึงทำงานไม่ถูกต้อง เพราะเมื่อฉันป้อนตัวเลขที่แตกต่างออกไป ระบบจะตรวจจับข้อยกเว้นและพิมพ์บนคอนโซล System.out.println( ) แต่โปรแกรมจะยุติลงเมื่อสิ่งนี้เกิดขึ้น
ฉันต้องการลองจับเพียงเพื่อให้ได้ข้อยกเว้นของการป้อนไม่ใช่ตัวเลขโดยไม่ต้องยุติโปรแกรมทุกครั้งที่จับข้อยกเว้น ฉันจะแก้ไขปัญหานี้ได้อย่างไร?
ขอบคุณมาก ๆ สำหรับความช่วยเหลือของคุณ!
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //Creates Scanner object to read from keyboard
String playAgain = ""; //if == y, game restarts
try {
do {
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
//System.out.println(theNumber); //Uncoment this in case we want to know the number (for testing).
int guess = 0; //Number entered by the player
int count = 0; //Number of tries of guessing the number
while(guess != theNumber){
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); //Reads the number typed on the keyboard by the player
count++; //Plus 1 every time a number is entered
System.out.println("You entered " + guess +".");
if(guess < theNumber) { //If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if(guess > theNumber) { //If number entered is bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { //If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
}
//Once guess == theNumber
System.out.println("Number of tries: " + count);
System.out.println("Play again? (y/n)");
playAgain = scan.next(); //Reads the String entered from keyboard by the player
}
while(playAgain.equalsIgnoreCase("y")); //If player enters y, start again.
//Otherwise
System.out.println("Thank you for playing! Goodbye :)");
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
}
scan.close(); //Close scanner
} //Close main
} //Close class
catch
ของคุณ คุณกำลังปิดเครื่องสแกนและกลับมาจากหลัก ดังนั้นคุณคาดหวังอะไร - person tkausl   schedule 01.12.2017