0

This is my code .. When I am compiling it it says sarr is an undeclared variable...please help me sort this problem out.

import java.util.*;
public class StringPractise2 {
  public static void main() {
    String temp;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the sentence:");
    String s = sc.nextLine();
    s = s.toUpperCase();
    int l = s.length();
    int c; //String sarr[];
    if (s.charAt(l - 1) == '@' || s.charAt(l - 1) == '.') {
      StringTokenizer str = new StringTokenizer(s, "@.");
      c = str.countTokens();
      String sarr[] = new String[c];
      for (int i = 0; i < c; i++)
        sarr[i] = str.nextToken();
      for (int i = 0; i < c; i++) {
        for (int j = i + 1; j < c; j++) {
          if (sarr[i].compareTo(sarr[j]) > 0) {
            temp = sarr[i];
            sarr[i] = sarr[j];
            sarr[j] = temp;
          }
        }
      }
    }
    System.out.println("The original sentence:" + s);
    System.out.println("The array is alphabetical order:");
    for (int i = 0; i < c; i++) {
      System.out.println(sarr[i] + " ");
    }
  }
}
Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • 1
    `sarr` is declared inside the `if` block, but you are trying to use it outside of its scope. – 001 Jul 10 '23 at 15:50
  • `sarr` is declared inside the if-statement, it exist only there, read up on variable scope. And `c` is only declared, it's initialized inside the `if`, there are cases when it might not get initialized, you will get compilation error about it as well. Last, but not least, take care to properly format your code, those errors would be obvious, if the code was formatted correctly. – Chaosfire Jul 10 '23 at 15:52

0 Answers0