public class WordScrambleEx1 {
public static void main(String[] args) {
String[] strArr = {"CHANGE", "LOVE", "HOPE", "VIEW"};
String answer = getAnswer(strArr);
String question = getScrambledWord(answer);
System.out.println("Question :" + question);
System.out.println("Answer: " + answer);
}
public static String getAnswer(String[] strArr) {
String i = strArr[(int)Math.random()*4];
return i;
}
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}
return question1;
}
}
I am very new to Java and was given a question where I am given four letters of words and my method needs to pick one of them randomly using Math.random and scramble the characters of that string.
My code finds a String from the given array but does not scramble the string. Can anyone tell me what I am doing wrong?
Understanding constructor and scope is really hard.
first mistake:
(int) Math.random() * i
will always return 0, because Math.random() returns a float between 0 and 1, so it will always be zero when you cast it to int (int doesnt round, it just cuts off the numbers after the comma).
you can fix this by using this:
(int) (Math.random() * i)
now we are first multiplying the float result of Math.random() with i which results in a float because the first number is a float. then we are casting this float to an int.
second mistake:
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}
return question1;
}
each iteration you create a new char array with a length of 0 and then you set question1 to it, which is always an empty string because the java array has nothing in it.
i would do it as follows:
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = new String();
ArrayList<Character> chars = new ArrayList<Character>(); //an arraylist is an array wich dynamically changes its size depending on the amount of its elements
for (int i = 0; i < character.length; i++) {// first we put all characters of the word into that arraylist
chars.add(character[i]);
}
while(chars.size()>0){//then we iterate over the arraylist as long as it has more than 0 elements
int index = (int)(Math.random() * chars.size());//we create a random index in the range of 0 and the arraylists size
question1 += chars.get(index);// we add the letter at the index we generated to the scrambled word variable
chars.remove(index);// then we remove the character we just added to the scrambled word, from the arraylist, so it cant be in there twice
}// thus the size decreases by 1 each iteration until every element of the arrraylist is somewhere in the scrambled word
return question1;
}
There are some mistakes in your code. The way you generate random integers is misleading. Let's look at the statement (int)Math.random() * 4 for an explanation. Math.random() does:
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Now, in Java a type cast has precedence over +, -, * and /, so what actually happens is ((int)Math.random()) * 4. Math.random() returns a floating point number between 0.0 and 1.0 exclusive, so roughly [0.0, 0.999999...]. A cast to int will truncate all decimal places and you will always get 0. Your statement then simplifies to 0 * 4 = 0. Overall, you always get the first word.
I recommend you to use the Random class instead. It provides a method nextInt(int n), which returns a random integer between 0 inclusive and n exclusive, so [0, n - 1].
Since there are a lot of errors in your code, I would like to provide you this solution:
import java.util.Random;
public class WordScrambleEx1 {
private static Random random;
public static void main(String[] args) {
// Create object of class (initializes the
// random generator with a default seed)
random = new Random();
String[] strArr = { "CHANGE", "LOVE", "HOPE", "VIEW" };
String answer = getAnswer(strArr);
String question = getScrambledWord(answer);
System.out.println("Question: " + question);
System.out.println("Answer: " + answer);
}
public static String getAnswer(String[] strArr) {
// Chooses a random index in [0, strArr.length - 1]
int index = random.nextInt(strArr.length);
String i = strArr[index];
return i;
}
public static String getScrambledWord(String str) {
String remaining = str;
String scrambled = "";
// Loop over the string, each time choose a random letter
// and add it to the scrambled word, then remove that letter
// from the remaining word. Repeat until all letters are gone.
for (int i = str.length(); i > 0; i--) {
// Choose the index of a letter in the remaining string
int index = random.nextInt(remaining.length());
// Add the letter at the random index to your scambled word
scrambled += remaining.charAt(index);
// Remove the chosen character from the remaining sequence
remaining = remaining.substring(0, index) + remaining.substring(index + 1);
}
return scrambled;
}
}
Related
I have a integer value like 4590897, what i have to do is i have to shuffle this integer in a way so that i get output 4759980, its like rading first number and last number and creating a new number. integer value can be any.
i tried some code like by converting number in char array and then iterating it and appending it in StringBuilder but not getting desired result.
Code below
public final class class2 {
public static void main(String[] args) {
int a = 15670;
StringBuilder s2 = new StringBuilder();
String s1 = String.valueOf(a);
char[] ch = s1.toCharArray();
//System.out.println(ch.length);
Outerloop:
for(int i = 0; i <=ch.length-1;i++){
//System.out.println(ch[i]);
for(int j = ch.length-1; j >=0; j--){
s2.append(ch[i]);
s2.append(ch[j]);
break;
}
}
System.out.println(s2);
}
}
i have to shuffle this integer in a way so that i get output 4759980
Try this! I am first converting the number to a string. Then I add the first and last digit, the second and the before last digit, etc. Then, I make sure that the string is the same length as the starting one (in case of numbers with odd-number of digits).
public int scramble(int number) {
String numberString = Integer.toString(number);
int numberLength = numberString.length();
String result = "";
for (int i = 0; i < (numberLength + 2) / 2; i++) {
result += numberString.charAt(i);
result += numberString.charAt(numberLength - i - 1);
}
//Making sure that the resulting string is the same length as the original
//Initially, the result for a number with an odd number of digits, such as 12345
//will be 152344. So you need to make sure the last digit is removed.
result = result.substring(0, numberLength);
return Integer.parseInt(result);
}
What about this. First you decompose your number into digits and then you randomly add them back to each other, by picking a random position to add the digit...
public int scramble(int number) {
//Convert the integer to an Array of strings where each string represents a digit
String[] digits = Integer.toString(number).split("");
//Add the individual digits to a list in random order, using a random position
List<String> resultList = new ArrayList<>();
for (String digit: digits) {
int position = (int) (Math.random()*(resultList.size()));
resultList.add(position, digit);
}
//Convert the list with digits in random order to a string
String resultString ="";
for (String digit: resultList) {
resultString += digit;
}
//Convert the resulting string to an integer and return
return Integer.parseInt(resultString);
}
Take two pointers, start and end. Iterate through the string and append the character from start and end to a new string. Increment start and decrement end untill start and end is same.
public static void main(String args[]){
int num = 45908971;
System.out.println(alternate(num));
}
private static int alternate(int num){
String numStr = Integer.toString(num);
int start = 0;
int end = numStr.length()-1;
StringBuffer newNum = new StringBuffer();
while(start<=end) {
newNum.append(numStr.charAt(start++)).append(numStr.charAt(end--));
}
return Integer.parseInt(new String(newNum.toString()));
}
I am trying to sort the digits of an Integer in descending order in JAVA but I am not allowed to use any array.
This was given to me as an assignment in class and below is a code that I tried but failed.
import java.util.Scanner;
class descend
{
public static void main(String args[])
{
int a=0,loc=0,parse=0,temp=0,big=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number");
a=scan.nextInt();
String s=Integer.toString(a);
int l=s.length();
for(int i=0;i<l;i++)
{
big=(int)(s.charAt(i));
loc=i;
for(int j=i+1;j<l;j++)
{
parse=(int)(s.charAt(j));
if(parse>big)
{
big = parse;
loc=j;
}
}
temp=parse;
s.charAt(i)=s.charAt(loc);
s.charAt(loc)=temp
}
System.out.print(s);
}
}
Here I get a syntax error at s.charAt(i)=s.charAt(loc); and s.charAt(loc)=temp; that a variable is required but a value is given.
Please help me out with this and I shall always be grateful to you.
Maybe the teacher want to test your knowledge about the new stream API. Or maybe he wants you to test your knowledge about Collections.sort() and LinkedList (which does not contain an internal array).
1.) Here is a solution with stream API:
int number = 52214;
String.valueOf(number).chars()
.sorted()
.map(Character::getNumericValue).forEach(System.out::print);
This will print out:
12245
2.) Here is a solution with collections:
List<Integer> list = new LinkedList<Integer>();
StringCharacterIterator iterator = new StringCharacterIterator(String.valueOf(number));
for (char c = iterator.first(); c != CharacterIterator.DONE; c = iterator.next())
{
list.add(Character.getNumericValue(c));
}
Collections.sort(list);
System.out.println("list=" + list);
This will print out:
list=[1, 2, 2, 4, 5]
String cannot be changed, only replaced, hence a = b; f(b); will never change a.
With 10 digits only, you could iterate, step through, from 0 upto 9 to have the sorting:
int number = ... // or String number
if (number == 0) { // or < 10
System.out.println(number);
} else {
for (int digit = 0; digit <= 9; ++digit) {
// While being able to remove the current digit:
for (;;) {
int scrapedNumber = numberWithoutDigitOnce(number, digit);
if (scrapedNumber == number) {
break;
}
number = scrapedNumber;
System.out.print(digit);
}
}
System.out.println();
}
int numberWithoutDigitOnce(int number, int digit) {
if (number % 10 == digit) {
return number / 10;
}
int n = numberWithoutDigitOnce(number/10, digit)*10 + (number % 10);
}
Zero is a special case.
A recursive solution, you find the highest digit in the String, add it to your output String, and remove it from your input String.
Repeat until your input String is empty.
Removing the character at a given index in a String can be achieve by concatenating the characters before the index and the ones after the index. (Or with a StringBuilder but I agree with the comments on the OP that it would be cheating to use a StringBuilder)
private static String sort(String digitsLeftToSort, String sortedString) {
if(digitsLeftToSort.length() == 0) { // no more character to sort
return sortedString;
} else {
// find the index of the highest digit
int index = findIndexOfHighestDigit(digitsLeftToSort);
// add the character at that index to your output String
sortedString += digitsLeftToSort.charAt(index);
// Remove it from your input String
digitsLeftToSort = digitsLeftToSort.substring(0, index) + digitsLeftToSort.substring(index+1);
// Recursive call with your new Strings
return sort(digitsLeftToSort, sortedString);
}
}
// This finds the index of the highest digit in the given String
private static int findIndexOfHighestDigit(String s) {
int highestDigitValue = -1;
int highestDigitIndex = -1;
int integerValue;
for(int i = 0; i< s.length(); i++) {
integerValue = Character.getNumericValue(s.charAt(i));
if(integerValue > highestDigitValue) {
highestDigitValue = integerValue;
highestDigitIndex = i;
}
}
return highestDigitIndex;
}
Then
String sortedString = sort("462375623478142", "");
System.out.println(sortedString);
Outputs
877665444332221
Sorry, But after applying so much effort, I figured it out.
int n=54321;char ch;
String s=Integer.toString(n);
int l= s.length();
for(int i=48;i<=57;i++) //ascii values from 0 - 9
{
for(int j=0;j<l;j++)
{
ch=s.charAt(j);
if(ch==(char)i) // checking if a digit equals a number
{
System.out.print(ch);
}
}
}
It sorts the digits in ascending order. To sort in descending order we should use
for(int i=57;i>=48;i--)
I need to create a program that will take a word without spaces, punctuation, and all lowercase, and rearranges the letters randomly. It needs to have substrings or charAt, I cannot use an array since we have not learned them yet. It also hsa to be different everytime, really n! times I think. This is what I have so far-
public static void main(String[] args) {
Scanner kboard = new Scanner(System.in);
System.out.println("Enter a word that is less than 11 lowercase letters and has no punctuation or spaces: ");
String word = kboard.next();
while(word.length()>1)
{
System.out.print(word.charAt(1));
System.out.print(word.charAt(0));
word = word.substring(2);
}
System.out.println(word);
}
This rearranges the words, but it does not do it random every time. I thought I could do something like this, but I think it is messy and doesn't make much sense.
public static void main(String[] args) {
Scanner kboard = new Scanner(System.in);
String word, pt1 = "", pt2 = "", pt3 = "";
System.out.println("Enter a word that is less than 11 lowercase letters and has no punctuation or spaces: ");
word = kboard.nextLine();
int num1 = 0, num2 = 0, thing = 0;
while(thing<4)
{
thing = thing + 1;
num1 = (int)(word.length() * Math.random() + 1);
num2 = (word.length() - (word.length() % num1));
}
pt1 = word.substring(num1, num2);
pt2 = word.substring(num1, num2);
pt3 = word.substring(num1, num2);
System.out.print(pt1);
System.out.print(pt2);
System.out.print(pt3);
So what can I do to randomize the letters?
A simple solution to all "how do I randomize" a fixed set of elements is: shuffling.
Simply turn your String into a List of Character, to then shuffle that list.
( creating that list boils down to new ArrayList<>(yourWord.toCharArray() ).
GhostCat beat me in a few seconds :)
char[] arr = "abcdefg".toCharArray();
List<Character> list = new LinkedList<>(); // copy the chars to a list
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
Collections.shuffle(list); // use to shuffle
for (int i = 0; i < arr.length; i++) { // copy the shuffled chars back to the array
arr[i] = list.get(i);
}
System.out.println(new String(arr));
This could be implemented very easily using standard libraries,
but it seems you cannot use arrays and lists,
which makes this exercise a bit harder than it needs to be.
You can implement the following algorithm:
Initialize the output as an empty string
while the word is not empty
Pick a character randomly
Append the character to the output
Remove the selected character from the word, by replacing word with the part before the index + the part after the index
This can be implemented reasonably efficiently using a StringBuilder:
String shuffled(Random random, String word) {
StringBuilder result = new StringBuilder(word.length());
StringBuilder rest = new StringBuilder(word);
while (rest.length() > 0) {
int index = random.nextInt(rest.length());
result.append(rest.charAt(index));
rest.deleteCharAt(index);
}
return result.toString();
}
If you cannot use a StringBuilder,
then you can work with strings,
but this will be less efficient,
and normally not recommended in Java.
(Because it involves many string concatenations, which is inefficient.)
String shuffled(Random random, String word) {
String result = "";
String rest = word;
while (!rest.isEmpty()) {
int index = random.nextInt(rest.length());
result += rest.charAt(index);
rest = rest.substring(0, index) + rest.substring(index + 1);
}
return result;
}
You can call this with:
String shuffled = shuffled(new Random(), word);
What about this :
public static void main(String[] args) {
String test = "onetwothree";
Random random = new Random();
for (int i=0;i<test.length();i++){
int randomCharacterPosition = random.nextInt(test.length());
String start = test.substring(0,randomCharacterPosition);
String end = test.substring(randomCharacterPosition);
test = end.concat(start);
}
System.out.println(test);
}
Basically you getting a string, randomly choose a position in string.
Using this position you dividing input string into two strings and swaping them.
Nothing more than random, substring and concat (which can be replaced with + operator)
I want to write some automated tests for web app authentication. The login password is case-sensitive and always contains at least one alphabetic character.
I want to write a test where I randomly change the case of one or more alphabetic characters.
Let's say the password string is "123te123st!".
Now I want to change this string to one which contains at least one uppercase letter. I'm trying to make sure that the login is still case-insensitive and any variation in case will fail to match the password.
Does anybody know a elegant way to do it? I searched already (including Apache Commons) but couldn't find a helper method.
You can look at the randomAlphaNumeric from the RandomStringUtils, although it would seem that you are not guaranteed for it to have an upper case. To go around this, you could get the first lowercase letter and use the .toUpper() method to get it to upper case.
Alternatively, you could generate random numbers between 0 and 9 and 65 and 90 and 97 and 122. The first set should get you random numbers, you could then cast the second number to a character to get your upper case letter(s) and do the same on the last number to get your lower case ones.
That being said, when testing one usually goes for data which is predetermined rather than generating data on the fly, since that would make it easier to debug. Having a simple pool of passwords might also be easier to implement and would also allow you to better test edge cases.
class Case
{
public static void main(String ar[])
{
String s = "upperCase",split[];
split = s.split("");
int len = s.length(),i=0;
while(i!=len)
{
if(split[i].toUpperCase() == split[i])
{
System.out.println("Password Contains One UpperCase Latter");
break;
}
i++;
}
}
}
By using this code u can easily check whether string contain uppercase or not.
if output prints "Password Contains One Uppercase Latter" this message then string contain at least on uppercase.
In this case output would like:
You can use this class to generate random passwords with a constraint on uppercase letters.
import java.util.Random;
public class RandomPasswordGenerator {
private static final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final String NUM = "0123456789";
private static final String SPL_CHARS = "!##$%^&*_=+-/";
public static char[] generatePswd(int minLen, int maxLen, int noOfCAPSAlpha,
int noOfDigits, int noOfSplChars) {
if(minLen > maxLen)
throw new IllegalArgumentException("Min. Length > Max. Length!");
if( (noOfCAPSAlpha + noOfDigits + noOfSplChars) > minLen )
throw new IllegalArgumentException
("Min. Length should be atleast sum of (CAPS, DIGITS, SPL CHARS) Length!");
Random rnd = new Random();
int len = rnd.nextInt(maxLen - minLen + 1) + minLen;
char[] pswd = new char[len];
int index = 0;
for (int i = 0; i < noOfCAPSAlpha; i++) {
index = getNextIndex(rnd, len, pswd);
pswd[index] = ALPHA_CAPS.charAt(rnd.nextInt(ALPHA_CAPS.length()));
}
for (int i = 0; i < noOfDigits; i++) {
index = getNextIndex(rnd, len, pswd);
pswd[index] = NUM.charAt(rnd.nextInt(NUM.length()));
}
for (int i = 0; i < noOfSplChars; i++) {
index = getNextIndex(rnd, len, pswd);
pswd[index] = SPL_CHARS.charAt(rnd.nextInt(SPL_CHARS.length()));
}
for(int i = 0; i < len; i++) {
if(pswd[i] == 0) {
pswd[i] = ALPHA.charAt(rnd.nextInt(ALPHA.length()));
}
}
return pswd;
}
private static int getNextIndex(Random rnd, int len, char[] pswd) {
int index = rnd.nextInt(len);
while(pswd[index = rnd.nextInt(len)] != 0);
return index;
}
}
You can try like this:
public class Test{
public static void main(String[] args){
String s = "1a23test12hjsd2"; // Take it as a password
char[] c= s.toCharArray(); //Convert string in chararray
boolean flag= false;
StringBuilder s1= new StringBuilder();
for(int d:c){
if(d>=97 && d<=122 && !flag){ //Converting lowercase to upper case
d=d-32;
flag=true;
}
s1.append((char)d);
}
System.out.println(s1);
}
}
To generate all capitalized variants of a string, it makes sense to scan the string and store the position of each letter in a list. This will let you iterate over the letters while skipping the non-letter characters.
For example, for the string "_a_b_c_", you want to store the positions [1, 3, 5].
Next, make a boolean array of the same length as the list of letter positions. This will represent the positions of letters that have had their case inverted.
To generate the next capitalized variant, pretend that the boolean array represents a binary number in reverse. Add 1 to that boolean number, which means scanning the array from the beginning, flipping each true to false until you reach a false, which you flip to true. As you flip each bit, invert the case of the corresponding character in the string.
Thus, we get the following 23 - 1 = 7 variants of "_a_b_c_":
binary number reversed capitalized variant
001 100 _A_b_c_
010 010 _a_B_c_
011 110 _A_B_c_
100 001 _a_b_C_
101 101 _A_b_C_
110 011 _a_B_C_
111 111 _A_B_C_
Here is a complete Java implementation.
import java.util.*;
import java.io.*;
public class VaryCaps {
int wordLength,
numLetters;
Integer letterPositions[];
boolean inverted[];
StringBuffer buffer;
public VaryCaps(String word) {
wordLength = word.length();
List<Integer> positionList = new ArrayList<Integer>();
for (int i = 0; i < wordLength; ++i) {
if (Character.isLetter(word.charAt(i))) {
positionList.add(i);
}
}
numLetters = positionList.size();
letterPositions = positionList.toArray(new Integer[numLetters]);
inverted = new boolean[numLetters];
buffer = new StringBuffer(word);
}
private void invert(int index) {
int pos = letterPositions[index];
char ch = buffer.charAt(pos);
if (Character.isUpperCase(ch)) {
ch = Character.toLowerCase(ch);
} else {
ch = Character.toUpperCase(ch);
}
buffer.setCharAt(pos, ch);
inverted[index] = !inverted[index];
}
public String next() {
int index = 0;
while (index < numLetters && inverted[index]) {
invert(index++);
}
if (index == numLetters) {
return null;
}
invert(index);
return buffer.toString();
}
public static void main(String[] args) {
VaryCaps rc = new VaryCaps("_a_b_c_");
String s;
while ((s = rc.next()) != null) {
System.out.println(s);
}
}
}
import java.util.Scanner;
/**
*
* #author Cutuk
*/
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String a;
Scanner in = new Scanner (System.in);
a = in.nextLine();
char first = a.charAt(0);
System.out.print(first);
int v= a.length()-1;
char last = a.charAt(v);
int k= a.length();
int random=0;
char x='\u0000';
char middle= '\u0000' ;
for (int i=1; i<a.length()-1;i++){
random= (int )(Math.random() * (k-2) + 1);
middle=a.charAt(random);
x=middle;
System.out.print(x);
}
System.out.print(last);
}
}
I am supposed to take a word, shuffle the letters inside, but keep the first and the last letter unchanged. I managed to randomize, but I cannot keep it from repeating.
Your approach is incorrect: when you pick middle letters at random, it is impossible to guarantee that all letters from the middle of the word would be printed (and as a consequence, that other letters would not be repeated).
There are several ways of fixing this:
Each time you generate a random index, mark that index in an array of booleans. The length of the array is equal to the length of the word. Check the array before using each new index that you generate; if the index is marked, continue generating new random indexes until you hit an empty one.
Create an array of integer indexes of letters inside the word (i.e. 1 through length-1, inclusive). Do a random shuffle on the array, and use the shuffled indexes to pick middle letters.
Similar to 2, except you put all middle letters in an array, and shuffle it.
If I understand your question, I would suggest you start by building a List<Character> and then use Collections.shuffle(List) and finally build your return String with a StringBuilder like
private static String shuffleLetters(String in) {
if (in == null || in.length() < 3) {
return in;
}
char first = in.charAt(0);
char last = in.charAt(in.length() - 1);
List<Character> chars = new ArrayList<>();
for (char ch : in.substring(1, in.length() - 1).toCharArray()) {
chars.add(ch);
}
Collections.shuffle(chars);
StringBuilder sb = new StringBuilder();
sb.append(first);
for (char ch : chars) {
sb.append(ch);
}
sb.append(last);
return sb.toString();
}
Assuming "shuffling" can allow a middle character to sometimes be swapped with itself, you can do something like:
private static final String[] TEST_WORDS = {"apple", "banana", "pear", "raspberry", "cucumber", "watermelon", "a", "ab", "", null};
public static void main(String[] args)
{
for (String word: TEST_WORDS)
{
System.out.println(shuffleInside(word));
}
}
private static String shuffleInside(String word)
{
String ret = word;
if (word != null)
{
Random r = new Random();
int strLen = word.length();
if (strLen > 2)
{
char[] middleChars = word.substring(1, strLen - 1).toCharArray();
shuffle(middleChars, r);
ret = word.charAt(0) + new String(middleChars) + word.charAt(strLen - 1);
}
}
return ret;
}
private static void shuffle(char[] chars, Random r)
{
for (int i = chars.length - 1; i > 0; i--)
{
int index = r.nextInt(i + 1);
char c = chars[index];
chars[index] = chars[i];
chars[i] = c;
}
}
Which handles the case where the word is null, one character, two characters, or two or more characters and produces the following output on a single run:
apple
bnaana
paer
rerrsbpay
cbuemucr
waomteerln
a
ab
null
You could simply create a List<Integer> for storing the random numbers that you generated.
Here is your code from above, cleaned up, with meaningful naming and the List for looking up the history:
public class Main {
public static void main(String[] args) {
final Scanner in = new Scanner(System.in);
final Random rnd = new Random(System.currentTimeMillis());
final List<Integer> rndHistory = new LinkedList<>(); // <-- your history
System.out.print("Please type a word: ");
final String input = in.nextLine();
System.out.print(input.charAt(0));
for (int i = 1, random = 0; i < input.length() - 1; i++) {
do {
random = rnd.nextInt(input.length() - 2) + 1;
} while (rndHistory.contains(random)); // check the history
rndHistory.add(random); // add to the history
System.out.print(input.charAt(random));
}
System.out.println(input.charAt(input.length() - 1));
}
}
Main differences:
final Random rnd = new Random(System.currentTimeMillis()); Using
the the java.util.Random class is a better way for generating
random numbers.
final List<Integer> rndHistory = new LinkedList<>(); This is the actual difference, part of the mechanism to prevent double shuffles
System.out.print("Please type a word: "); a meaningful prompt for
the user (who is going to know what to do, when you program is
executed and there is nothing on the screen?)
and finally:
do {
random = rnd.nextInt(input.length() - 2) + 1;
} while (rndHistory.contains(random)); // check the history
rndHistory.add(random); // add to the history
The 'prevent a random number from being used twice' mechanics
For your random try this: Random generator = new Random(System.currentTimeMillis());