-2

why does my code fail? It fails on the chatAt function upon the second rotation of the for loop.

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

        int n = Integer.parseInt(scanner.nextLine());
        int sum = 0;

        for (int i = 0; i <n ; i++) {{
            String letter = scanner.nextLine();

            char valueOf = letter.charAt(i);
            int valueto = (int)valueOf;
            sum += valueto;
        }
        }
        System.out.println(sum);

    }
}
Valtar
  • 3
  • 2
  • What inputs did you give it? –  Jan 23 '22 at 14:19
  • 5 , A, b, C, d, E – Valtar Jan 23 '22 at 14:21
  • How is it failing? You need to explain what you are trying to do. Do you really want to read in a line inside the loop? What sum did you expect for your input? – WJS Jan 23 '22 at 14:21
  • Ask yourself: what is the second letter of the string "b"? –  Jan 23 '22 at 14:22
  • Oh I see, because it tries to read additional symbols, when all I needed to do was to read letter.charAt(0) since the position is not chaning, got it, ty vm dratenik – Valtar Jan 23 '22 at 14:24

1 Answers1

1

Your code is getting the character from ith index, which will throw an index out of range error, as i increases continuously throughout the loop.

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        int sum = 0;
        for (int i = 0; i <n ; i++) {{
            String letter = scanner.nextLine();
            // Set charAt 0th index to read the character from the input 
            char valueOf = letter.charAt(0);
            int valueto = (int)valueOf;
            sum += valueto;
        }
        }
        System.out.println(sum);

    }
Khan Asfi Reza
  • 566
  • 5
  • 28