JustAnotherCoder
JustAnotherCoder

Reputation: 17

Even-indexed and odd-indexed - Java

I am trying to write a code for a program which:

1. Asks the number of words which you want to enter.

2. Takes the words as the input and for each word, displays the characters at even positions and the characters at odd positions.[0 is considered as an even position]

So I wrote this code but it shows an error which says "Array cannot be resolved to a variable". I am not able to figure out where I have gone wrong.

import java.io.*;
import java.util.*;

public class Trying4 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter the number of words: ");

        int T = in.nextInt();

        for(int m = 0; m<T; m++) {
            String S = in.nextLine();
            int N = S.length();
            char array[] = new char[N];
            for(int n = 0; n<N; n++) {
                array[n] = S.charAt(n+1);
            }
            display(N);
        }
    }

    public static void display(int N) {
        for(int i = 0; i<N; i = i + 2) {
            System.out.print(array[i]);
        }

        System.out.print(" ");

        for(int j = 1; j<N; j = j + 2) {
            System.out.print(array[j]);
        }
    }
}

Upvotes: 0

Views: 2928

Answers (7)

Rajalakshmi.S
Rajalakshmi.S

Reputation: 1

import java.io.*;
import java.util.*;
public class Solution {
 private static void ex(String S) {
  char c[] = S.toCharArray();
  int i, j;
  for (i = 0; i < c.length; i++) {
   System.out.print(c[i]);
   i += 1;
  }
  for (j = 1; j < c.length; j++) {
   System.out.print(c[j]);
   j += 1;
  }
 }
 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  int T = scan.nextInt();
  while (hasNext()) {
   for (int m = 0; m <= = T; m++) {
    String S = scan.next();
    ex(S);
    System.out.println();
   }
  }
 }
}

Upvotes: 0

LowLevel
LowLevel

Reputation: 1095

If I may touch your code, because people mostly get frustrated when touching the code.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int wordCount = getInt(sc, "Enter the number of words: ");
    int wordIndex = 1; // Just to type a message "Word 1, word 2, etc."
    sc.nextLine();
    while (wordCount > 0) {
        System.out.printf("Type word %s: ", wordIndex);
        String word = sc.nextLine();
        List<Character> oddPosChars = new ArrayList<>();
        List<Character> evenPosChars = new ArrayList<>();
        for (int i = 0; i < word.length(); i++) {
            if (i % 2 == 0) {
                evenPosChars.add(word.charAt(i));
            } else {
                oddPosChars.add(word.charAt(i));
            }
        }
        print(evenPosChars, "Even Characters: ");
        print(oddPosChars, "Odd Characters: ");
        wordCount--;
        wordIndex++;
    }
}

static int getInt(Scanner sc, String message) {
    System.out.print(message);
    if (sc.hasNextInt()) {
        return sc.nextInt();
    }
    sc.next();
    System.out.println("Wrong input. Try again.");
    return getInt(sc, message);
}

static void print(List<Character> characters, String message) {
    System.out.print(message);
    characters.stream().forEach(System.out::print);
    System.out.println();
}

Or if you're sure you want to use arrays:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int wordCount = getInt(sc, "Enter the number of words: ");
    int wordIndex = 1; // Just to type a message "Word 1, word 2, etc."
    sc.nextLine();
    while (wordCount > 0) {
        System.out.printf("Type word %s: ", wordIndex);
        String word = sc.nextLine();
        char[] evenPosChars = new char[word.length() - (word.length() / 2)];
        char[] oddPosChars = new char[word.length() / 2];
        for (int i = 0; i < word.length(); i++) {
            if (i % 2 == 0) {
                evenPosChars[i / 2] = word.charAt(i);
            } else {
                oddPosChars[(i - 1) / 2] = word.charAt(i);
            }
        }
        print(evenPosChars, "Even Characters: ");
        print(oddPosChars, "Odd Characters: ");
        wordCount--;
        wordIndex++;
    }
}

