'Correcting my output to match the expected

I am fairly new to coding and have been trying to do this assignment for hours. What I am trying to do is have my output look like the expected output but can't seem to figure out what I am doing wrong. Could someone please explain to me what it is I am doing wrong and guide me to the correct answer? Thank You!

import java.io.*;
import java.util.*;
 
public class ShowCharacter {
 
    public static void showCharacter(String s, int index) {
        System.out.println("The letter at position " + index + " is " + s.charAt(index));
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str;
        int index;
        System.out.println("Please enter a String");
        str = in.nextLine();
        System.out.println("Please enter the character's position");

        index = in.nextInt();
        while (true) {
            if(index >= 0 && index < str.length()) {
                break;
            }
            else{
                System.out.println("Invalid Position. Enter a valid position");
            }
        }
        showCharacter(str, index);
    }
}

Input: This is a sentence. -7 -8 0

My output: Please enter a String

Please enter the character's position

Invalid Position. Enter a valid position

Invalid Position. Enter a valid position

Invalid Position. Enter a valid position

Invalid Position. Enter a valid position

Invalid Position. Enter a valid position

Invalid Position. Enter a valid position

Invalid Position. Enter a valid position

Invalid Position. Enter a valid position

etc. etc.

Expected output:

Please enter a String

Please enter the character's position

Invalid Position. Enter a valid position

Invalid Position. Enter a valid position

The letter at position 0 is T



Solution 1:[1]

there is a simple solution for that. First of all, your while loop runs the whole time on the same number (e.g -7) but you never change it, so it will always give you your error message.

You can solve this by reassigning index to a new input like this:

while (true) {
  if(index >= 0 && index < str.length()) {
    break;
  } else {
    System.out.println("Invalid Position. Enter a valid position");
    index = in.nextInt();
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CyberHD1811