简体   繁体   中英

How to use for loop to input 10 numbers and print only the positives?

I'm trying to make a "for" loop in which it asks the user to input 10 numbers and then only print the positives.

Having trouble controlling the amount of inputs. I keep getting infinite inputs until I add a negative number.

import java.util.Scanner;

public class ej1 {
    public static void main(String args[]) {

        int x;

        for (x = 1; x >= 0; ) {
            Scanner input = new Scanner(System.in);
            System.out.print("Type a number: ");
            x = input.nextInt();
        }
    }
}

From a syntax point of view, you've got several problems with this code.

  • The statement for (x = 1; x >= 0; ) will always loop, since x will always be larger than 0, specifically because you're not introducing any kind of condition in which you decrement x .

  • You're redeclaring the scanner over and over again. You should only declare it once, outside of the loop. You can reuse it as many times as you need.

  • You're going to want to use nextLine() after nextInt() to avoid some weird issues with the scanner.

    Alternatively, you could use nextLine() and parse the line with Integer.parseInt .

That said, there are several ways to control this. Using a for loop is one approach, but things get finicky if you want to be sure that you only ever print out ten positive numbers, regardless of how many negative numbers are entered. With that, I propose using a while loop instead:

int i = 0;
Scanner scanner = new Scanner(System.in);
while(i < 10) {
    System.out.print("Enter a value: ");
    int value = scanner.nextInt();
    scanner.nextLine();
    if (value > 0) {
        System.out.println("\nPositive value: " + value);
        i++;
    }
}

If you need to only enter in ten values, then move the increment statement outside of the if statement.

i++;
if (value > 0) {
    System.out.println("\nPositive value: " + value);
}

As a hint: if you wanted to store the positive values for later reference, then you would have to use some sort of data structure to hold them in - like an array.

int[] positiveValues = new int[10];

You'd only ever add values to this particular array if the value read in was positive, and you could print them at the end all at once:

// at the top, import java.util.Arrays
System.out.println(Arrays.toString(positiveValues));

...or with a loop:

for(int i = 0; i < positiveValues.length; i++) {
    System.out.println(positiveValues[i]);
}
Scanner scan = new Scanner(System.in);
int input=-1;
for(int i=0;i<10;i++)
{
 input = sc.nextInt();
if(input>0)
System.out.println(input);
}

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