I am having problems with replacing the characters in the char array. I have tried the .replace method, but it does not seem to work. So do you know how to replace the letters in the char array, with the char variable GuessedLetter. This is code whole code I've developed so far:
import java.util.Scanner;
public class Hangman{
public static void main(String []args){
Scanner Input = new Scanner(System.in);
String[] CollectionOfWords = {"apple","banana","pear","plum","watermelon"};
int RadmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length);
String RadmWord = CollectionOfWords[RadmNumber];
System.out.println(RadmWord);
char[] GenRadmLetter = RadmWord.toCharArray();
char[] GenRadmLetter2 = RadmWord.toCharArray();
for (int x = 0; x<GenRadmLetter.length; x++){
GenRadmLetter[x]='?';
}
System.out.println(String.valueOf(GenRadmLetter));
Scanner input = new Scanner(System.in);
System.out.println("Hello. Guess a letter.");
char GuessedLetter = Input.next().charAt(0);
int RW = RadmWord.indexOf(GuessedLetter);
String GenRadmLetterStr = String.valueOf(GenRadmLetter);
}
}
Thank you,
You are trying to modify a String.
This class is immutable, so when you try something such as:
GenRadmLetter[x]='?';
You are not modifying the data inside the RadmWord.
What you could do, is something such as:
char[] GenRadmLetter2 = new char[RadmWord.length];
for (int x = 0; x < RadmWord.length; x++){
GenRadmLetter[x]='?';
}
String result = new String(GenRadmLetter2);
Although, you may wish to keep the displayed String as a character array to allow easy changes to the display.
Firstly, variable names should begin with a lowercase letter as such. A capital letter implies a class type. This is a very standard convention when it comes to Java, and as such it helps readability when sharing code with others.
String radmWord = collectionOfWords[radmNumber];
Secondly, the method String.indexOf(Char) only returns the first index of that character within the string. Since you would want to be replacing all occurrences of that character you would want to actually loop through the word checking each character to see if it is the character that was guessed. From there you could then replace that index within your guessing word. Take a look at this code I put together as an example, it should help you figure out what you need to do:
String randomWord = "apple";
String guessWord = "?????";
char guess = 'p';
for (int i = 0; i < randomWord.length(); i++) {
if (randomWord.charAt(i) == guess) {
char[] tempGuess = guessWord.toCharArray();
tempGuess[i] = guess;
guessWord = Arrays.toString(tempGuess);
}
}
Related
I am writing a program in java that allows a user to enter n and puts them strings into an array. Then, the program takes those strings and splits them up into single char characters and places those characters into a new char array.
An example of what I'm trying to do is below:
Input n: 3
Input strings: "Cat", "Dog", "Mouse"
Original Input Array: [Cat][Dog][Mouse]
Desired Output Array: [C][a][t][D][o][g][M][o][u][s][e]
There are a few problems that occur with my code when I run it:
I get an exception error with the line of code that takes in my input strings. Line of code: exp[i] = input.nextLine();
Netbeans IDE is telling me it can not find the symbol for the split function I'm trying to use.
I am not sure what is wrong with my code, but I feel like at least the part where I input the strings should be working. I realize I don't have any output code yet, as I am just trying to get the input part working right now. Any suggestions would be appreciated!
public class Strings {
Scanner input = new Scanner(System.in);
int n; //number of strings
String[] exp = new String[n]; //input strings
char[] tokens = new char[n]; //individual char characters
//Gather data
public void SetNumberStrings(){
n = input.nextInt();
}
public void SetExpressions(){
for (int i = 0; i < n; i++){
exp[i] = input.nextLine();
}
}
public void SplitExpressions(){
for (int i = 0; i < n; i++){
tokens[i] = exp.split(" ");
}
}
public static void main(String[] args) {
Strings exp1 = new Strings();
exp1.SetNumberStrings();
exp1.SetExpressions();
exp1.SplitExpressions();
}
}
There are multiple issues with your code:
The array initialization is not working like that. Having int n;
//number of strings as a class field, means it will be initialized
with 0, resulting in your arrays having a length of 0. To fix this
you may declare your arrays after giving a value to n.
At line tokens[i] = exp.split(" "); there is indeed a compilation
error, because you are trying to call the split method on the exp
array, but the split method is from String class. So you would need
to call exp[i].split
split method is not doing what you think it's doing. I think you
are looking for the toCharArray() method.
tokens array should have the length of all the strings that you
scanned.
There are several issues with your program. The initialisation of class member variables seems to be wrong (considering your requirement). The call to SetExpressions in main will not alter the members n, exp and tokens as you are expecting. Value of n will be 0 by default and it remains so by the time exp and tokens get initialised. Hence, when you try to assign the input strings to the elements of exp, you get java.lang.ArrayIndexOutOfBoundsException.
Further, you are trying to invoke split method on a String[] object (exp), which is wrong (a String has split() method not String[]).
If you just trying to take a string of words and convert them all into a char[], then may be you can simply concatenate all the words into a single String object, and then do a toCharArray() on that.
Hope this helps.
import java.util.Scanner;
public class Strings {
Scanner input = new Scanner(System.in);
int n; //number of strings
String[] exp; //Fix...This line was causing exception in your program We should not initialize array here because at this point we don't have the length from user
char[] tokens; //Fix...We are not confirmed of the length of token array at this point
//Gather data
public void SetNumberStrings(){
n = input.nextInt();
}
public void SetExpressions(){
exp= new String[n];
for (int i = 0; i <n; i++){
exp[i] = input.next();//.next() function should be used.
}
}
public void SplitExpressions(){
int length=0;
int l=0;
for(int i=0; i<exp.length; i++) {
length+= exp[i].length();
}//this loop will calculate the required length for character array
tokens =new char[length];//Giving length of array here
for(int i=0; i<exp.length; i++) {
for(int j=0; j<exp[i].length(); j++) {
tokens[l]=exp[i].charAt(j);//
l++;
}
}
}
public static void main(String[] args) {
Strings exp1 = new Strings();
exp1.SetNumberStrings();
exp1.SetExpressions();
exp1.SplitExpressions();
}
}
I have cleared all the problems in the code. As mentioned in comments.You had initialized all class variables in class, this is not a good programming practice.
Scanner user_input = new Scanner( System.in );
String cipher_input = user_input.nextLine();
String[] arr_cipher_input = cipher_input.split("");
int[] arr_ctext = new int[cipher_input.length()];
for (int i = 0; i < cipher_input.length(); i++) {
arr_ctext[i] = (int) arr_cipher_input[i].charAt(i);
}
The above code takes an input and splits it into an array (e.g. "hello" becomes ["h","e","l","l","o"]) and then I attempt to convert the characters to their ascii values which is where it returns the error in the title. It correctly converts the first character every time and then stops on the second and I can't seem to figure out why. The array lengths seem to be the same so I'm not sure what I'm doing wrong. I'd appreciate any help. Thanks in advance!
You are creating a number of one character String(s). But you are trying to access subsequent characters. There aren't any. Change charAt(i) to charAt(0) to fix. Like,
arr_ctext[i] = (int) arr_cipher_input[i].charAt(0);
or (more efficiently) skip the split and access the characters in the input directly. Like,
String cipher_input = user_input.nextLine();
int[] arr_ctext = new int[cipher_input.length()];
for (int i = 0; i < cipher_input.length(); i++) {
arr_ctext[i] = (int) cipher_input.charAt(i);
}
I have successfully printed my String backwards, but I'm having a hard time getting it to shift forward a letter. My outputs have been numbers instead of letters, so I have tried to convert those numbers back to letters unsuccessfully. There is other code in this as well, but I only need help with this one bit.
package inlämningsuppgift4;
import java.util.Scanner;
public class Inlämningsuppgift4 {
public static void word(String w1){
//char a[]= w1.toCharArray();
for (int i=w1.length()-1; i>=0; i--)
//char c = 'a';
//c = (char) (((c - 'a' - 1) % 26) + 'a');
{System.out.print(w1.charAt(i));
}
System.out.println();
}
public static void word2(String w2){
for (int j=0;j<w2.length(); j++)
{System.out.print("*"+w2.charAt(j));
}
System.out.println("*");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Ange ett ord: ");
String ord = input.nextLine();
word2(ord);
word(ord);
}
}
It seems like I was on the right path trying to set up "//char c" but I couldn't get it to function as written. I got that code from a questions search, but can't wrap my head around it. How do I make it fit with my code already written? Or should I find a different way?
You have two different problems:
reversing a string. There are a lot of ways to do it.
String s1 = "cat";
String s2 = "";
for (int i =0 ; i < s1.length(); i++) {
s2 = s1.charAt(i) + s2;
}
System.out.println(s2);
So just create a new string by adding strings backwards.
"Shifting" a character, which presumably means taking the code-point and modifying it, and possibly wrapping it (eg: Z wraps to A, instead of moving forward to [)
String s1 = "cat";
String s2 = "";
for (int i =0 ; i < s1.length(); i++) {
char c = s1.charAt(i);
c += 1;
// reverse string implementation omitted
}
System.out.println(s2);
Java seems to let you add directly to char so whatever works. Note that this does not care about wrapping, so z would not wrap to a. That's up to you to figure out.
Now you just need to combine that with the string building.
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 have String variable with value- f.e.:
this is test-str-ing_łóśżćń.
And I would like replace this chars:
, -, ł,ó,ś,ż,ć,ń
with those:
_,_,l,o,s,z,c,n.
And I mean here, that if parser will found f.e.: char - (which is second in first list) should be replaced with char that is in the same position/place in second list, which in this example is: _.
The char ó should be replaced with char o.
The char ń should be replaced with char n.
In my case the list of characters to replace is quite long and parsing in loop for each char to replace would not be enought efficient.
I know method replaceAll(). but it only accept one in String and one out String
So I am looking for method, that will allow me to work on arrays/list of Strings instead of single String.
Please give me some help.
Use java.text.Normalizer to Decompose accented letters in base letter plus "combining diacritical marks."
String base = Normalizer.normalize(accented, Form.NFKD)
.replaceAll("\\p{M}", "");
This does a decompose (D) normalization, and then removes Marks.
Some replacements still needed.
char[] out = new char[src.length()];
for( j ...){
inputChar = src.charAt(j);
for (int i = 0; i < convertChars.length; i++) {
if (inputChar == convertChars[i]) {
inputChar = toChars[i];
}
}
}
out[j] = inputChar ;
}
out2 = new String(out);
Extracted from bigger code without IDE, not tested. Loop (I hope) don't allocate objects and should not degrade speed.
Make a static lookup table:
private static char[] substitutions = new char[65536];
static {
// Initialize
for (char c = 0; c < substitutions.length; c++) {
substitutions[c] = c;
}
// Now add mappings.
substitions['-'] = '_'; // Map source->target character
... // Add the rest
}
// LATER IN Code
char[] stringChars = inputString.toCharArray();
for (int i = 0; i < stringChars.length; i++) {
stringChars[i] = substitutions[stringChars[i]];
}
outputString = new String(stringChars);