This question already has answers here:
How to shuffle characters in a string without using Collections.shuffle(...)?
(17 answers)
Closed 9 years ago.
How can i randomized each string in Array words... for the word "Position" to "Psioiont". basically what i need to do is i want to display the i an funny way where a person has to think before he can answer...
Hello ---> "hlelo"
public class Rnd {
public static void main(String[] args) {
List list = new ArrayList();
Collections.shuffle(list);
String[] words =new String[]{"Position", "beast", "Hello"};
Collections.shuffle(Arrays.asList(words));
}
}
Just put the characters in each string into a list, then call Collections.shuffle(), then put them back into a string:
String x = "hello";
List<Character> list = new ArrayList<Character>();
for(char c : x.toCharArray()) {
list.add(c);
}
Collections.shuffle(list);
StringBuilder builder = new StringBuilder();
for(char c : list) {
builder.append(c);
}
String shuffled = builder.toString();
System.out.println(shuffled); //e.g. llheo
Convert the each string to an array of chars and call shuffle on that, then create a string again.
Of course, that doesn't actually work with real Unicode - there's no easy way to do it if there could be non-BMP characters or composite characters in there. But it will probably do for the kind of small game this appears to be.
Related
Trying to write a java method that will take a string, loop through it and where it finds a vowel (A,E,I,O,U,Y) replace it with the vowel plus "OB".
I've written the below but it isn't working as I'd expect and doesn't seem to be matching the current character in my string with the vowels from my list. (The program compiles and runs so it isn't an issue with not importing necessary bits at the beginning. The input string will always be uppercase and only contain alphas.) I'm struggling to figure out where I'm going wrong.
Can anyone help?
public static String obifyText(String text) {
String[] myList = new String[] {"A","E","I","O","U","Y"};
StringBuilder tempText = new StringBuilder(text);
String obify = "OB";
for (int i = 0; i < text.length() -1 ; i ++ ) {
if ( Arrays.asList(myList).contains(tempText.charAt(i)) ) {
System.out.println(tempText.charAt(i)+" found.");
tempText = tempText.insert((i+1),obify);
}
}
text = tempText.toString();
return text;
}
Don't play with indexes.
Managing with indexes could be difficult when you are dealing with changing the string.
Loop on the chars itself as follows:
public static void main(String[] args){
String[] myList = new String[] {"A","E","I","O","U","Y"};
String text = "AEE";
StringBuilder tempText = new StringBuilder("");
String obify = "OB";
for (char c : text.toCharArray()){
tempText = tempText.append(c);
if ( Arrays.asList(myList).contains(c+"") ) {
System.out.println(c+" found.");
tempText = tempText.append(obify);
}
}
text = tempText.toString();
System.out.println(text);
}
OUTPUT:
A found.
E found.
E found.
AOBEOBEOB
charAt returns a char, but myList stores String elements. An array of Strings can never contain values of char. Your if statement never runs.
You can convert the char value to a string:
Arrays.asList(myList).contains(Character.toString(tempText.charAt(i)))
There's just one more problem with your code.
When the code inserts OB after a vowel, there is a side effect: a new vowel O is created. Your code then tries to insert OB after the new O. This is undesired, right?
To make it not do this, you can loop from the end of the string to the start:
for (int i = text.length() - 1; i >= 0 ; i--) {
If this is not a homework question to practice using StringBuilder or for loops, here's a one liner solution using regex:
return text.replaceAll("([AEIOUY])", "$1OB");
You compare two different types in Arrays.asList(myList).contains(tempText.charAt(i)), Arrays.asList(myList) is a List<String> and tempText.charAt is a char. So the contains check will never result in true.
One possible fix, change myList to Character[]
Character[] myList = new Character[] {'A','E','I','O','U','Y'};
There is another problem with the actual insertion, see Pankaj Singhal answer for a solution to that.
This question already has answers here:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
(16 answers)
Closed 4 years ago.
so i am learning how to use the HashMap object. My question is, if I use the scanner object to ask a user for a String and I save that to a String variable. How can I take that String and "compare" it to my HashMap.
For example if a user inputs "abc".
My HashMap has ("a","abra") ("b","blastoise") ("c","charizard")
I want to print to System.out.println the result -- abra blastoise charizard instead of abc.
I will share my code that i have now but i am stuck with the next step and i hope that i am being clear with my question.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String keyboard = "";
HashMap hm = new HashMap();
hm.put("A","Abra");
hm.put("B", "Blastoise");
hm.put("C", "Charizard");
hm.put("D", "Dewgong");
keyboard = sc.nextLine();
Thank you in advanced :)
You can use chars as the key of your Map such put('a', "Abra") then you compare each char.
char[] str = string.toLowerCase().toCharArray();
for(char c : str)
System.out.println(map.get(c));
Also note that 'A' is different from 'a', you need to handle such case the best one would calling toLowerCase() in the string before getCharArray().
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
So I'm trying to convert a .txt file in the format of
1 2 3 4
5 6 7 8
9 1 0 1
into a 2D arraylist of strings.
This should also be replicable with any other thing such as
EXTENDING RETRACTING RETRACTING EXTENDING
EXTENDING EXTENDING RETRACTING
RETRACTING
Here's my code
public class Test {
public static ArrayList<ArrayList<String>> readFromFile(String path) throws FileNotFoundException{
#SuppressWarnings("resource")
Scanner in = new Scanner(new File(path));
ArrayList<ArrayList<String>> comments= new ArrayList<ArrayList<String>>();
ArrayList<String> words = new ArrayList<String>();
String[] line;
String str;
String [] values;
while(in.hasNextLine()){
str=in.nextLine();
line = str.split("\t");
values = line[2].split(" ");
for(String word : values){
words.add(word);
}
}
comments.add(words);
return comments;
}
public static void main(String[] args) throws FileNotFoundException{
ArrayList<ArrayList<String>> inputs = readFromFile("/Users/Jason/yaw.txt");
int k = 0;
for(int i = 0; i < inputs.size(); i++){
for(int j = 0; j < inputs.get(k).size(); j++){
System.out.print(inputs.get(i).get(j));
k++;
}
System.out.println();
}
}
}
Currently, it returns this error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Test.readFromFile(Test.java:19)
at Test.main(Test.java:31)
Any help on how to get this working?
This is one way to solve it:
// read file into list
List<String> linesInFile = Files.readAllLines(Paths.get("filename.txt"));
// create 2d array based on number of lines
List<List<String>> array = new ArrayList<>(linesInFile.size());
// iterate through every line of the file and split the elements using whitespace
linesInFile.forEach(line -> {
// get the elements in the current line
String[] elements = line.split("\\s+");
// store it in our 2d array
array.add(Arrays.asList(elements));
});
// print every row in our 2d array
array.forEach(System.out::println);
The Files.readAllLines method will return a List with all the lines in your file (similar to what your own version does).
Edit: Convert the List<List<String>> into ArrayList<ArrayList<String>> like following:
ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
array.forEach(row -> arrayList.add(new ArrayList<>(row)));
System.out.println(arrayList.getClass());
System.out.println(arrayList.get(0).getClass());
Will output:
>> class java.util.ArrayList
>> class java.util.ArrayList
You read in a line, then split it with "\t", which gives you an array with 1 value (so length = 1).
lines[2] is therefor out of bounds.
If I understood you correct, then you want to do:
line = str.split("\\s"); // line=[1, 2, 3, 4] for the first line you read
split("\\s") splits all space characters (so not only " ")
If this is not the case, then check what str contains.
Not sure why you do this:
values = line[2].split(" ");
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 8 years ago.
I recently attended an interview where I was asked to write a program.
The problem was:
Take a string. "Hammer", for example.
Reverse it and any character should not be repeated.
So, the output will be - "remaH".
This is the solution I gave:
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
String revStr = "";
for(int i=0; i<=str.length()-1;i++){
if(revStr.indexOf(str.charAt(i))==-1){
revStr = str.charAt(i)+revStr;
}
}
System.out.println(revStr);
}
}
How I can improve the above?
The problem is String is immutable object, and when using operator+ to concat a char with the current result, you actually create a new string.
This results in creating strings of length 1+2+...+n, which gives you total performance of O(n^2) (unless the compiler optimizes this for you).
Using a StringBuilder instead of concatting strings will give you O(n) performance, and with much better constants as well.
Note that a StringBuilder offers an efficient append() implementaiton, so you need to append elements to it, and NOT add them at the head of your StringBuilder.
You should also reconsider usage of indexOf() - if a characters cannot appear twice at all, consider using a Set<Chatacter> to maintain the list of 'used' characters, if it can appear twice, but not one after the other (for example "mam" is valid) - there is really no need for the indexOf() in the first place, just check the last character read.
Here is a solution without using any stringbuilder or intermediary String objects, just treating Strings as arrays of chars; this should be more efficient.
import java.util.Arrays;
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
String revStr = null;
char [] chars = str.toCharArray();
char [] reversedChars = new char[chars.length];
// copy first char
reversedChars[reversedChars.length - 1] = chars[0];
// process rest
int r = reversedChars.length - 2;
for(int i = 1 ; i < chars.length ; i++ ){
if(chars[i] != chars[i-1]){
reversedChars[r] = chars[i];
r--;
}
}
revStr = new String(Arrays.copyOfRange(reversedChars, r+1, reversedChars.length));
System.out.println(revStr);
}
package com.in.main;
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
StringBuilder revStr= new StringBuilder("");
for(int i=str.length(); i>=0;i--){
if(revStr.indexOf(str.charAt(i))==-1){
revStr.append(str.charAt(i));
}
}
System.out.println(revStr);
}
}
This question already has answers here:
Reversing characters in each word in a sentence - Stack Implementation
(6 answers)
Closed 9 years ago.
I am supposed to write a code that reads a sentence from the user and prints the characters of the words in the sentence backwards. It should include a helper method that takes a String as a parameter and returns a new String with the characters reversed. The individual words are reversed, for example the sentence "Hi dog cat". would print "iH god tac". I can make the entire sentence reverse but i cant figure out how to reverse individual words. Thanks! Also, i know how to return the String once i have found it, but i just cant get the right string
import java.util.Scanner;
import java.util.Stack;
public class ReverseStack
{
public static void main(String[] args)
{
String sentence;
System.out.println("Enter a sentence: ");
Scanner scan = new Scanner(System.in);
sentence = scan.nextLine();
String k = PrintStack(sentence);
}
private static String PrintStack(String sentence)
{
String reverse;
String stringReversed = "";
Stack<String> stack= new Stack<String>();
sentence.split(" ");
for(int i=0;i<sentence.length(); i++)
{
stack.push(sentence.substring(i, i+1));
}
while(!stack.isEmpty())
{
stringReversed += stack.pop();
}
System.out.println("Reverse is: " + stringReversed);
return reverse;
}
}
I will type an expatiation so you can still get the experience of writing the code, rather than me just giving you the code.
First create a Stack of Characters. Then use add each character in the String to the Stack, starting with the first char, then the second, and so on. Now either clear the String or create a new String to store the reversed word. Finally, add each character from the Stack to the String. This will pull the last character off first, then the second to last, and so on.
Note: I believe you have to use the Character wrapper class, rather than the primitive char; I may be incorrect about that though.
If you aren't familiar with how Stacks work, here is a nice interactive tool to visualize it: http://www.cise.ufl.edu/~sahni/dsaaj/JavaVersions/Stacks/AbstractStack/AbstractStack.htm
Change:
Stack<String> stack = new Stack<String>();
to be
Stack<Character> stack = new Stack<Character>();
and refactor your methods code as necessary; i.e.
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
I did it with a different kind of stack, but I suspect this might help
private static String reverseWord(String in) {
if (in.length() < 2) {
return in;
}
return reverseWord(in.substring(1)) + in.substring(0, 1);
}
private static String reverseSentence(String in) {
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(in);
while (st.hasMoreTokens()) {
if (sb.length() > 0)
sb.append(' ');
sb.append(reverseWord(st.nextToken()));
}
return sb.toString();
}
public static void main(String[] args) {
String sentence = "Hi dog cat";
String expectedOutput = "iH god tac";
System.out.println(expectedOutput
.equals(reverseSentence(sentence)));
}
Outputs
true