2016-09-23 62 views
0

我正在嘗試編寫一個非常基本的代碼,它需要一個數字(通過手動編輯代碼(即不允許掃描程序)完成),然後打印所有數字的倍數一定的最大值(也可以在代碼中手工計算)我的代碼可以用於循環,值等等 - 這只是我們必須包含兩種方法來打印它:一種方法很簡單,每個數字都在一個新線,另一種方式更難 - 每行有6個數字,正確的意圖,由幾個空格分隔。我知道%(x/y/z/a/b/c)f將打印字符串/整數/雙打/等。右對齊基於x/y/z/a/b/c的間距,但我不知道如何在6個數字後自動開始換行。從循環中輸出/打印每行6個數字

import java.util.*; 
public class IncrementMax 
{ 
    public static void main(String[] args) 
    { 
     Scanner sc = new Scanner(System.in); 

     int maxvalue = 200; // these top 2 values have to be adjusted to suit the program to your needs 
     int incvalue = 5; 
     int increment = incvalue; 
     int max = 200; 

     System.out.println("I will print the multiples of " + increment + ", up to " + max + ". Do you want each number on a different line (y/n)?"); 
     String yesno = sc.next(); 

     if (yesno.equalsIgnoreCase("y")) 
     { 
      for(increment=incvalue; increment<(max+incvalue); increment=increment+incvalue) 
       System.out.println(increment); 
     } 
     else if (yesno.equalsIgnoreCase("n")) 
     { 
      for (increment=incvalue; increment<(max+incvalue); increment=increment+incvalue) 
       System.out.print(increment + ". "); 
     } 
     else 
      System.out.print(""); 
    } 
} 

這是我迄今爲止的代碼。

+0

您在需要的,如果條件的for循環,打印每次都打印出來,6號線在一個新行。提示:模數運算符 –

+0

@MichaelMarkidis認爲我已經正確輸入了。 –

回答

0

這是一個相對簡單的使用%運營商:

for (increment = incvalue; increment < max + incvalue; increment += incvalue) { 
    System.out.print(increment); 
    if (increment % (incvalue * 6) == 0) 
     System.out.println(); 
} 
+0

謝謝!這解決了它。但是,我遇到了一些問題,看看它是如何工作的(所以如果需要的話可以適應未來的代碼)。我知道你正在測試的是如果int增量可以被6整除(我假設某種事情只是每6行發生一次),但我沒有看到的是你如何讓這個增量完全被6整除(看作是我現在用其他數字嘗試過它,它仍然有效)。 – Ronan

+0

它的工作原理是'increment'初始化爲'incvalue'。要做任何數字'n',使用'increment%(incvalue * n)'。 –