我不得不編寫一個程序,其中返回讀取的正數的總和,並將讀取用戶的輸入,直到輸入零。返回正數的總和
我到目前爲止沒有計算輸入正數的總和,我需要一些幫助。
這是我到目前爲止有:
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 "));
}
任何幫助被讚賞和點將被授予!
在此先感謝。
*我到目前爲止沒有執行...下面是正在執行的代碼... *這個問題有點混亂。 – shmosel
我的意思是它沒有計算輸入正數的總和。 – rls1982
你的意見是什麼?輸出是什麼?預期產出是多少? – shmosel