Advertisement
Kancho

Zig_Zag_Print

Mar 9th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Arrays_Exercise {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6.  
  7. System.out.print("Enter n: ");
  8. int n = Integer.parseInt(sc.nextLine());
  9.  
  10. String[] numbers = new String[n * 2]; // create String array with n * 2 elements to store the numbers we want to print
  11.  
  12. int userInputIndex = 0; // create int variable to index each number from the pair of numbers
  13. for (int i = 0; i < n; i++) {
  14. System.out.print("Enter two numbers: ");
  15. String[] userInput = sc.nextLine().split(" "); // create new array to store the pairs of numbers from the user's input
  16. if (i % 2 == 0) { // create if condition check whether i is even number
  17. numbers[userInputIndex++] = userInput[0]; // connect userInput array with numbers array
  18. numbers[userInputIndex++] = userInput[1];
  19. } else { // or odd number
  20. numbers[userInputIndex++] = userInput[1];
  21. numbers[userInputIndex++] = userInput[0];
  22. }
  23. }
  24. String firstOutput = " "; // create String array to store the even i numbers
  25. String secondOutput = " "; // create String array to store the odd i numbers
  26.  
  27. for (int i = 0; i < numbers.length; i++) { //read the numbers array
  28. if (i % 2 == 0) {
  29. firstOutput += numbers[i] + " ";
  30.  
  31. } else {
  32. secondOutput += numbers[i] + " ";
  33.  
  34. }
  35. }
  36. System.out.println(firstOutput.trim());
  37. System.out.println(secondOutput.trim());
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement