nextInt()
方法是Java中Scanner
類的一個方法,用于從輸入流中讀取下一個整數(shù)
nextInt()
方法。例如,創(chuàng)建一個簡單的程序,要求用戶輸入兩個整數(shù)并計算它們的和。import java.util.Scanner;
public class SumOfTwoIntegers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first integer: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second integer: ");
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("The sum of the two integers is: " + sum);
}
}
nextInt()
方法。例如,假設你有一個包含整數(shù)的文本文件,你需要計算這些整數(shù)的總和。import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SumOfIntegersFromFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(new File("integers.txt"));
int sum = 0;
while (scanner.hasNextInt()) {
sum += scanner.nextInt();
}
System.out.println("The sum of the integers in the file is: " + sum);
}
}
nextInt()
方法。例如,創(chuàng)建一個程序,要求用戶輸入一系列整數(shù),并計算它們的總和。import java.util.Scanner;
public class SumOfMultipleIntegers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
System.out.println("Enter integers (enter -1 to stop):");
while (true) {
int num = scanner.nextInt();
if (num == -1) {
break;
}
sum += num;
}
System.out.println("The sum of the integers is: " + sum);
}
}
總之,nextInt()
方法在循環(huán)中的使用場景非常廣泛,可以用于讀取用戶輸入、文件中的整數(shù)以及在循環(huán)中累加整數(shù)。