Odd and Even Numbers [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

This question already has an answer here:

How can I display all the evens on one line and all the odds on the next line? need to display 25 integers.

public class OddsOrEvens {     public static void main(String[] args)     {         int[] numbers = new int[25];          System.out.print ("EVENS & ODDS");          for(int i=0; i < 25; i++)         {             numbers [i]  =  (int) (Math.random()*99) + 1;             if(numbers[i]%2 == 0)                 System.out.println(numbers[i] +" " );             else                 System.out.println(numbers[i] +" " );          }      } } 

回答1:

Instead of printing each number immediately, consider building up two strings (the first made up of the evens, and the second the odds). Then print the result strings when you're done. This should require just one loop.



回答2:

In your providing code you print every number at time when it processed.if you want to print in one line so one possible solution is that you have store numbers in some array, or a string instead of display the number. So in your code this line must change

System.out.println(numbers[i] +" ");

like this (if you want to store them in string variable)

even += numbers[i] +" ";

and later when loops end you can print out both line one by one. Hope this will help you

//Snippet  if(numbers[i]%2 == 0)     even += numbers[i] +" "; else     odd += numbers[i] +" "; //after loops ends  System.out.println(even); System.out.println(odd);


回答3:

Just save all the evens in one array and all the odds in another and then print them seperately.



回答4:

Well right now you are printing them all individually. what you could do is before the for loop declare a String for the odds and a String for the evens. and initialize them to "". then in the for loop instead of printing, just add the numbers[i] to the string and print them outside of the for loop



回答5:

Alternatively ...

Read the javadoc for PrintStream, 'cos System.out is a PrintStream. Look at the different print methods available.



回答6:

Create a string to hold them and just display them at once at the end:

public class OddsOrEvens {     public static void main(String[] args)     {         int[] numbers = new int[25];           String evens = "";         String odds = "";          System.out.print ("EVENS & ODDS");          for(int i = 0; i < 25; i++)         {             numbers [i]  =  (int) (Math.random() * 99) + 1;             if(numbers[i] % 2 == 0)                 evens += numbers[i] + " "; // save it to evens string             else                 odds += numbers[i] + " "; // save it to odds string          }           // now print them          System.out.println("Evens: " + evens);          System.out.println("Odds: " + odds);      } } 


转载请标明出处:Odd and Even Numbers [duplicate]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!