Java奇数循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22213387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:21:45  来源:igfitidea点击:

Java Odd Number Loop

javaloops

提问by Javier

I am trying to output the first "x" odds, but I am clueless on how to stop the loop at the number that x is. For example... if you input 6, I want it to show 1, 3, 5, 7, 9, 11. However, my coding does it for all the odds.

我试图输出第一个“x”赔率,但我对如何在 x 的数字处停止循环一无所知。例如...如果您输入 6,我希望它显示 1, 3, 5, 7, 9, 11。但是,我的编码可以解决所有问题。

import java.util.Scanner;


public class OddNumber {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Please input a number.");
    Scanner keyboard = new Scanner(System.in);
    int x = keyboard.nextInt();
    int total = x*x;
    if (x > 0){
        System.out.println("The first 5 odd numbers are...");
    }
    if (x > 0){
        for (int i = 0; i < total; i++){
        if (i % 2 != 0){
            System.out.println(i+"");
        }}
    System.out.println("The total is "+total);
    }

        }


}

采纳答案by Peshal

Something like this should work:

这样的事情应该工作:

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("Please input a number.");
        Scanner keyboard = new Scanner(System.in);
        int x = keyboard.nextInt();
        for(int i =1; i<=x*2; i++) {
            if (i%2!=0) {
                System.out.print(i+", ");
            }
        }
        keyboard.close();
}

回答by newuser

int total = x*2;

instead of

代替

int total = x*x;

回答by mamboking

For you loop you should use:

对于循环,您应该使用:

for (int i=0; i<x; i++) {
    System.out.println((i*2)+1);
}

回答by Dave

This is most efficient (based on the unusual requirements):

这是最有效的(基于不寻常的要求):

var oddNumber = 1;
for (int i=0; i<x; i++) {
     System.out.println(oddNumber);
     oddNumber += 2;
}

回答by BateTech

Change your forloop to:

将您的for循环更改为:

for (int i = 1; i <= x; i++){
    System.out.println(i * 2 - 1);
}

or an alternative:

或替代方案:

for (int i = 1; i < x * 2; i = i + 2){
        System.out.println(i);
}

回答by Joe's Morgue

Your if (i % 2 != 0){

你的 if (i % 2 != 0){

You can address it a few ways.

您可以通过几种方式解决它。

After that, you can:

之后,您可以:

 if (i != x){
    System.out.print(i+", ");
 }

OR, you can:

或者,您可以:

 if (i % 2 && i != x){
    System.out.print(i+", ");
 }

that will do both checks at the same time.

这将同时进行两项检查。

回答by Dima Bors

For odd numbers:

对于奇数:

for(int i=0; i<number; i++)
   {
   i=i+1;

   System.out.println(i);
   }

For even numbers:

对于偶数:

for(int i=1; i<number; i++)
   {
   i=i+1;

   System.out.println(i);
   }