I am trying to get my Java program to accept blank lines of text as input, as well as displaying them in the final output.
Basically I have made a word scrambling program, that is supposed to take in an unspecified amount of text from the Scanner, scrambling each word individually except for the first and last letters of each word. I have successfully gotten the scrambling and parsing to work, so no worries there. The last spec that I'm working on, is the fact that the user may hit the "return" button entering in a blank line of text.
So, for example, if someone were to enter:
Pizza is my favorite thing to eat
The output would be something like:
Pziza is my fovaitre tnhig to eat
That works perfectly on one line, but if someone were to enter:
I
Like
Animals
Only the last line gets printed and scrambled:
aimnlas
I have tried a few different suggestion I found through research, but most are suggestions for file reading and other things that haven't worked out for me.
This is what I'm doing now:...
Scanner input = new Scanner(System.in);
String text = "";
System.out.println("Enter text to scramble: ");
while(input.hasNextLine()){
text = input.next();
}
System.out.println(scramble(text));
Any help would be greatly appreciated. Thanks everyone =)
EDIT:
OK I'm thinking something I did in my scramble method may be what's preventing me from allowing blank lines. I've looked it over and can't seem to pinpoint it, so if someone could please take a look and let me know what you think I would appreciate it =)
private static String scramble(String txt) {
StringTokenizer st = new StringTokenizer(txt, " ,.!?()-+/*=%##$&:;\"'", true);
String[] tokens = new String[st.countTokens()];
String scrambled = "";
int letter = 0;
int wordlength = 0;
char[] temp;
while(st.hasMoreTokens()) {
tokens[letter] = st.nextToken();
letter++;
}
for(int i = 0; i < tokens.length; i++) {
if(tokens[i].length() <= 3) {
scrambled += tokens[i];
continue;
}
wordlength = tokens[i].length() - 1;
temp = new char[wordlength + 1];
temp[0] = tokens[i].charAt(0);
temp[wordlength] = tokens[i].charAt(wordlength);
ArrayList<Character> c = new ArrayList<Character>();
for(int j = 1; j < wordlength; j++) {
c.add(tokens[i].charAt(j));
}
Collections.shuffle(c);
String z = new String();
for(Character x:c){
z += x.toString();
}
String output = new String(temp[0] + z + temp[wordlength]);
scrambled += output;
}
return scrambled;
}
When reading from System.in, you are reading from the keyboard, by default, and that is an limitless input stream so Scanner.hasNextLine() will always return true.
One solution is to read one line at a time and split each line into words using String.split():
Scanner input = new Scanner(System.in);
String text = "";
System.out.println("Enter text to scramble: ");
boolean done = false;
while (!done) {
text = input.nextLine();
if (text.equals("")) {
done = true;
} else {
performScramble(text);
}
}
...
void performScramble(String line) {
String[] words = line.split("\\s+");
for (String word: words) {
System.out.println(scramble(word));
}
}
Related
I have a string that I split based on delimiter on new lines. I'm wondering now how to check the first word index[0] what word is but can't find a way to actually go trough the elements and check.
May be my approach is totally wrong.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
int ask = 0;
for (int i = 0; i < stringArr.length; i++) {
if (stringArr[0].equals("radio")) {
ask = 10;
} else if (Objects.equals(stringArr[0], "tv")) {
ask = 15;
} else {
System.out.println("Invalid media.");
}
}
System.out.println(ask);
}
Then when I input radio 3 7210>>tv 4 2345>>radio 9 31000>>
The output should be:
10
15
10
Instead - got nothing. Empty line and the program ends.
Is something like this what you want:
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
for (int i = 0; i < stringArr.length; i++) {
int ask = 0;
String[] words = stringArr[i].split(" ");
if (words[0].equals("radio")) {
ask = 10;
System.out.println(ask);
} else if (words[0].equals("tv")) {
ask = 15;
System.out.println(ask);
} else {
System.out.println("Invalid media.");
}
}
Input:
radio 3 7210>>tv 4 2345>>radio 9 31000>>
Output:
10
15
10
First of all, I defined the scanner, not sure if you did that but pretty sure you did.
The elements of stringArr will include the random numbers between each ">>". That means, in each element, we should create a new list split by " " to isolate the "radio" and "tv" as the first element.
Additionally, I just rewrote the else-if statement that checks if the first word of the phrases separated by ">>" is "tv" by using the .equals() method as your original if statement did.
Finally, since you are printing out a number EACH time the code encounters a ">>", we should print out ask inside of the for loop.
EDIT:
Moved the System.out.println(ask) inside of the if and else-if statements so it will only run with valid media.
Other than that your code worked perfectly :> , let me know if you have any further questions or clarifications!
I am trying to write a code to play hangman and it is working correctly but every time when I input a character, it resets my output. Can someone please help.
my code:
import java.util.*;
public class game
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
String ask = "_";
for(int i = 1; i < word.length();i++){
ask = ask + "_";
}
System.out.println(ask);
System.out.println("hint: It is a fruit");
for (int j = 1; j<=15; j++){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (char i : word.toCharArray()){
if(input == i){
System.out.print(input);
continue;
}
System.out.print("_");
}
}
}
}
A small piece of the output:
______
hint: It is a fruit
Enter a character:
a
__a___
Enter a character:
o
o_____
Enter a character:
r
_r____
Enter a character:
n
___n__
Enter a character:
When I enter 'a' it prints it correctly but when I enter some other character it prints that character an not 'a'. Can somebody pls tell me what should I do to get the correct output.
It looks like you are not saving the string with the character added to the game, you are only printing it. You will probably want to do something like add the new character to the string variable _ask rather than printing as you go, then print after the for loop has run. Basically you are not storing the past rounds anywhere.
As mentioned in the other answer you need to remember the characters from previous attempts. This could for example be done like this:
String tempAsk = "";
for (char i : word.toCharArray()){
if(input == i){
tempAsk += i;
} else {
tempAsk += ask.charAt(i);
}
}
ask = tempAsk;
System.out.println(ask);
I think that,
In the loop for (char i : word.toCharArray()),
you should add the character to ask (or have another string variable named ans),
and then print ask at the end of the loop
because you are not updating the value of ask and printing the place of the character in the string,
and when the loop runs a second time it doesn't show the last character that u entered
plus you can have specific hints according to the fruit name using switch case
and maybe have an error pop up when the player enters the wrong character
You can use a character array to check what letters are present so far like so:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
// Create a character array to store the result so far
char[] result = new char[word.length()];
//Fill the array with _
Arrays.fill(result, '_');
System.out.println(new String(result));
System.out.println("hint: It is a fruit");
int numChances = 15;
for (int j = 1; j <= numChances; j++){
System.out.println("Enter a character: ");
char input = in.next().charAt(0);
for (int i = 0; i < word.length(); i++) {
if(word.charAt(i) == input){
//update the array with user's correct response
result[i] = input;
}
}
// Check how we're doing so far. Make a string with the result
String untilNow = new String(result);
// Show user what we have so far
System.out.println(untilNow);
//Check if the user has guessed the word.
if(untilNow.equalsIgnoreCase(word)) {
System.out.println("You win...");
break;
}
}
}
This is my second question here and still a beginner so please bear with me.
I have this code of a very basic hangman type game.I have changed the characters to "-",I am able to get the indices of the input but I am not able to convert back the "-" to the characters entered.
Its an incomplete code.
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
for (int j=0;j<10;j++){ //Asks 10 times for user input
input = inpscanner.nextLine();
int check = line.indexOf(input);
while (check>=0){
//System.out.println(check);
System.out.println(encrypt.replaceAll("-",input).charAt(check));
check = line.indexOf(input,check+1);
}
Here is how it looks like:
You have 10 chances to guess the movie
------
o
o
o
L
L
u //no repeat because u isn't in the movie.While 'o' is 2 times.
I would like to have it like loo---(looper).
How can I do like this "[^ ]","-" in case of a variable?
This might help.
public static void main(String[] args) {
String line = "xyzwrdxyrs";
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
System.out.println(line);
Scanner scanner = new Scanner(System.in);
for (int j=0;j<10;j++) { //Asks 10 times for user input
input = scanner.nextLine();
//int check = line.indexOf(input);
int pos = -1;
int startIndex = 0;
//loop until you all positions of 'input' in 'line'
while ((pos = line.indexOf(input,startIndex)) != -1) {
//System.out.println(check);
// you need to construct a new string using substring and replacing character at position
encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
//check = line.indexOf(input, check + 1);
startIndex = pos+1;//increment the startIndex,so we will start searching from next character
}
System.out.println(encrypt);
}
}
What I'm trying to do in this code is separate each word of a five-word input into the five words that it's made of. I managed to get the first word separated from the rest of the input using indexOf and substring, but I have problems separating the rest of the words. I am just wondering what I could do to fix this.
import java.util.Scanner;
public class CryptographyLab {
public static void main (String [] args) {
fiveWords();
}
public static void fiveWords () {
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 3; i++) {
if (i > 1) {
String clear = input.nextLine();
// I was having some problems with the input buffer not clearing, and I know this is a funky way to clear it but my skills are pretty limited wher I am right now
}
System.out.print("Enter five words: ");
String fW = input.nextLine();
System.out.println();
// What I'm trying to do here is separate a Scanner input into each word, by finding the index of the space.
int sF = fW.indexOf(" ");
String fS = fW.substring(0, sF);
System.out.println(fS);
int dF = fW.indexOf(" ");
String fD = fW.substring(sF, dF);
System.out.println(fD);
int gF = fW.indexOf(" ");
String fG = fW.substring(dF, gF);
//I stopped putting println commands here because it wasn't working.
int hF = fW.indexOf(" ");
String fH = fW.substring(gF, hF);
int jF = fW.indexOf(" ");
String fJ = fW.substring(hF, jF);
System.out.print("Enter five integers: ");
int fI = input.nextInt();
int f2 = input.nextInt();
int f3 = input.nextInt();
int f4 = input.nextInt();
int f5 = input.nextInt();
//this part is unimportant because I haven't worked out the rest yet
System.out.println();
}
}
}
The Scanner class has a next() method that returns the next "token" from the input. In this case, I think calling next() five times in succession should return your 5 words.
As Alex Yan points out in his answer, you can also use the split method on a string to split on some delimiter (in this case, a space).
You're extracting the strings incorrectly. But there is another simpler solution which I'll explain after.
The problem with your approach is that you're not supplying the indices correctly.
After the first round of extraction:
fW = "this should be five words"
sf = indexOf(" ") = 4
fS = fW.substring(0, sF) = "this"
This appears correct. But after the second round:
fW = "this should be five words". Nothing changed
df = indexOf(" ") = 4. Same as above
fD = fW.substring(sF, dF) = substring(4, 4). You get a null string
We see that the problem is because indexOf() finds the first occurrence of the supplied substring. substring() doesn't remove the portion that you substring. If you want to keep doing it this way, you should trim off the word you just substringed.
space = input.indexOf(" ");
firstWord = input.substring(0, space);
input = input.substring(space).trim(); // sets input to "should be five words" so that indexOf() looks for the next space during the next round
A simple solution is to just use String.split() to split this into an array of substrings.
String[] words = fw.split(" ");
If input is "this should be five words"
for (int i = 0; i < words.length; ++i)
System.out.println(words[i]);
Should print:
this
should
be
five
words
while (scan.hasNextLine()) {
String thisline = scan.nextLine();
totalnumber.countthelines++; //linecount works
for(int i = 0; i < thisline.length();i++){
totalnumber.charactercounter++; //chararacter count works
String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length; //does not work
}
}
I am having trouble getting my wordcounter to work(I am already able to count the characters and lines). I have tried many different ways to make it work, but it always ends up only counting the words from the last line of the read in file. Any suggestions on how to make it read every single line instead of just the last?
Thanks
Well :
totalnumber.wordcounter += thewords.length
should be enough !
You just forgot to add the number of words...
So the entiere code is :
while (scan.hasNextLine()) {
String thisline = scan.nextLine();
totalnumber.countthelines++; //linecount works
totalnumber.charactercounter+=thisline.length(); //chararacter count works
String [] thewords = thisline.split (" ");
totalnumber.wordcounter += thewords.length;
}
(Sorry about the multiple edits. Sometime, it's so obvious... ;)
You need:
String [] thewords = thisline.split (" ");
totalnumber.wordcounter += thewords.length;
outside of the loop iterating the characters. Note the += instead of =.
for(int i = 0; i < thisline.length(); i++) {
totalnumber.charactercounter++; //chararacter count works
}
String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length; //does not work