2016-11-24 210 views
0

我應該寫一個要求輸入姓名的代碼,要求輸入1到10之間的數字,然後從1輸入用戶輸入的數字,除非每個第三個數字應該是用戶輸入的姓名該計劃的開始。我的代碼符合這一目的。下一步是使用循環打印所有從2到用戶號碼的偶數。我不知道如何在代碼中包含這些信息,甚至是什麼樣的循環。有人可以解釋如何正確包含這個嗎?這是目前的代碼。打印偶數的循環?

import java.util.Scanner; 

public class NewClass1 { 
    public static void main(String[] args) { 

     int number; 

     Scanner scan = new Scanner(System.in); 
     System.out.print("Enter your name: "); 
     String name = scan.nextLine(); 

     System.out.print("Please enter a number between 1 and 10: "); 
     number = scan.nextInt(); 

     //asks for a number between one and ten until I get number within that range, 
     while (number < 1 || number > 10) { 
      System.out.print("No, between 1 and 10: "); 
      number = scan.nextInt(); 
     } 

     for (int i = 1; i <= number; i++) { 
      if (i % 3 == 0) { 
       System.out.print(name + " "); 
      } else { 
       System.out.print(i + " "); 
      } 
     } 
    } 
} 
+0

所以你需要一個循環,開始於打印和每秒數。你有什麼麻煩?它基本上只是把價值和添加一個打印。 –

+0

使用一個類似於你所擁有的循環,除非'i%2 == 0'什麼都不打印,也就是說,省去'if'語句的'else'部分。 –

回答

0

下面的代碼,供您參考:

public class NewClass1 { 
    public static void main(String[] args) { 
     int number; 
     Scanner scan = new Scanner(System.in); 
     System.out.print("Enter your name: "); 
     String name = scan.nextLine(); 

     System.out.print("Please enter a number between 1 and 10: "); 
     number = scan.nextInt(); 

    //asks for a number between one and ten until I get number within that range, 
     while (number < 1 || number > 10) { 
      System.out.print("No, between 1 and 10: "); 
      number = scan.nextInt(); 
     } 

    for (int i = 1; i <= number; i++) { 
     if (i % 3 == 0) { 
      System.out.print(name + " "); 
     }else { 
      System.out.print(i + " "); 
     } 
    } 
    System.out.println(); 
    for(int i =2; i<=number; i+=2) 
     System.out.print(i + " "); 
    } 
} 
1

運行一個循環,每個偶數打印是沒有什麼不同,然後運行一個循環,每第三個數字打印。只需使用% 2,而不是% 3

for (int i = 2; i <= number; i++) { 
    if (i % 2 = 0) { 
     System.out.print(i + " "); 
    } 
} 

這可以被改寫,而無需使用%可言:

for (int i = 2; i <= number; i += 2) { 
    System.out.print(i + " "); 
} 
0

這是一個循環,由偶數上升。

for(int i=2;i<number;i+=2) 
{ 
    System.out.println(i); 
} 
0
public static void main(String[]p){ 
    int limit=20; 
    for(int i=2; i<=limit; i+=2) 
    { 
     System.out.println(i); 
    } 
} 
-1
for (int i = 2; i <= number; i++) { 
    if (i % 2 = 0) { 
     System.out.print(i + " "); 
    } 
} 

上面是代碼。

+0

嘗試添加一些關於您的代碼的解釋以豐富您的答案。 – zuazo

+1

'='或'=='? –

+0

使用'=='@Tahir –

0
for (int i = 2; i <= number; i++) { 
    if (i % 2 == 0) { 
     System.out.print(i + " "); 
    } 
}