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.
Related
My assignment:
Write a program that reads user input until an empty line. For
each non-empty string, the program splits the string by spaces and
then prints the pieces that contain the letter g, each on a new line.
Expected output:
java programming language
programming
language
programming courses
programming
other courses
(loop must stop from receiving user input, because the last string does not contain letter g)
Here is my attempt and code:
Scanner scanner = new Scanner(System.in);
while (true) {
String userInput = scanner.nextLine();
String[] splitArray = userInput.split(" ");
for (int loopString = 0; loopString < splitArray.length; loopString++) {
if (splitArray[loopString].contains("g")) {
System.out.println(splitArray[loopString]);
} else if (userInput.equals("")) {
break;
}
}
}
I have tried to introduce an empty line within (userInput.equals("")), but loop continues infinitely without breaking.
I have also tried to add else if(!splitArray[loopString].contains("g")) {break;}, but I couldn't find the result I am looking for.
Goal: I want to keep writing sentences that contain the letter G and eventually want to write a sentence that hasn't got the letter G to stop the loop at that point.
How can I approach such a problem and how to solve it in a linear way?
You break is not in the right place. But in any case, you should keep a "containsG" flag and exit if the last line did not have a g
boolean containsG;
do {
containsG = false;
String userInput = scanner.nextLine();
String[] splitArray = userInput.split(" ");
for (int loopString = 0; loopString < splitArray.length; loopString++) {
if (splitArray[loopString].contains("g")) {
System.out.println(splitArray[loopString]);
containsG = true;
}
}
} while (containsG);
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!
public class Test1 {
public static void main(String[] args) {
System.out.println("Give me a word: ");
Scanner console = new Scanner(System.in);
ArrayList<String> arr = new ArrayList<>();
boolean found = true;
while (console.hasNextLine() && found) {
String line = console.nextLine();
if (line.equals("")) {
found = false;
} else {
arr.add(line);
}
}
System.out.println("You said: ");
for (int index = 0; index < arr.size(); index++) {
System.out.println(arr.get(index));
}
}
}
I'd like to print what user typed in whenever the user types enter twice, however this requires three enters to be inputted for some reason. When I remove the console.hasNextLine statement in while loop's condition, it works perfectly fine. Why is this the case?
console.hasNextLine() blocks application flow and waits for input to be received.
1st enter - word is found and found remains == true
2nd enter - word is not found and found is set to == false
3rd enter - is required because your booleans are evaluated in order which they are arranged. so first it'll call console.hasNextLine() and allow user to provide input. THEN it'll check if found == true/false which would == false and would break out of the loop.
an easy solution would be to rearrange your conditions to be
found && console.hasNextLine()
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 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
????? ????????