static int getInt(Scanner sc, String message) {
    System.out.print(message);
    if (sc.hasNextInt()) {
        return sc.nextInt();
    }
    sc.next();
    System.out.println("Wrong input. Try again.");
    return getInt(sc, message);
}

static void print(char[] characters, String message) {
    System.out.print(message);
    for (char character : characters) {
        System.out.print(character);
    }
    System.out.println();
}

Upvotes: 0

castletheperson
castletheperson

Reputation: 33496

There error is being produced because array is being using in display which is outside of the scope you declared it in.

To fix that, you can either declare array as an instance variable (outside of any methods), or pass the array as a parameter to display.

Also, to get a character array from the string, use S.toCharArray().

import java.io.*;
import java.util.*;

public class Trying4 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of words: ");
        int numWords = in.nextInt();
        in.nextLine(); // consume the new-line character after the number
        for(int i = 0; i < numWords; i++) {
            char[] word = in.nextLine().toCharArray();
            display(word);
        }
    }
    public static void display(char[] word) {
        for(int i = 0; i < word.length; i += 2) {
            System.out.print(word[i]);
        }
        System.out.print(" ");
        for(int i = 1; i < word.length; j += 2) {
            System.out.print(word[i]);
        }
        System.out.println();
    }
}

Upvotes: 0

Sorin J
Sorin J

Reputation: 652

There are many things wrong with your code, starting from violating naming conventions and code identation rules to compile time errors (array variable used out of the scope/block it was declared) to runtime errors (wrong index passed at chatAt()). Even if that code was running ok, any experienced developer would reject it instantly.

I've pasted below a cleaner working version (still I wouldn't implement it in this way (no need for that array, a String object would be enough), but it is the closest to what you've had originally) :

import java.io.*;
import java.util.*;

public class Trying4 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of words: ");
        int nrWords = Integer.parseInt(scanner.nextLine());

        for (int counter = 0; counter < nrWords; counter++) {
            System.out.print("Word[" + counter + "] : ");
            String word = scanner.nextLine();
            int length = word.length();
            char array[] = new char[length];
            for (int i = 0; i < length; i++) {
                array[i] = word.charAt(i);
            }
            display(length, array);
        }
    }

    public static void display(int N, char[] array) {
        System.out.print("Result EVEN : ");

        for (int i = 0; i < N; i = i + 2) {
            System.out.print(array[i]);
        }

        System.out.print("\nResult ODD : ");

        for (int j = 1; j < N; j = j + 2) {
            System.out.print(array[j]);
        }
        System.out.println("");
    }
}

Upvotes: 1

Joey
Joey

Reputation: 1370

You need to pass the array to the display() function.

import java.io.*;
import java.util.*;

public class Trying4 {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    System.out.println("Enter the number of words: ");

    int T = in.nextInt();

    for(int m = 0; m<T; m++)
        {
        String S = in.nextLine();
        int N = S.length();
        char array[] = new char[N];
        for(int n = 0; n<N; n++)
            {
            array[n] = S.charAt(n);
        }
        display(N, array);
        }
    }

public static void display(int N, char[] array){

    for(int i = 0; i<N; i = i + 2)
        {
          System.out.print(array[i]);
        }

    System.out.print(" ");

    for(int j = 1; j<N; j = j + 2)
        {
        System.out.print(array[j]);
        }
}
}

Upvotes: 0

Ethan Williams
Ethan Williams

Reputation: 88

Just a little tip to tidy up the code too, there's a built in method called toCharArray() whose name is self explanatory and eliminates that loop you're using. char array[] = in.NextLine().toCharArray();

Upvotes: 0

Vladimir Vagaytsev
Vladimir Vagaytsev

Reputation: 2891

It fails with compile-time error.

You need to change your method public static void display(int N) to public static void display(char[] array, int N) and pass it the array inside your main method: display(array, N);

It it your only problem or do you have any other issues?

Upvotes: 0

Related Questions