我知道這段代碼做了我需要做的工作,但我不禁感到有更多...精煉的方式來獲得相同的結果。請注意,最後幾個輸出僅應顯示如果已經有至少1號(多個)是大於或小於0他們是寫這段代碼的更好方法嗎?
//This program will take an unspecified number of
//integers, determine how many of those integers are
//positive and how many are negative, and finally
//compute the total and average of the integers.
import java.util.Scanner;
public class exampleWork {
public static void main(String[] args) {
//create a scanner
Scanner input = new Scanner(System.in);
//create a variable to hold the positive integers
int pos = 0;
//create a variable to hold the negative integers
int neg = 0;
//create a variable to hold the total number of entries
int total = 0;
//create a variable to hold the average
float avg = 0;
//create a counter variable
int count = 0;
//prompt user to enter integer
System.out.println("Enter an integer, the input ends if it is 0: ");
int usrInput = input.nextInt();
//determine if the number is positive, negative,
//or zero, and either place in relative variables,
//or end the loop.
if (usrInput == 0)
System.out.print("Only zero was entered");
while (usrInput != 0) {
if (usrInput > 0){
pos++;
total += usrInput;
count++;
System.out.println("Enter an integer, the input ends if it is 0: ");
usrInput = input.nextInt();
} if (usrInput < 0){
neg++;
total += usrInput;
count++;
System.out.println("Enter an integer, the input ends if it is 0: ");
usrInput = input.nextInt();
}
}
if (count > 0){
avg = (total/count);
System.out.println("The number of positives is " + pos);
System.out.println("The number of negatives is " + neg);
System.out.println("The total is " + total);
System.out.println("The average is " + avg);
}
}
}
是。您可以... –
忽略關於「創建...」的評論,他們沒有增加任何價值。不要描述你做了什麼,這是代碼應該告訴你的。描述你爲什麼這樣做。 –
我主要是以這種方式製作筆記,因爲這是一個班級作業,但它是一個很好的提示,可以知道如何使用筆記。謝謝。我沒有意識到這一點。 – AceFactor