จะให้ผู้ใช้ป้อนตัวเลขเพื่อออกจากลูปได้อย่างไร?

ฉันกำลังพยายามให้ผู้ใช้ป้อนตัวเลขระหว่าง 0 ถึง 10 โดยไม่จำกัดจำนวนครั้งจนกว่าพวกเขาต้องการหยุด พวกเขาหยุดด้วยการป้อนค่า -1 จนถึงตอนนี้ ฉันสามารถสร้างสิ่งที่เกิดขึ้นได้เมื่อพวกเขาป้อนค่าที่ถูกต้อง แต่เมื่อพวกเขาป้อน -1 (ซึ่งเป็นค่าที่ไม่ถูกต้องใน while loop) โปรแกรมจะรู้ว่ามันไม่ถูกต้อง สิ่งที่ฉันกำลังมองหาคือให้โปรแกรมยกเว้น -1 สำหรับอินพุตที่ไม่ถูกต้องที่เป็นไปได้ และเพื่อให้โปรแกรมหยุดขออินพุตเพิ่มเติม นี่คือรหัสของฉันจนถึงตอนนี้:

    int userInput=0;
    System.out.println("Please enter numbers ranging from 0 to 10 (all inclusive).");
    System.out.println("When you want to stop, type and enter -1.");


    while (userInput <= 10 && userInput >= 0)
    {
        userInput=Integer.parseInt(br.readLine());

        while (userInput > 10|| userInput < 0)
        {
            System.out.println("That number is not in between 0 and 10. Please enter a correct number.");
            userInput=Integer.parseInt(br.readLine());
        }
        sum=sum+userInput;
        freq++;
    }
    while (userInput == -1)
    {
        System.out.println("You have chosen to stop inputing numbers.");
    }

ขออภัยสำหรับความเข้าใจที่จำกัดของฉัน :/


person r2d2    schedule 07.11.2015    source แหล่งที่มา


คำตอบ (1)


ฉันขอแนะนำให้คุณพยายามทำ while loop มากเกินไป ตามที่เขียนไว้ คุณจะไม่มีวันออกจากครั้งแรก หากคุณป้อนตัวเลขระหว่าง 0 ถึง 10 ระบบจะย้อนกลับและถามอีกครั้ง หากคุณใส่อย่างอื่นนอกเหนือจากนั้น คุณจะเข้าสู่ while ที่ซ้อนกัน และมันจะถามหาตัวเลขอีกครั้ง คิดถึงกระแสและสิ่งที่คุณต้องการให้มันทำ ต่อไปนี้คือโครงร่างสั้นๆ ของวิธีหนึ่งที่จะดำเนินการได้:

System.out.println("Please enter numbers ranging from 0 to 10 (all inclusive).");
System.out.println("When you want to stop, type and enter -1.");
keepgoing = true;
while(keepgoing) {
    userInput=Integer.parseInt(br.readLine());
    if((userInput <= 10 && userInput >= 0) {
        sum=sum+userInput;
        freq++;
    }
    else if(userInput == -1) {
        System.out.println("You have chosen to stop inputing numbers.");
        keepgoing = false;
    }
    else {
        System.out.println("That number is not in between 0 and 10. Please enter a correct number.");
    }
}

อย่างน้อยฉันก็คิดว่ามันไปถึงที่นั่น มีหลายวิธีในการควบคุมการไหลของโค้ดของคุณ เป็นการดีที่จะรู้ว่าเมื่อใดควรใช้อันไหน

person emd    schedule 07.11.2015