I am writing a simple code that takes an input read by the scanner and saved into a variable word.
It is required for an assignment to create a separate method that will take that string and convert all the letters to a '?' mark. At the spaces, however, there should be a space.
The problem is that every time I run this code, it stops at the space.
Here is my code:
import java.util.Scanner;
public class commonPhrase {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String word;
System.out.print("Welcome to the Guessing Game.");
System.out.println("");
System.out.println("Please enter a common phrase");
word = input.next();
createTemplate(word);
}
public static String createTemplate(String word) {
String sPhrase = "";
for (int i=0; i < word.length(); i++) {
if (word.charAt(i) == ' '){
sPhrase += " ";
}
else {
sPhrase += "?";
}
}
System.out.println(sPhrase);
return sPhrase;
}
}
And here is a sample run of it:
Welcome to the Guessing Game.
Please enter a common phrase.
Why wont it add spaces!!!!!!!
???
You call next() on the Scanner, but that method grabs the next token, and by default it's separating tokens by whitespace. You only gathered one word.
Call nextLine() instead, to grab the text of the entire line.
word = input.nextLine();
Sample run with fix above:
Welcome to the Guessing Game.
Please enter a common phrase
Stack Overflow
????? ????????
Related
Hi I'm finishing an assignment, however I'm getting the wrong output.
The goal of the project is to reverse a string.
So it's supposed to take in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
the output is:
ereht olleH
yeH
My code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
while (true) {
str = scnr.nextLine();
if (str.equals("quit") || str.equals("Quit") || str.equals("q")) break;
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
}
My current code is that however output is coming back as:
Input
Hello there
Hey
done
Output
ereht olleH
yeH
enod
Expected output
ereht olleH
Cannot figure out what I'm doing wrong.
/*
I don't know what you know, so I am not sure how your professor
wants you to complete this, but I will do what comes to mind for myself.
*/
//Instead of while(true) I like to use do while, which runs once automatically, and continues running until a condition is met
do {
str = scnr.nextLine();
int i = 0;
//This isn't the cleanest way to solve this, especially because it doesn't remove the space before done.
//You could add more if statements for that, but the cleanest way would be to split the words into a String array
// and check if any of the values of the array equal done, and remove it before flipping it around
if(str.toLowerCase().contains("done"))
i = 4;
else if(str.toLowerCase().contains("d"))
i = 1;
while (i < str.length()) {
System.out.print(str.charAt(str.length() - i - 1));
i++;
}
System.out.println();
}
while (!str.toLowerCase().contains("done") || !str.toLowerCase().contains("d")); //This replaces that if statement from before
you are using .equals() to check if the line is equal to one of your break words, but you are giving it the input Hello there Hey done, so it will not detect the the break word (ignoring the fact that you gave it done, not quit, I'm assuming that was a typo), so to detect that, you would either have to check if the line contains that word and if so, toggle a boolean and remove the word and any text after it from the line, e.g:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
boolean end = false;
while (!end) {
str = scnr.nextLine();
if (str.contains("quit") || str.contains("Quit") || str.contains("q")) { // checks if str contains the word, so if you write "hello quit" it will still detect it.
str = str.substring(0,str.toLowerCase().indexOf("q")); // cuts off the string from the q.
end = true;
}
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
otherwise, you would just need to add the quit to the line after, and then it would work, so you would put in Hello there Hey then press enter, and then quit, and that will work.
I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.
My assignment is to write a program to scramble a word while maintaining the same first and last letter and only swapping two letters, then prompt the user to continue if they wish.
Example: userInput = bacon | Output = bcaon
I've attached an imagine of my program, there may be several issues, but as it stands I can't really run it due to the errors in the image. I'm really confused because I got a TA to help me on this assignment, and they seemed to think this would definitely work, but as you can see it does not.
I would really appreciate if someone could tell me what exactly is wrong and why. And if you have anything to add to make this program work, I'd really, really appreciate that too, but bottom line is I just want to understand what's wrong and why.
import java.util.Scanner;
import java.util.Random;
public class FreeStyle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // Importing and initializing keyboard to 'in'
System.out.println("Please enter a word to be scrambled"); // Asking user for a word
String word = in.next(); // Initializing the user's input
System.out.println(swapLetters(word));
System.out.println("Would you like to enter another word? y/n");
String answer = in.next();
boolean userDone = true; //Using a Boolean statement to ask the user if they are done enter words or not
while (userDone) {
if (answer.equals('y')) {
System.out.println("Please enter a new word"); //Ask user for new word to scramble
word = in.nextLine(); //New initialization for 'word'
} else if (answer.equals('n')) { //If user types 'n', loops then breaks because while(userDone) is false
userDone = false;
} else {
System.out.println("Invalid input, please enter more than 3 letter words."); // The logic doesn't flow or apply to words that are less than 4 letters, so this catches that error and notifies the user
}
}
}
private static String swapLetters(String word) { //Private method used for the program only, no need to involve the user
Random r = new Random(); //Using random instead of math floor
//int arraysize = word.length();
int a = r.nextInt(word.length()-2)+1;
int b = r.nextInt(word.length()-2)+1;
//String word2 = word.substring(a, a+1);
String word2 = word.substring(0, a) + word.charAt(b)+word.substring(a+1, b)+word.charAt(a)+word.substring(b+1);
return word2;
}
Several points:
Why not use something already done exactly for what you are trying to do - Collections.shuffle? See comments in the code for understanding how it works.
You can't use equals() between a String and a char (' ' are for chars, " " are for Strings). Simple fix - just put your 'y' into "y", same for 'n'.
I've refactored the code at the beginning that we used to get user input and then scramble into a separate method, so we can reuse it again - getInputAndScramble.
And finally, I've used a do-while loop to keep looping until the user stops the loop with the "n" letter.
Please see my comments in the code, hopefully will clear things up.
public class Scrambler {
public static void main(String[] args) {
boolean userDone = true;
String word;
Scanner in = new Scanner(System.in);
getInputAndScramble(in); //Extracted method to get Scanner input and scramble
do {
System.out.println("Would you like to enter another word? y/n");
word = in.next();
while (userDone) {
if (word.equals("y")) {
getInputAndScramble(in);
break;
} else if (word.equals("n")) {
userDone = false;
} else {
System.out.println("Invalid input, please enter more than 3 letter words.");
}
}
} while (userDone); //continue until "n"
}
private static void getInputAndScramble(Scanner in) {
System.out.println("Please enter a word to be scrambled");
String word = in.next();
System.out.println(swapLetters(word));
}
private static String swapLetters(String word) {
/* Convert word into an ArrayList of characters.
Create ArrayList size of word,
convert String word into a char array and insert every char in
the char array into our ArrayList.
*/
ArrayList<Character> chars = new ArrayList<>(word.length());
for (char c : word.toCharArray()) {
chars.add(c);
}
//Shuffle, omitting first and last letters
Collections.shuffle(chars.subList(1, chars.size()-1));
//Add shuffled letters into an array to output as a word entity
char[] shuffled = new char[chars.size()];
for (int i = 0; i < shuffled.length; i++) {
shuffled[i] = chars.get(i);
}
//Return shuffled String
return new String(shuffled);
}
}
You are assuming that the two random number a and b have the property that a < b. What if a >= b? Then word.substring(a+1, b) will throw an error.
To fix it, just make sure that a < b is maintained (regenerating, swapping, etc.).
But to be sure, there are more than just this bug in your code. For example, using next(), comparing String with char, using wrong newline character, not striping newline character, and so on. You might want to add some print statements in your code you see what is actually happening.
Well, as for the swapping function, something like that should work:
private static String swapLetters(String word) {
char[] temp = word.toCharArray();
char swapHelper;
Random r = new Random();
int a = r.nextInt(word.length()-2)+1;
int b = r.nextInt(word.length()-2)+1;
swapHelper = temp[a];
temp[a] = temp[b];
temp[b] = swapHelper;
word = String.copyValueOf(temp);
return word;
}
Basically, im converting string to char array so i can operate on them with ease. A and B are variables that contain index of letters that should be swapped. After that, array is converted back to string and returned.
I have seen similar questions to this problem and the answer on the Stack Overflow did not seem to satisfy the problem. I heard that you need to use use.Delimeter, however, I never used it before and want to know how to use it to exclude punctuation from a string that the user inputs. The assignment prompt question is here:
Change the CountWords program (Listing 3.10) so that it does not include punctuation characters in its character count. Hint: You must change the set of delimiters used by the StringTokenizer class.
Here is Listing 3.10:
import java.util.Scanner;
import java.util.StringTokenizer;
public class ThreeEight {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int wordCount = 0, characterCount = 0;
String line, word;
StringTokenizer tokenizer;
System.out.println("Please enter text (type DONE to quit):");
line = scan.next();
while (!line.equals("DONE")) {
tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word = tokenizer.nextToken();
wordCount++;
characterCount += word.length();
}
line = scan.next();
}
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + characterCount);
}
}
Output:
Please enter text (type DONE to quit):
Hello World! ##$%^&():"<>?~/\
DONE
Number of words: 3
Number of characters: 29
As you can see, it does not count punctuation, what code would I use to exclude the punctuation? I used use.Delimeter but it said that it was an invalid method.
import java.util.*;
public class VowelCounter
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Input a series of characters: ");
String letters = keyboard.next();
int count = 0;
for (int i = 0; i < letters.length(); i++)
{
char characters = letters.charAt(i);
if (isVowel(characters) == true)
{
count++;
}
}
System.out.println("The number of vowels is: " + count);
}
public static boolean isVowel(char characters)
{
boolean result;
if(characters=='a' || characters=='e' || characters=='i' || characters=='o' || characters=='u')
result = true;
else
result = false;
return result;
}
}
The code works but im suppose to input "Spring break only comes once a year." which if i do with the spaces my program will only find the vowels of Spring. how do i make it so it will skip the spaces and read the whole sentence.
This is your problem:
String letters = keyboard.next();
It has nothing to do with the vowel-counting part - but everything to do with reading the value. The Scanner.next() method will only read to the end of the token - which means it stops on whitespace, by default.
Change that to
String letters = keyboard.nextLine();
and you should be fine.
You should verify this is the problem by printing out the string you're working with, e.g.
System.out.println("Counting vowels in: " + letters);
When you do:
String letters = keyboard.next();
The Scanner stops reading at the first whitespace.
To read the complete phrase until you press enter, you should use nextLine() instead:
String letters = keyboard.nextLine();
Just use
String letters = keyboard.nextLine();
instead of
String letters = keyboard.next();
This is because .nextLine() will read line by line so that you can have your complete statement in latters. Hope this will help you