简体   繁体   中英

(Java) Advise on loops in program

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);

在此处输入图片说明

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);

if (integer % 2 == 0){
    count++;
}

Here you are :)

Read some fundamentals at start because later you'll have hard

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM