Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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); } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote