Switching letters in a string and recieving an index out of range error in Java -


i'm trying write program input sentence, , 2 letters, , switch instances of letters , print out switched sentence. instance, input

i eat bananas 

and “e” , “a,” , program print

i lika aet benenes  

here code, @ end prints out string index out of line. ideas how fix this?

system.out.println("write awesome."); string input1 = keyboard.readstring(); system.out.println("pick letter awesome sentence."); char letter1 = keyboard.readchar(); system.out.println("pick letter awesome sentence."); char letter2 = keyboard.readchar();  double let1 = (input1.length()); int let1next = (int) let1; double let2 = (input1.length()); int let2next = (int) let2;  string newuserimput = input1.replace(input1.charat(let1next),         input1.charat(let2next)); system.out.println(newuserimput); 

without stack trace, have guess exception on line.

string newuserimput = input1.replace(input1.charat(let1next),         input1.charat(let2next)); 

what input1.charat(let1next) resolve to?

double let1 = (input1.length()); int let1next = (int) let1; double let2 = (input1.length()); int let2next = (int) let2; 

this can't mean.

let1next represent end of array + 1 let2next.

therefore, there 2 major bugs here:

  1. you replacing occurrences of given character itself.
  2. the letter picking beyond end of string. remember, string indexes (such input string.charat) 0-based, range 0 through (length - 1). specifying input1.length, asking character after last character of string, hence stringindexoutofboundsexception.

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -