簡體   English   中英

if和else語句不起作用java

[英]if and else statements not working java

您好,我嘗試輸入1到10之間的整數。如果用戶不這樣做,則希望程序再次運行。 我相信我需要使用else if語句來調用我的函數,但是我不知道如何在Java中調用函數。

到目前為止,這是我的代碼:

import java.util.Scanner;
public class NumChecker {
     public static void main(String[] args){

         Scanner in = new Scanner(System.in);
         System.out.print("Enter a number between 1 and 10: ");
         int num1 = in.nextInt();
         if (num1 >= 1 && num1 <= 10); {
             System.out.println("Input = " + num1);
             }

         else if {
         ???
         }


     }

}

if-else始終有效。

您在if語句中犯了一個錯誤。

沒有; if

if (num1 >= 1 && num1 <= 10) {//no semicolon
   System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
... 
}  

如果我在if語句的末尾加上分號怎么辦?


如何再次詢問用戶輸入的值是否不在1到10之間?

循環播放,直到獲得所需的內容:)

Scanner sc = new Scanner(System.in);
int num = 0;
while(true)
{
 num = sc.nextInt();
 if(num > 0 && num < 11)
  break;
 System.out.println("Enter a number between 1 and 10");
}
System.out.println(num);

由於您期望的數字介於1到10之間,但是直到獲得有效數字之前,您不知道會得到多少個數字,因此,我建議使用while循環,如下所示:

import java.util.Scanner;
public class NumChecker {
    public static void main(String[] args){

        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number between 1 and 10: ");
        int num1 = in.nextInt();
        while (num1 < 1 || num1 > 10) {
            System.out.print("Invalid number, enter another one: ");
            num1 = in.nextInt();
        }
        System.out.println("Input = " + num1);
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM