My programs throws StringIndexOutOfBoundsException at this segment of code: temp1 = temp.replace('-', temp.charAt(p)); I'm trying to get the index of the same letter (after comparing inputted letter and word) and removing the '-' to show that the user has guessed correctly.** **I've been trying for hours to no avail. I think the problem lies in my loops. Thanks for the answers :) if I violated anything, please forgive me.
run:
-----
Enter a letter:
a
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:
3
at java.lang.String.charAt(String.java:658)
at Hangman.main(Hangman.java:34)
Java Result: 1
import java.util.Scanner;
public class Hangman {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String word = "Sample";
String temp = null;
String temp1 = null;
String letter = null;
int n;
int m=0;
int p = 0;
for (n = 0; n<word.length(); n++){
temp = word.replaceAll(word, "-"); //replaces the String word with "-" and prints
System.out.print(temp);
}
while (m<=5){ //the player can only guess incorrectly 5 times
System.out.println("\nEnter a letter:");
letter = sc.nextLine();
letter.toLowerCase();
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.print(temp1);
}
else {
System.out.print("\nMissed: "+letter); //if not, Missed: +the given letter
m++; //to count for incorrect guesses
}
System.out.print(temp1);
}
System.out.println("Game Over.");
}
}
When you do this:
temp = word.replaceAll(word, "-");
...you are setting temp to be just "-", and not (for example) "----". To see why, consider if word is "hello"; then this line looks like:
temp = "hello".replaceAll("hello", "-");
So then later you are assuming that temp is as long as word is, because you find an index in word and try to access that character in temp. But temp is only one character long, hence the exception.
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p));
Try this one.....
This will solve your problem...!!
package beans;
import java.util.Scanner;
public class Hangman {
public static String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String word = "Sample";
String temp = "";
String letter = null;
int n;
int m=0;
int p = 0;
for (n = 0; n<word.length(); n++){
temp = temp + word.replaceAll(word, "-"); //replaces the String word with "-" and prints
}
System.out.print(temp);
while (m <= 5){ //the player can only guess incorrectly 5 times
System.out.println("\nEnter a letter:");
letter = sc.nextLine();
letter.toLowerCase();
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp = replace(temp, p , word.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.println(temp);
}
else {
System.out.print("\nMissed: "+letter); //if not, Missed: +the given letter
m++; //to count for incorrect guesses
}
}
System.out.println("Game Over.");
}
}
You shoud check documentation for replaceAll() method.Cause you are using it wrong.
replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
You putting whole string into regex parameter
If you do myString.replaceAll("\\.","-"); (use double backslash to specify regex) will replace any character beside newline with "-" check into regex. Regullar expressions
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.print(temp1);
}
the word.indexOf(letter); return index of letter if that latter is present in string otherwise -1. that's why you are getting Exception.
Related
It's hard to explain but I'm trying to create a program that only capitalizes the letter of every word that ends with a period, question mark, or exclamation point. I have managed to receive a result when inputting any of the marks but only when it is entered the second time. In other words I have to hit enter twice to get a result and I'm not sure why. I am still working on it on my own but I'm stuck at this problem.
import java.util.*;
public class SentenceCapitalizer
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
String wrong = keyboard.nextLine();
String[] check = {".!?"};
String upper_case_line="";
Scanner lineScan = new Scanner(line);
for (String sent : check)
{
if (sent.startsWith(wrong))
{
System.out.println("cant use .?!");
}
else
{
/* if (line.startsWith(" "))//if starts with space
System.out.println("good");
else
System.out.println("bad");
*/
//if (int i = 0; i < line.length; i++)
//{char c = line.chartAt(i);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) +
word.substring(1) + " ";
}
System.out.println(upper_case_line.trim());
}
}
}
}
Solution
Hey just a quick solution for your question. Converts the string to character array and then checks the character array for '.!?' if it finds the value then it will make the next letter a capital!
public class SentenceCapitalizer {
public static void main(String[] args) {
//Scanner, Variable to hold ouput
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
//Char array, boolean to check for capital
char [] lineChars = line.toCharArray();
boolean needCapital = false;
//String to hold output
String output = "";
//Check for period in line
for (int i = 0; i < lineChars.length; i++) {
//Make sure first char is upper case
if (i == 0) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
}
//Check for uppercase if char is not space
if (needCapital && Character.isLetter(lineChars[i])) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
needCapital = false;
}
if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') {
needCapital = true;
}
//Add character to string
output += lineChars[i];
}
//Output string
System.out.println (output);
}
}
i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again.
Some examples are
Input: “TAN” Output: “ATN”
Input: “ALACTRIC” Output:“AALCTRIC”
Input: "Fork" Output:"Fork"
Here is my code so far: i cannot figure out what to put in the for loop. Thank you!
import java.util.Scanner;
public class scrambleWordRetry {
public static void main(String[] args)
{
}
public static String scramble( Random random, String inputString)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word to scramble.");
inputString = scan.nextLine();
char a[] = inputString.toCharArray();
for( int i=0 ; i<a.length-1 ; i++ )
{
}
return inputString;
}
}
I hope this code is useful for you
Scanner x = new Scanner(System.in);
String str = x.next();
System.out.println("Before Swapping" + str);
str = scramble(str);
System.out.println("After Swapping " + str);
}
public static String scramble(String inputString) {
char s[] = inputString.toCharArray();
for (int i = 1; i < s.length; i++) {
if (s[i] == 'A' || s[i] == 'a') {
char temp = s[i - 1];
s[i - 1] = s[i];
s[i] = temp;
}
}
return new String(s);
}
then if you input 'ALACTRIC' the output will be 'AALCTRIC',
'Tan = aTn',
'fork = fork'.
I have this code to find a palindrome below; I need to be able to remove all numbers, spaces, and punctuation from the user input String, so I've been using replaceAll. When I only had String input = str.toLowerCase(); and String newInput = input.replaceAll("[0-9]+", ""); in my code, there was no problem. It removes the numbers and continues. However when I try to add punctuation or a space, I get a StringIndexOutOfBoundsException.
Example: I input Anna.55
The line underneath all of the replaceAll statements, System.out.println(newestInput);, will print out anna but immediately throws the error when reaching the while loop and states that the problem is with the index of 6.
From my understanding (I am still learning Java and am unfamiliar with replaceAll) removing the spaces with replaceAll("\\s", "") would remove the spaces left by the previous replaceAll statements and thus there would be no index 6 (or even 4). How is there an error at index of 6 when it no longer exists?
import java.util.Scanner;
public class PalindromeTester {
public static void main (String[] args) {
String str;
String another = "y";
int left;
int right;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) {
System.out.println("Enter a potential palindrome:");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
String input = str.toLowerCase();
String newInput = input.replaceAll("[0-9]+", "");
String newerInput = input.replaceAll("\\W", "");
String newestInput = newerInput.replaceAll("\\s", "");
System.out.println(newestInput);
while (newestInput.charAt(left) == newestInput.charAt(right) && left < right) {
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println("That string is not a palindrome.");
else
System.out.println("That string is a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
You're using right = str.length() - 1; to determine the length of the input, but you modify what was input after it (and what you compare)...
String input = str.toLowerCase();
String newInput = input.replaceAll("[0-9]+", "");
String newerInput = input.replaceAll("\\W", "");
String newestInput = newerInput.replaceAll("\\s", "");
System.out.println(newestInput);
while (newestInput.charAt(left) == newestInput.charAt(right) && left < right) {
Which means the String is no longer the original length, in your example, it's 1 character shorter
Instead, calculate the length of the newestInput instead
right = newestInput.length() - 1;
System.out.println(newestInput);
while (newestInput.charAt(left) == newestInput.charAt(right) && left < right) {
Two things first:
I think
input.replaceAll("\\W", "");
should be
newInput.replaceAll("\\W", "");
And right should be calculated after the tokens are removed and not before, like so:
left = 0;
String input = str.toLowerCase();
String newInput = input.replaceAll("[0-9]+", "");
String newerInput = newInput.replaceAll("\\W", "");
String newestInput = newerInput.replaceAll("\\s", "");
right = newestInput.length() - 1;
Otherwise right can be larger than the length of newestInput and you'll get a java.lang.StringIndexOutOfBoundsException.
Actually, an easier way to test if a string is a palindrome, is if it is the same backwards and forwards.
I tried this code but this is not working for all strings.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++)
{
if(str.charAt(i) == subStr.charAt(0))
{
for(int j=0 ; j<subStr.length();j++)
{
if( subStr.charAt(j) ==str.charAt(i+j))
count++;
else
{
count=0;
break;
}
}
}
}
if(count == subStr.length())
System.out.println("Sub String Matched !!");
else
System.out.println("String does not match !!");
}
}
What's wrong with this code ?
How to search a sub string in string
You don't need to loop over whole String. You can use string.indexOf(subString) to find the index of the substring in the string and it will return the index of the first occurrence of the substring. If you only want to ckeck whether String contains substring or not you can use string.contains(subString).
Try to decipher to the logic behind the code, so in plain english your code does the following:
LOGIC:
1)Enter a String via the Scanner and store it as str, do the same for the substring and store it as subStr.
2)Cycle through the each character of str via the for loop.
If the first character of the subStr is equal to any character with in str, then cycle through the characters of subStr. If the characters beyond this index are equal then increment the count variable each time the letters in each String are equal at the following indexes.
Else print String does not match.
3) If the number of similar characters in both Strings (denoted by the count variable) is equal to the length of the subString, then the subString is matched. Else no match.
ANSWER
So what went wrong?
I hope you notice on 2), The first bullet point you are only checking whether or not the first character of str is equal to the first character of subStr, if they are not equal you are then concluding that their is no match, which is false.
Consider the example:
str = "baloon"
subStr = "loon"
Your output would be: "String not matched"
This is because according to your code if 'b' != 'l' then theirs no match, which is false. That in essence is why your code does not work.
You could've just done the following:
if(str.contains(subStr)){
System.out.println("Sub-string matched");
}
Your code will only work if the substring is the end of the original string. This is because your code does not check that the entire substring was matched until it exits the first for loop. I moved the if (count == subStr.length() ) statement inside your first for loop and added a break if it finds the substring.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++) {
if(str.charAt(i) == subStr.charAt(0)) {
for(int j=0 ; j<subStr.length();j++) {
if( subStr.charAt(j) ==str.charAt(i+j)) {
count++;
} else {
count=0;
break;
}
}
if(count == subStr.length()) {
System.out.println("Sub String Matched !!");
//int index = i;
break;
}
}
}
if(count == 0){
System.out.println("String does not match !!");
}
}
}
Note: If you then want the index at which the substring (first) occurred, you can set int index = i; before breaking the loop as shown in the commented line above.
Another note: don't tend to omit the {}s in if and else statements. While, technically, you don't need them for single statements, it can cause bugs if you need to edit code later...
I am new to java and I have been trying to solve a problem which I feel might have a simpler answer than my code.The problem was to print the initials of a user input name of any length along with the full surname.But this has to be done without any String.split() or arrays.I tried getting the user to input his name one word at a time, but is there any there a possible way to get the whole name at once and do as required.
My code is as follows:
import java.io.*;
public class Initials {
public static void main(String[]args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of words your name contains");
int n=Integer.parseInt(br.readLine());
String str="";
for(int x=1;x<=n-1;x++){
System.out.println("Enter your name's word number:"+" "+x);
String s=br.readLine();
String st=s.toUpperCase();
char ch=st.charAt(0);
str=str+ch+".";
}
System.out.println("Enter your surname");
String sur=br.readLine();
str=str+" "+sur.toUpperCase();
System.out.println(str);
}
}
Use a regular expression (namely (?<=\w)\w+(?=\s)):
String name = "John Paul Jones"; // read this from the user
System.out.println(name.replaceAll("(?<=\\w)\\w+(?=\\s)", "."));
J. P. Jones
No split(), no arrays :)
A little explanation: We essentially want to replace all letters of each word that is followed by a whitespace character except the first letter, with a . character. To match such words, we use (?<=\w)\w+(?=\s):
(?<=\w) is a positive lookbehind; it checks that a word-character exists at the start of the match but does not include it in the match itself. We have this component because we don't want to match the first character of each name, but rather all but the first (except for the last name, which we'll deal with shortly).
\w+ matches any continuous string of word characters; we use this to match the rest of the name.
(?=\s) is a positive lookahead; it checks that our match is followed by a whitespace character, but does not include it in the match itself. We include this component because we don't want to replace anything on the last name, which should not be followed by a whitespace character and hence should not match the regular expression.
Another way around---
import java.util.Scanner;
//a class that will print your output
class Initial {
public void Initials() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Full name:");
String name = sc.nextLine();
int l = name.length();
int pos = 0;
for (int i = l - 1; i >= 0; i--) {
char ch = name.charAt(i);
if (ch == ' ') {
pos = i; //getting the last space before Surname
break;
}
}
System.out.print("The initials are: ");
System.out.print(name.charAt(0) + ".");//prints first name initial
// with dot
for (int x = 1; x < pos; x++) //finds midname initial
{
char ch = name.charAt(x);
if (ch == ' ') {
System.out.print(name.charAt(x + 1) + ".");
}
}
for (int i = pos; i < l; i++) { //for printing Surname
System.out.print(name.charAt(i));
}
}
}
public class Str {
public static void main(String[] args) {
Initial i = new Initial();
i.Initials();
}
}
//This code will work for any no. of words in the name
class Surnam {
public static void main(String name) {
name = " " + name;
int l=name.length(), p=0, m=0, r=0;
char y;
String word=" ", words=" ";
for(int i = 0; i = 0; i--) {
y=name.charAt(i);
if(y==' ') {
r=name.lastIndexOf(y); //extracting the last space of the string
word=name.substring(i,l); //extracting the surname
words=name.replace(word," "); //removing the surname break;
}
}
for (int i = 0; i <= r - 1; i++) {
char x=words.charAt(i);
if (x == ' ') {
System.out.print(words.charAt(i + 1) + "."); //Printing all initials before the surname with a dot
}
}
for (int i = l - 1; i >= 0; i--) {
char x=name.charAt(i);
if(x==' ') {
m=i;
name=name.substring(m,l); //extracting the surname
name=name.trim(); //removing all the spaces before the surname
System.out.print(name);
break;
}
}
}
}