简体   繁体   English

Java循环,打印出奇数

[英]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.这是解决问题的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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