Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Arrays_Exercise {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter n: ");
- int n = Integer.parseInt(sc.nextLine());
- String[] numbers = new String[n * 2]; // create String array with n * 2 elements to store the numbers we want to print
- int userInputIndex = 0; // create int variable to index each number from the pair of numbers
- for (int i = 0; i < n; i++) {
- System.out.print("Enter two numbers: ");
- String[] userInput = sc.nextLine().split(" "); // create new array to store the pairs of numbers from the user's input
- if (i % 2 == 0) { // create if condition check whether i is even number
- numbers[userInputIndex++] = userInput[0]; // connect userInput array with numbers array
- numbers[userInputIndex++] = userInput[1];
- } else { // or odd number
- numbers[userInputIndex++] = userInput[1];
- numbers[userInputIndex++] = userInput[0];
- }
- }
- String firstOutput = " "; // create String array to store the even i numbers
- String secondOutput = " "; // create String array to store the odd i numbers
- for (int i = 0; i < numbers.length; i++) { //read the numbers array
- if (i % 2 == 0) {
- firstOutput += numbers[i] + " ";
- } else {
- secondOutput += numbers[i] + " ";
- }
- }
- System.out.println(firstOutput.trim());
- System.out.println(secondOutput.trim());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement