import java.util.Scanner;
public class linecounter {
public static void main(String[] args) {
System.out.print("Enter a line of integers ");
Scanner chopper = new Scanner(System.in);
int x = chopper.nextInt();
while (chopper.hasNextInt()) {
System.out.println(chopper.nextInt());
}
}
}
我在CS1课程中学习Java的基础知识并有一个快速的问题,在这个代码上,任何人都可以告诉我如何才能记住输入了多少个整数? 谢谢
答案 0 :(得分:3)
,声明:
int count = 0;
然后在你的while循环中使用 计数++;
这将从0开始,每次递增计数
答案 1 :(得分:0)
你可以在while循环中添加一个计数器。
int counter = 0;
while (chopper.hasNextInt()) {
counter++;
System.out.println(chopper.nextInt());
}
System.out.println(counter);
答案 2 :(得分:0)
如果你有整数,双数,你只需要计算整数,你可以使用:
public class linecounter {
public static void main(String[] args) {
System.out.print("Enter a line of integers ");
Scanner chopper = new Scanner(System.in);
int x = chopper.nextInt();
int counter = 0;
while (chopper.hasNextInt()) {
System.out.println(chopper.nextInt());
String myCurrentArg = chopper.nextInt();
if(isInteger(myCurrentArg) ){
counter++;
}
}
System.out.println("The number of integer arguments are: " + counter);
}
public static boolean isInteger(String s) {
return isInteger(s,10);
}
}