0

i am working on a problem wherein i have to check if the input entered into the array is between 1 and 10000. if it is true, i have to proceed with the next set of operations. how do i go about with it. please find my code below:

Scanner in =  new Scanner(System.in);
    System.out.println("Enter 10 values between 1 and 10000: " );
    for(int i=0; i<10; i++) {
          if (z[i]>1 && z[i]<10000) {
        z[i] = in.nextInt();
        }
    }

but im not able to check with the "if" statement i've placed there. can you please help me out.

3
  • 2
    Swap asking for input and comparison lines. Commented Jan 11, 2015 at 14:12
  • sorry, i didn't get you, what Commented Jan 11, 2015 at 14:21
  • you can't test if z[i]>1 if there is nothing in z[i]. You should get the input, test if it fits values, and then assign it to the array. Commented Jan 11, 2015 at 16:51

2 Answers 2

3

Save the input to a variable first

int num = in.nextInt();

then validate

if(num>1 && num < 10000) {
   z[i] =num;
}else {
   System.out.printf("Invalid number: %d",num);
}
Sign up to request clarification or add additional context in comments.

1 Comment

while true, more needs to be done (e.g. what if the user types a letter and not a number, or type s 11.33.22
0

You want to use a pattern line the following (pseudocode, since questions like these are often homework and learning based, not find an answer and copy). I want great future programmers!

First the setup:

  1. Initialize a variable to the "What you should enter" message you plan for your user. Why? so if you need to change it, you only have one place to go!
  2. Initialize a variable to any error message(s) that you will detect
  3. Establish the input stream

Now the loop:

Issue the "what you should enter" message
Initialize any needed counters
begin the loop (while counters < value?)
   // use try catch to surround your input and calculations to catch malformed integers etc
   try {
       get candidate data element from input stream
       check for validity
         if success increment count, do other needed work
         if fail, reissue "what you should enter" message or more specific error message
   } catch malformed input {
         reissue "what you shoue enter" message, including error for malformed input
   }
end loop

Note, if you are doing work until some condition occurs (e.g. the user enters QUIT), you use that condition (set to false the first time) as your loop termination test

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.