2016-12-01 62 views
1

所以我試圖編寫一個程序,用戶輸入兩個整數。 根據輸入的第一個數字,程序應該從循環中輸入的第二個整數中減去5。 (所以第一個數字應該規定多少次,它會循環。使用while循環的減法Java

public int getScheme1() { 
    while (Mark >= 20) { 
     System.out.printf((Mark = Mark - 5) + Mark + " "); 
    } 

    for (int Day = 1; Day <= 20; Day++) { 
     System.out.printf("(" + Day + "):" + Mark + " "); 
    } 

    return Mark; 
} 

我所有的代碼確實是打印用戶的第二輸入整20倍。 也對不起即時通訊全新到Java

+1

你是說第一個數字輸入的定義你要多少次從第二個數字中減去5?例如'第一個數字:3''第二個數字:25'會給你輸出'10'。 – Gendarme

+0

假設輸入數字是n1和n2,如果n2需要在n1次減去5,爲什麼不只是'n2 - = n1 * 5'而不是循環? – diufanman

回答

0

基於你所描述的,您正在尋找這樣的事情:

Scanner input = new Scanner(System.in); //create a scanner to get user input 
int a1 = input.nextInt(); //get 2 ints from the user 
int a2 = input.nextInt(); 
for(int i = 0; i < a1; i++) { //loop as many times as a1 specifies 
    a2-=5; //subtract 5 from a2 each time it loops 
} 
System.out.println(a2); 

這樣做的關鍵部分是在for循環,這在下面的工作:

for(variable; condition; increment), 基本上,我寫的for循環說的是:

設置i = 0在開始。如果i符合條件(在這種情況下小於a1),則循環。增量部分當它完成運行的代碼塊被調用,現在讓i更大(在這種情況下1使用++更大)需要注意的另一個重要的事情是,在第一時間循環運行,I = 0

所以例如,如果我想環路10倍,3起始變量,每次遞增5,我會做:

for(int i = 3; i <= 53; i+=5) {}

另外,最後一兩件事:請你看看variable naming conventions,不該變量我們從這樣的帽子開始,他們應該是camelCase

1

您必須在主程序中調用此函數。

public int getScheme1 (int num1, int num2){ 
    for(int i = 1 ; i >= num1 ; i++){ 
     num2 -= 5; 
    } 
    return num2; 
} 

調用它簡單地使用getScheme1(num1,num2);