可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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); } }