简体   繁体   English

如何将这两个while语句合并为一个?

[英]How do I combine these two while statements into one?

I have two while loops where one is taking the odd numbers between 50 to 100 and the other is taking the even numbers from the same between 50 to 100. It is printing out well and it works but my professor wants me to transform it into one while loop instead of two. 我有两个while循环,其中一个正在取50到100之间的奇数,另一个正在从50到100之间的偶数中取偶数。它可以很好地打印出来并且可以工作,但是我的教授希望我将其转换为一个while循环而不是两个。 I am having trouble with it because I am using the print statement before in order so it fits into when the numbers go in. 我遇到了麻烦,因为我以前是按顺序使用print语句的,所以它适合输入数字时使用。

 int e = 50;
 int o = 51;
 System.out.print("Even numbers between 50 and 100: 50,");
 while (e <= 98){
     e += 2;
     if (e%2 == 0){
        System.out.print(e + ",");
     }
 }
 System.out.print("\nOdd numbers between 50 and 100: 51,");
 while (o <= 97){
     o+= 2;

     if (e%1 == 0) { 
         System.out.print(o + ",");
     }
}


Even numbers between 50 and 100: 50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,
Odd numbers between 50 and 100: 51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,

The output looks like this right now, but I need to be able to do it with just one loop instead 现在的输出看起来像这样,但是我需要能够只用一个循环来完成它

If you only want one while loop, and separate lines, you should build your strings and print them afterwards. 如果只需要一个while循环和单独的行,则应构建字符串并在以后打印它们。 Something like: 就像是:

StringBuilder odds = new StringBuilder();
StringBuilder evens = new StringBuilder();
i = 50;
while(i<100) {
    if(i%2 == 1) {
        odds.append(i).append(",");
    }
    else {
        evens.append(i).append(",");
    }
    i++;
}
// remember that odds and evens now probably ends with a ','which you should remove
odds.removeCharAt(odds.size());
evens.removeCharAt(evens.size());
// or do something like the following:
//odds.append(" and nothing more!");
//evens.append(" and nothing more!");

System.out.println("Odd numbers are: ");
System.out.println(odds);
System.out.println("Even numbers are" ");
System.out.println(evens)

Try to increment a counter variable by 1 in each step and use an if statement to check the modulus (%). 尝试在每个步骤中将计数器变量增加1,然后使用if语句检查模数(%)。 If it equals 0, then the number is even; 如果等于0,则数字为偶数;否则为0。 if it equals 1, then the number is odd. 如果等于1,则数字为奇数。 For printing the separately, you can use two lists or arrays. 要单独打印,可以使用两个列表或数组。

int count=50;
StringBuilder odds = new StringBuilder();
StringBuilder evens = new StringBuilder();

while(count<=100)
{
if(count%2==0) // here, the number is even, append this number to even string
   evens.append(count).append(",");

else // here, the number is odd, append this number to odds string
   odds.append(count).append(",");
count++;
}

// when everything is done, print the strings
// before doing that, you should remove the last comma at the end of these Strings. 
// Otherwise, you will have something like this: 93,95,97,

evens.setLength(evens.length() - 1); // to remove the comma at the end
odds.setLength(odds.length() - 1); // to remove the comma at the end

System.out.println("The even numbers are: " + evens.toString());
System.out.println("The odd numbers are: " + odds.toString());

It is much more efficient to use a StringBuilder rather than using += kind of appending for String s. 使用StringBuilder而不是使用+=类型的String效率要高得多。 Take a look at this link: 看一下这个链接:

https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

You can use single while loop like this for printing odd and even number. 您可以像这样使用单while循环来打印奇数和偶数。

int e = 50;
    while (e <= 98)
    {       
        if (e%2 == 0)
        {
            System.out.println("even :"+e);
        }
        else
        {
            System.out.println("odd :"+e);
        }
        e++;
    }

Just create 2 string output variables and fill them in the loop based on condition 只需创建2个字符串输出变量,然后根据条件将其填充到循环中

if (i%2==1)
  odd_output = odd_output + "," + i.toString 
else
  even_output = even_output + "," + i.toString 

(I might be wrong in Java syntax) (我在Java语法中可能是错误的)

And then just print both resulting strings with any additional info you like 然后只需打印两个结果字符串以及您喜欢的任何其他信息

Here You don't need to maintain Any separate Arrays Or Strings , but a complex conditions 在这里,您不需要维护任何单独的ArraysStrings ,而是需要复杂的条件

public class EvenOddTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int num = 50;
        System.out.println("Even numbers between 50 and 100: ");
        while (num < 100){
            if (num%2 == 0){
                System.out.print(num + ",");
            } else {
                System.out.print(num + ",");
            }
            if( num == 98 ) {
                num = 49;
                System.out.println();
                System.out.println("Odd numbers between 50 and 100: ");
            }
            num += 2;
        }
    }
}

I know it doesn't answer directly the question (although the output is the same) but in 2016 when one want to print a sequence of numbers we do something like that: 我知道它并不能直接回答问题(尽管输出是相同的),但是在2016年,当一个人想要打印一系列数字时,我们会做类似的事情:

public static void main(String[] args) {
    int[] evenNumbers = IntStream.rangeClosed(50, 100).filter(i -> i % 2 == 0).toArray();
    int[] oddNumbers = IntStream.rangeClosed(50, 100).filter(i -> i % 2 != 0).toArray();

    System.out.println("Even numbers between 50 and 100: " + Arrays.toString(evenNumbers));
    System.out.println("Odd numbers between 50 and 100: " + Arrays.toString(oddNumbers));
}

If the goal of your exercice is to learn how to use a while loop, my solution is useless. 如果您的运动目标是学习如何使用while循环,那么我的解决方案将毫无用处。 However if your goal is to practice Java as it should be nowadays, I think if reaches the goal. 但是,如果您的目标是像现在这样练习Java,那么我认为是否可以达到目标。

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

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