JAVA: storing input into array - java

I need to write a program where the program would generate random letter and i would need to store this random character into an array
char[] arrayRandom = new char[10];
for (int i = 0; i < 8; i++) {
randomNumLet = (generator.nextInt(20) + 1);
System.out.print(arrayRandomLetter[randomNumLet] + " ");
arrayRandomLetter[randomNumLet] = arrayRandom[i];
}
is there anything wrong with my code?
because when i run this and printed the array i get boxes for all the values in the array and there are some letter that this line of code cannot print
System.out.print(arrayRandomLetter[randomNumLet] + " ");
Thanks

You're assigning an element of arrayRandomLetter a value from arrayRandom. As you never initialize arrayRandom, its values are all 0. 0 is not the value of a printable character, hence the boxes.
An easy way to pick a random character is like this:
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char randomChar = chars.charAt(random.nextInt(chars.length()));

You are trying to print arrayRandomLetter before it is assigned.

I'm not going to give you the answer, but I will give you a hint:
(char)('A' + 1) is 'B'
#fastcodejava's answer explains why you are seeing "boxes" -- rendering the ASCII NUL character.
#Mark Peters is also correct, but that's not the simplest solution.

Related

How to replace first and middle char in string

I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.

Length of an array that was initialized using a split string?

I have the following code to split a String of a list of words separated by spaces. The string is split and used to populate the array. If I use the .length method, will it return the amount of split strings? As in, would it be similar to the String.length method that counts the amount of characters and returns that value?
I want to have the program increment the array position by one each time it's run, but I want it to reset to 0 if it already used the last word, so it circles back and starts with the first word again.
Would this bit of code reset the word position to 0 when it has already used the last word in the array?
String wordsList[] = words.split(" ");
this.currentWord = wordsList[wordPos];
if(wordPos < wordsList.length)
wordPos++;
else
wordPos = 0;
If you use array.length on an array doesn't it tell you what the length is?
The answer is yes. Also, the .length is a property and not a method.
Take a look at this going over the .length property with a bit more detail. Cheers.
If I understand correctly, It sounds like you want to use a for loop like this?:
String words = "Blah blarg bloob"
String wordsList[] = words.split(" ");
String currentWord = "";
for (int i = 0; i < wordsList.length; i++){
if (currentWord !=null && currentWord.equals(wordsList[i])) {i = 0;}
currentWord = wordsList[i];
}

How do I add int. to char and string to get "abc" in the output? (For Java)

So I was given this formatted problem and told to fix the format in order to get the output.
int x = 0;
int y = 1;
char p = 'a';
String s = "c"
The format is
(p + x + p + y + s)
And I'm supposed to change this (as long as I use x,y,p,s) to make the output be "abc."
How do I do this? The farthest I've gotten is that
System.out.println(p=(char)((int)p+x));
And that makes the output "a".
What do I do? Help please! I'm a very new programmer.
Thanks in advance.
I have tried the following which works:
int x = 0;
int y = 1;
char p = 'a';
String s = "c";
StringBuilder builder = new StringBuilder();
builder.append((char)((int)p+x)).append((char)((int)p+y)).append(s);
System.out.println(builder.toString());
It prints: abc
System.out.println(p + String.valueOf((char)(p+y)) + s);
Thanks for asking this question, I probably would have never known that String constructor doesn't take only a single character as a parameter.
For clarity:
String.valueOf() returns the character p+y as a String.
When you use + between all the three, they get concatenated.
Edit- A note on what you were doing with your code is that in the line:
System.out.println(p=(char)((int)p+x));
You here are overwriting the value of character variable p which already stores the value of character 'a' with the value of p+x. Here, x is 0 so it will be added to the ASCII value of character stored in p, i.e 'a' and results in the same.
Another note is that even if x was something else other than 0, you didn't have to first type cast into (int), you could have directly type casted it into (char). And since the variable where you are storing that operation is a character itself, you don't need any type casting at all!

Java: Next character in String

I have one String generated of random characters that will encrypt another String given by the user by adding the first character from the String with the first character of the given String. It's working fine, but if the user were to enter multiple words with spaces in between, I want to choose the next character of the first String rather than code the space itself. Is that possible? This is what I have:
(random is the coded string and sentenceUpper is string given by user)
public static void encrypt(String sentenceUpper){
String newSentence = "";
for(int i = 0; i < sentenceUpper.length(); i++){
char one = random.charAt(i);
char two = sentenceUpper.charAt(i);
if(one < 'A' || one > 'Z'){
two = sentenceUpper.charAt(1 + i);}
char result = (char)((one + two)%26 + 'A');
newSentence += "" + result;
}
EDIT FOR BETTER EXPLANATION:
I have:
String random = "WFAZYZAZOHS";
I would like to code user input:
String upperCase: "YOU GO";
So, I'm going to take Y + L = U, etc...
to get :
"UTUSEN
"
But I see that there's a space in "YOU GO" , So I'd like to change it to:
WFA ZY + YOU GO = UTU SE.
I hope that's better explained.
The simplest way to do this would probably be to use an if statement to run the code in the loop only if the character is not a space. If you don't want to skip the character in the random string, you would need a separate variable to track the current character index in that string.
Example: Put this after defining one and two and put the rest of the loop inside it:
if(two==' '){
...
}
Then, add the space in the output:
else{
newSentence+=" ";
}

How can I compare 2 strings character by character?

for a college project, I am doing a spelling test for children and i need to give 1 mark for a minor spelling error. For this I am going to do if the spelling has 2 characters wrong. How can I compare the saved word to the inputed word?
char wLetter1 = word1.charAt(0);
char iLetter1 = input1.charAt(0);
char wLetter2 = word1.charAt(1);
char iLetter2 = input1.charAt(1);
I have started out with this where word1 is the saved word and input1 is the user input word.
However, if I add lots of these, if the word is 3 characters long but I am trying to compare the 4th character, I will get an error? Is there a way of knowing how many characters are in the string and only finding the characters of those letters?
Just use a for loop. Since I'm assuming this is about JavaScript, calling charAt() with an index out-of-bounds will just return the empty string "".
To avoid a out-of-bounds exception you'll have to iterate up until the lower of the lengths:
int errs = Math.abs(word1.length - input1.length);
int len = Math.min(word1.length, input1.length);
for (int i = 0; i < len; i++) {
if (word1.charAt(i) != input1.charAt(i)) errs++;
}
// errs now holds the number of character mismatches

Categories

Resources