0

My program for the most part runs smoothly. Only incorrect part is the last input for the variable newsub does not work. Rather, the program skips over it and moves on. I tried to comment out the last part but then I was still not allowed to type anything. So apparently eclipse is skipping lines?? I saw a couple of posts, but when I changed the first part from keyboard to input an error was called because they viewed it as a new uncalled variable. Any help will be great! (Also I am fully aware that my program is longer than necessary) Thanks!

import java.util.Scanner;

public class ScannerTest1 {

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

        System.out.print("Enter a long string: ");
        String lin = keyboard.nextLine();

        System.out.print("Enter a substring: ");
        String sub = keyboard.nextLine();

        int leng = lin.length();
        System.out.println("Length of your string: " + leng);

        int leng2 = sub.length();
        System.out.println("Length of your substring: " + leng2);

        int mid = lin.indexOf(sub);

        System.out.println("Starting position of your substring in string: " + lin.indexOf(sub));

        System.out.println(lin.substring(0, mid));
        System.out.println(lin.substring((mid + leng2 + 1), leng));

        System.out.print("Enter a position between 1 and 43: ");
        int pos = keyboard.nextInt();

        System.out.println("The character at position " + pos + " is " + lin.charAt(pos));

        System.out.print("Enter a replacement string: ");
        String newsub = keyboard.nextLine();

        System.out.println("Your new string is: " + lin.substring(0, mid) + newsub + lin.substring((mid + leng2 +1), leng));

        keyboard.close();
    }

}

1 Answers1

0

Do this:

System.out.print("Enter a position between 1 and 43: ");
int pos = keyboard.nextInt();
keyboard.nextLine();

You need to eat up the new line character that is left over. If you don't your last keyboard.nextLine() will and never allow for user input.

This is a side-effect of nextInt() nextDouble() etc...they don't eat up the new line character.

brso05
  • 12,634
  • 1
  • 17
  • 37