2016-09-23 102 views
1

我不得不編寫一個程序,其中返回讀取的正數的總和,並將讀取用戶的輸入,直到輸入零。返回正數的總和

我到目前爲止沒有計算輸入正數的總和,我需要一些幫助。

這是我到目前爲止有:

readAndSumPositives()(注意到你給出的掃描儀,不使用System.in) - 從用戶讀取,直到給出0,並返回正數的總和讀。

實例:

♦用戶輸入:0 =>返回0

♦用戶輸入1 2 3 0 =>返回6(1 + 2 + 3)

♦用戶輸入1 - 2 3 0 =>返回6(1 + 3,跳過-2因爲它是負的)

public static int readAndSumPositives(Scanner in,PrintStream out) 
{ 
    int input; 
    int count; 
    int sum; 
    int total; 

    sum = 0; 
    count =0; 
    total = sum+count; 

     out.println("Please enter a number"); 
     input=in.nextInt(); 
    while(input != 0 && input != -2 && input != -3 && input != -4) { 
     sum += input; 
     count++; 
     out.println("Enter your next positive number"); 
     input=in.nextInt(); 
    } 

    if (input == 0) { 
     return sum; 
    } else return input; 
} 

這裏是正在執行的代碼,當我在GitBash

運行該方法
private static int readAndSumPositivesFrom(String input) { 

    ByteArrayOutputStream out_bs = new ByteArrayOutputStream(); 
    PrintStream out=new PrintStream(out_bs); 

    Scanner in_s = new Scanner(new ByteArrayInputStream(input.getBytes())); 
    int ans = Assignment5.readAndSumPositives(in_s,out); 
    in_s.close(); 
    return ans; 
} 

@Grade(points = 20) 
@Test 
public void testReadAndSumPositives() {  
    Assert.assertEquals(30, readAndSumPositivesFrom("10 20 0 ")); 
    Assert.assertEquals(20, readAndSumPositivesFrom("10 -20 10 0 ")); 
    Assert.assertEquals(10, readAndSumPositivesFrom("1 2 -2 3 -3 4 -4 0 ")); 
} 

任何幫助被讚賞和點將被授予!

在此先感謝。

+1

*我到目前爲止沒有執行...下面是正在執行的代碼... *這個問題有點混亂。 – shmosel

+0

我的意思是它沒有計算輸入正數的總和。 – rls1982

+0

你的意見是什麼?輸出是什麼?預期產出是多少? – shmosel

回答

1

您正在返回錯誤的值。當第一個輸入是0sum時,您應該返回input。你做的恰恰相反。另外,如果用戶首先輸入一個正數(或者更確切地說是一個語法),那麼將第一個輸入移到循環外,然後在循環中檢查它並獲取循環中的下一個輸入,將導致邏輯錯誤錯誤,因爲input未在循環外初始化)。處理循環中的所有內容並檢查你要返回的內容。

while(true){ //infinite loop 
    out.println("Enter positive number to add, 0 to stop."); 
    input = in.nextInt(); 
    if(input == 0) 
     break; 
    if(input > 0) 
     sum+= input; 
} 
return sum; 
+0

工作正常!非常感謝你! – rls1982

-1
while(input != 0 && input != -2 && input != -3 && input != -4) 
//instead of above logic,use logic mentioned below.... 

int sum=0; 
while(input!=0) 
{ 
    if(input>0) 
    sum+=input; 
    out.println("Enter your next positive number"); 
    input=in.nextInt(); 
    //What is the purpose of using "count"? 
} 
return sum; 
+0

「count」的目的僅僅是計算添加到「sum」的整數數量,儘管'count'的** _值從不使用_ **。 – progyammer