Java是一種高級編程語言,可以用來計算整數和負數的個數。以下是一個簡單的Java程序來計算整數和負數的個數。
import java.util.Scanner; public class CountIntegersAndNegatives { public static void main(String[] args) { Scanner input = new Scanner(System.in); int positives = 0; int negatives = 0; int count = 0; double total = 0; System.out.print("Enter an integer, the input ends if it is 0: "); int number = input.nextInt(); if (number == 0) { System.out.println("No numbers are entered except 0"); System.exit(1); } while (number != 0) { if (number >0) positives++; else negatives++; total += number; count++; number = input.nextInt(); } double average = total / count; System.out.println( "The number of positives is " + positives + "\nThe number of negatives is " + negatives + "\nThe total is " + total + "\nThe average is " + average); } }
在這個程序中,我們使用Scanner類從控制臺讀取整數,并使用while循環根據輸入的數字進行計算。如果輸入的數字是正數,則增加計數器“positives”的值,如果輸入的數字是負數,則增加計數器“negatives”的值。最后輸出計數器的值和平均值。