import java.util.Scanner;
public class CompareStrings {
public static void main(String[] args) {
// prompted user input
Scanner input = new Scanner(System.in);
int firstIndex;
int secondIndex;
System.out.print("Enter First String:"); // prompt user
String stringNumberOne = input.next(); // assigns stringNumberOne to user input
System.out.print("Enter Second String:"); // prompt
String stringNumberTwo = input.next(); // assigns stringNumberTwo to user input
System.out.print("Enter Starting Index for First String:"); // prompt
firstIndex = input.nextInt(); // assigns firstIndex to user input
System.out.print("Enter Starting Index for Second String:"); // prompt
secondIndex = input.nextInt(); // assigns secondIndex to user input
System.out.print("Enter Number of Characters to be Compared:"); // prompt
int numberCompared = input.nextInt(); // assigns numberCompared to user input
boolean results = stringNumberOne.regionMatches(firstIndex,
stringNumberTwo, secondIndex, numberCompared);
if (results)
System.out.println(true);
else
System.out.println(false);
}
}
This is my code. I am trying to use String method regionMatches to compare two strings input by the user. The program should prompt the user to enter two strings, the starting index in the first string, the starting index in the second string, and the number of characters to be compared. The program then should print whether or not the strings are equal (true/false). Ignoring the case of the characters during comparison. I have written the above code and if a single word like "Hello" is entered, I am able to run my program correctly. However, if I write a sentence such as "Hello this is my Java program" I receive an error stating
String:Exeception in thread "main" java.util.InputMismatchException
and then the code will not run. It highlights the portion of my firstIndex = input.nextInt();
code. Any help would be greatly appreciated! Thank you for taking the time to read this post! :)