简体   繁体   中英

Java loop , print out odd numbers

Good day, my program is supposed to print out all odd numbers entered in the scanner, which it does but i would like to know how can i compare both inputs, the first number should always be less than the second number upon input. How can i allow the first input to always be less than the second number?

package loopsassign2;
   import java.util.Scanner;
/**
 *
 * @author whitneykenny
 */
public class LoopsAssign2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        
         int start =1;
         int number ;
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Input the first Number");
        
        
        number=scanner.nextInt();
        
        System.out.println("Input the second Number");
          number=scanner.nextInt();
        
       do {
            if((start%2)!=0){
      System.out.print((start + " "));
            }
            start++;
            
       }while (start <= number);
       }
    
}
       
       
    

Maybe by using input validation when you ask for the second number. Also you are assigning the second number to the same variable that you use for the first number so it may be overwritten.

while (number2 < number1)
{
  System.out.println("The second number needs to be greater than the first number")
  System.out.println("Input the second Number");
  number=scanner.nextInt()
}
int num1;
int num2;
boolean outcome = false;
.
.
.
while (outcome!=true) {
    System.out.println("Input the second Number");
    num2=scanner.nextInt();
    if (num2 > num1) {
        outcome = true;
    } else {
        System.out.println("Try again.");
    }
}

This is one way of solving the problem.

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