Cant get the this java problem to work (Trying to swap to random characters of a
ID: 3652148 • Letter: C
Question
Cant get the this java problem to work (Trying to swap to random characters of a word)package chapter4;
import java.util.Scanner;
public class SwitchingCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please print a word: ");
String word = in.next();
int i = (int) (Math.random() * (word.length() - 1));
int j = (int) (i + (Math.random() * word.length() + 1));
System.out.println(i);
System.out.println(j);
String first = first.substring(0,i); **** (it is saying that i never initialized first, middle and last here)
String middle = middle.substring(i + 1,j);
String last = last.substring(j,word.length() - 1);
String newword = first + word.charAt(j) + middle + word.charAt(i) + last; ****(when i do this)
System.out.println(newword); *******(so it wont print out of course)
}
}
Explanation / Answer
import java.util.Scanner; public class SwitchingCharacters { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please print a word: "); String word = in.next(); int i = (int) (Math.random() * (word.length() - 1)); int j = (int) (i + (Math.random() * word.length() + 1)); System.out.println(i); System.out.println(j); String first =word.substring(0, i); String middle = word.substring(i + 1,j); String last = word.substring(j,word.length() - 1); String newword = first + word.charAt(j) + middle + word.charAt(i) + last; System.out.println(newword); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.