I need to remove "the enter a sentence to be reversed" bit at the top and the bottom, because it shouldn't be there. Below is my code and the console message that needs to be fixed.
import java.util.Scanner;
public class ques1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sentence;
do {
String newsent = "";
System.out.println("\nEnter a sentence to be reversed: ");
sentence = scanner.nextLine();
for (int i = sentence.length() - 1; i >= 0; i--) {
newsent = newsent + sentence.charAt(i);
}
System.out.print(newsent);
} while (!sentence.equals("exit"));
}
}
Enter a sentence to be reversed: (want to remove this)
Enter a sentence to be reversed:
Hi how are you?
?uoy era woh iH
Enter a sentence to be reversed:
I am doing great, thanks.
.sknaht ,taerg gniod ma I
Enter a sentence to be reversed:
Exit
tix
Enter a sentence to be reversed: (Want to remove this)
Your input is wrong and it doesn't match with the string check "exit". The loop will continue till you feed the input as "exit".
Related
create a java program that will ask a user to input a word and reverse it using the recursive method. It should ask the user to try again y or n
I have missing code I don't know what should I put on line 14.
package reverseword;
import java.util.Scanner;
public class ReverseWord {
public static void main(String[] args) {
String tryAgain = "Y";
do{
String reversedString = "";
System.out.print("Enter string to reversed: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
reversedString = reverseString(input);
System.out.println("Reversed String : "+reversedString);
System.out.println("Try again? enter \"Y/N\": ");
tryAgain = input.next();
}while(!tryAgain.equals("N"));
}
public static String reverseString(String input){
if(input.isEmpty())
return input;
return reverseString(input.substring(1)) + input.charAt(0);
}
}
Enter string to reversed:lala
Reversed String : alal
Try again? enter \"Y/N\": Y
Enter string to reversed:
//if the answer is no:
Enter string to reversed:lala
Reversed String : alal
Try again? enter \"Y/N\": N
Bye!
I assume that 14th line is
tryAgain = input.next();
It does not compile because input is String, you meant to use Scanner sc. Try this:
tryAgain = sc.next();
My Computer Science class assignment requires that I write a program which determines if a word or phrase is a palindrome (is the same forward and backwards, ie "noon"). As part of this, I have to write a method which removes all punctuation and spaces, so they are not counted in determining if it is a palindrome. It also runs on a loop, allowing the user to input as many phrases they want until they indicate they're done. My problem is that when the word/phrase entered contains a space, somehow it terminates the loop and doesn't allow more input. The program works just fine, as long as the input has no spaces. Here's my code:
In class RecursivePalindrome:
public String removePunctuation(String s){
s = s.replaceAll("\\.","");
s = s.replaceAll("!","");
s = s.replaceAll(",","");
s = s.replaceAll(" ","");
s = s.replaceAll("'","");
s = s.replaceAll("-","");
s = s.replaceAll("\\?","");
return s;
}
public boolean isPalindrome(String s) {
s = removePunctuation(s);
String firstChar = s.substring(0,1);
String lastChar = s.substring(s.length()-1);
if (s.length() == 1){
return true;
}
if (s.length() == 2 && firstChar.equalsIgnoreCase(lastChar)){
return true;
}
if (!firstChar.equalsIgnoreCase(lastChar)){
return false;
}
return isPalindrome(s.substring(1, s.length() - 1));
}
In class RecursivePalindromeTester:
public static void main(String[]args){
//Create objects
Scanner in = new Scanner(System.in);
RecursivePalindrome palindrome = new RecursivePalindrome();
//Output
for (String again = "Y"; again.equalsIgnoreCase("Y"); again = in.next())
{
//Prompt for input
System.out.println();
System.out.print("Enter a word or phrase: ");
String phrase = in.next();
//Output
if (palindrome.isPalindrome(phrase)){
System.out.println("This is a palindrome.");
}
else
System.out.println("This is not a palindrome.");
System.out.print("Another word or phrase? (Y/N): ");
}
}
The output should be:
"Enter word or phrase: <input>mom- mom!
This is a palindrome
Another word or phrase? (Y/N): <input>Y
Enter a word or phrase: <input>Dog?
This is not a palindrome
Another word or phrase? (Y/N): <input>N"
Terminate
But instead I get:
"Enter word or phrase: <input>mom- mom!
This is a palindrome
Another word or phrase? (Y/N):"
Terminate
I really have no idea why a space would cause the loop to terminate, especially since it doesn't do this with any other punctuation.
Totally agreed with #Ilya Bursov comment,
You should use in.nextLine() instead of in.next() , there are big difference between both methods
next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line
Try like this ,
class RecursivePalindromeTester {
public static void main(String[] args) {
//Create objects
Scanner in = new Scanner(System.in);
RecursivePalindrome palindrome = new RecursivePalindrome();
//Output
for (String again = "Y"; again.equalsIgnoreCase("Y"); again = in.nextLine()) {
//Prompt for input
System.out.println();
System.out.print("Enter a word or phrase: ");
String phrase = in.nextLine();
//Output
if (palindrome.isPalindrome(phrase)) {
System.out.println("This is a palindrome.");
}
else
System.out.println("This is not a palindrome.");
System.out.print("Another word or phrase? (Y/N): ");
}
}
}
Does my reverse method only work if I input a series of words all at once?
My task was to: Write a complete method that reads a series of Strings from the user. The user enters "end" to stop inputting words. Then, output the Strings in reverse order of how they were entered. Do not output the String “end”.
Use a stack to accomplish this task. Invoke only the methods push, pop, peek, and isEmpty on the stack object.
Here is how it is supposed to run:
Enter a word or 'end' to quit: Hello
Enter a word or 'end' to quit: Java
Enter a word or 'end' to quit: World
Enter a word or 'end' to quit: end
You entered (in reverse):
World
Java
Hello
But mine runs:
Enter a word or 'end' to quit: Hello
Enter a word or 'end' to quit: Java
Enter a word or 'end' to quit: World
Enter a word or 'end' to quit: end
You entered (in reverse): end
Here is what I have so far:
import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Pattern;
public class Stack1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "end";
do {
System.out.printf("Enter a word or 'end' to quit: ");
input = scanner.nextLine();
if (input == null || input.length() == 0) {
System.out.println("Invalid! Try again...");
return;
}
} while(!input.equalsIgnoreCase("end"));
String reverse = reverse(input);
System.out.printf("You entered (in reverse): %s", reverse);
}
private static String reverse(String inputString) {
String[] str = inputString.trim().split(Pattern.quote(" "));
Stack stack = new Stack();
for(String input : str) {
stack.push(input);
}
StringBuilder builder = new StringBuilder();
while( !stack.isEmpty()) {
builder.append(stack.pop()).append(" ");
}
return builder.toString();
}
}
read input.
push it in stack.
if input equals "end" then stop reading input.
pop stack until stack gets empty.
Code
import java.util.Scanner;
import java.util.Stack;
public class Stack1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = "";
Stack stack = new Stack();
while(true){
System.out.printf("Enter a word or 'end' to quit: ");
input = in.next(); // to read a word use next() method.
if(input.equalsIgnoreCase("end")){ break; }
if(!input.equals("")) stack.push(input);
}
System.out.println("You entered (in reverse): ");
while(!stack.isEmpty())
System.out.println(stack.pop());
}
}
Your loop is overwriting input on each iteration. To make it work with your reverse() method, you'll want to concat each word incrementally with a space:
String input = "";
while (true) {
System.out.printf("Enter a word or 'end' to quit: ");
String next = scanner.nextLine();
if (next == null || next.length() == 0) {
System.out.println("Invalid! Try again...");
return;
}
if (next.equalsIgnoreCase("end")) {
break;
}
input += next + " ";
}
Alternatively, you can populate the stack directly in the loop and skip the string splitting:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack<String> stack = new Stack<>();
while (true) {
System.out.printf("Enter a word or 'end' to quit: ");
String next = scanner.nextLine();
if (next == null || next.length() == 0) {
System.out.println("Invalid! Try again...");
return;
}
if (next.equalsIgnoreCase("end")) {
break;
}
stack.push(next);
}
System.out.println("You entered (in reverse):");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
Note that the latter solution correctly reverses multi-word inputs, whereas the concatenation approach can't differentiate between lines and words.
This is because your input variable contains only "end". Thus whenever you call reverse function ,it only reverses end String.
String reverse = reverse(input);//input="end"
the problem comes from this place
#Toby Speight thanks for your advice.
by the way I am a English newcomer,I'm pleased to accept any suggestion.
What I'm trying to say is to learn debug your program when you meet problems.In this case: you want the program print a reversed String to the console .but you got a strange answer.now you need to consider where the answer maybe comes from ?
and then just print it before you use it like below
String reverse = reverse(input);//we said you think the problem comes from this place.
System.out.printf("%s%n",input);//this is a key statement to debug--just print it
Now you and then consider where input is not what you want? and then just consider where input comes from?keep on doing this ,and then you can find where
your problem comes from.
On the other hand ,there have a lot of method to debug,you can use IDE debug your program and it will be more efficient ,what's more you can use a log file and so on.
You're using a do-while loop, which is why "end" gets added to the array.
To reverse the string, you can either use a for loop and reverse it yourself:
StringBuilder reverseStr = new StringBuilder();
for (int i = str.size - 1; i >= 0; i--) {
reverseStr.append(str[i]);
}
Or use something like Apache Commons Lang StringUtils.reverse().
Im writing a program that first takes input from the user as an int then constructs an array that the user then types in individual characters that builds a string from that. i've written some code but I've come up with a form of writer's block and i don't know where to go from here. any help is greatly appreciated.
EDIT: im stuck on getting the string from the input into the array im getting an error where a method is not applicable. ill make in the code where the error is happening.
Example:
How many strings? 2
Enter string #1:
Enter an alphabetic string followed by enter: t
Enter an alphabetic string followed by enter: e
Enter an alphabetic string followed by enter: s
Enter an alphabetic string followed by enter: t
Enter an alphabetic string followed by enter: %
Enter string #2:
Enter an alphabetic string followed by enter: one
Enter an alphabetic string followed by enter: two
The strings you entered are:
test onetwo
code is below:
package workfiles;
//George Flamburis
import java.util.*;
public class Hw3 {
private static Scanner numScan;
public static void main(String[] args) {
int numstring=0;
numScan = new Scanner(System.in);
while (numstring <= 0 ){
System.out.print("How many strings? ");
numstring = numScan.nextInt();
if (numstring<1){
System.out.print("Please enter a positive (> 0) number.");
}
}
String[] stringarray = new String[numstring];
for (int i = 0; i < numstring; i++) {
//ERROR HAPPENING IN THIS CODE BELOW!!!
stringarray[i] = inputAlphaString();
}
numScan.close();
}
public static String inputAlphaString(Scanner aScan) {
Scanner strScan = new Scanner(System.in);
String t = "a";
String hold = "";
while(t.matches("[a-zA-Z]+")){
System.out.println("Enter an alphabetic string followed by enter: ");
t = strScan.nextLine();
hold = hold + t;
}
strScan.close();
return hold;
}
//added [] into the method name and int to i
public static void printSArray(String[] sArray) {
for (int i = 0; i <= sArray.length; i++)
System.out.print(sArray[i] + " ");
System.out.println();
}
}
I am having some trouble preventing the user from entering numbers with the scanner class. This is what I have:
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word;
String inverse = "";
System.out.println("Write a sentence or word: ");
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Not valid! Try again: ");
input.nextLine();
}
word = input.nextLine();
word = word.replaceAll("\\s+","");
word = word.toLowerCase();
int length = word.length();
length = length - 1;
for (int i = length; i >= 0; i--) {
inverse = inverse + word.charAt(i);
}
if (word.equals(inverse)) {
System.out.println("Is a palindrome.");
} else {
System.out.println("Is not a palindrome.");
}
}
}
Basically when I enter a word or sentence I want it to check if it has any numbers anywhere in the input, if it has then you need to enter another one until it doesn't. Here is an example of output:
Write a sentence or word:
--> 11
Not valid! Try again:
--> 1 test
Not valid! Try again:
--> test 1
Is not a palindrome.
As you can see it works for most cases, but when I enter a word FIRST and then a space followed by a number it evaluates it without the number. I am assuming this is happening because in the while loop is checking for only input.hasNext but it should be input.hasNextLine I believe to check the entire string. However I cannot have any arguments if I do that. Help much appreciated!
Change your regex from: [A-Za-z]+ to ^[A-Za-z]+$ in order to prevent numbers anywhere in the input-string