要查詢陣列元素的總和,請建立一個空變數。(sum)將其初始化為 0 在迴圈中遍歷每個元素(或從使用者處獲取每個元素)將每個元素新增到 sum 中列印 sum 示例import java.util.Arrays; import java.util.Scanner; public class SumOfElementsOfAnArray { public static void main(String args[]){ System.out.println("Enter the required size of the array :: "); Scanner s = new Scanner(System.in); int size = s.nextInt(); int myArray[] = new int [size]; int sum = 0; System.out.println("Enter the elements of the array one by one "); for(int i=0; i
弗洛伊德三角形,以羅伯特·弗洛伊德的名字命名,是一個直角三角形,它是使用自然數構成的。它從 1 開始,連續選擇序列中的下一個更大的數字。演算法獲取要列印的行數 n。進行 n 次外迴圈 I 以列印行進行內迴圈 J 到 I 列印 K 遞增 K 在每次內迴圈後列印換行符示例import java.util.Scanner; public class FloyidsTriangle { public static void main(String args[]){ int n, i, j, k = 1; System.out.println("Enter the number of lines you need in the FloyidsTriangle"); Scanner sc ... 閱讀更多
java.util.Scanner 類是一個簡單的文字掃描器,可以使用正則表示式解析基本型別和字串。1. 掃描器使用分隔符模式將其輸入分解為標記,預設情況下匹配空格。2. 掃描操作可能會阻塞以等待輸入。3. 掃描器對於多執行緒使用是不安全的,除非使用外部同步。Scanner 類的 nextInt() 方法用於從源讀取整數值。示例import java.util.Scanner; public class ReadingNumbersFromUser { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter a number ::"); int num ... 閱讀更多
Java 中的 * 運算子用於將兩個數字相乘。使用 Scanner 類從使用者處讀取所需的數字,並使用 * 運算子將這兩個整數相乘。示例import java.util.Scanner; public class MultiplicationOfTwoNumbers { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the value of the first number ::"); int a = sc.nextInt(); System.out.println("Enter the value of the first number ::"); int b = sc.nextInt(); int result = a*b; System.out.println("Product of the given two numbers ... 閱讀更多