英文:
(Java) Advise on loops in program
问题
以下是翻译好的内容:
如何编写程序从用户输入中读取5个整数,并计算其中有多少个是正数?
这是我的代码,但它与示例运行结果不符。
int count = 0;
System.out.print("输入5个整数:");
for (int i = 0; i < 5; i++) {
Scanner sc = new Scanner(System.in);
int integer = sc.nextInt();
if (integer > 0) {
count++;
}
}
System.out.println("计数 = " + count);
英文:
How do I write a program to read 5 integers from user input and count how many of them are positive?
Here is my code but it doesn't match the sample run.
int count = 0;
System.out.print("Enter 5 integers: ");
for (int i = 0; i < 5; i++) {
Scanner sc = new Scanner(System.in);
int integer = sc.nextInt();
if (integer > 0) {
count++;
}
}
System.out.println("Count = " + count);
答案1
得分: 0
在你的情况下,在你的代码中当你输入这些数字时,应该用换行符作为分隔,例如:输入 1 换行 5 换行 ...,如果你想使用空格作为分隔,像这样 1 2 0 15 ...,使用我的代码,我认为我不确定在循环内部创建扫描器是否明智,你可以创建一个扫描器并读取一行,然后找到下一个整数,然后创建另一个扫描器,它不会记住上一行,所以你不能使用空格作为分隔。
System.out.print("输入5个整数:");
int count = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
int integer = sc.nextInt();
System.out.println(integer);
if (integer > 0) {
count++;
}
}
sc.close();
System.out.println("数量 = " + count);
英文:
in your case in your code when u enter the numbers you should enter them with enter separator, example : 1 enter 5 enter ..., if you want to use space separator 1 2 0 15... use my code, I think im not sur creating the scanner inside the loop create a scanner and read one line find the next int then you create another scanner witch not remember the previous line so you cant use space separator.
System.out.print("Enter 5 integers: ");
int count = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
int integer = sc.nextInt();
System.out.println(integer);
if (integer > 0) {
count++;
}
}
sc.close();
System.out.println("Count = " + count);
答案2
得分: -6
如果(整数 % 2 == 0){
计数++;
}
在这里:)
从开始阅读一些基础知识,因为稍后会变得困难。
英文:
if (integer % 2 == 0){
count++;
}
Here you are
Read some fundamentals at start because later you'll have hard
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论