ending a while loop condition - java

I'm trying to make a simple program that uses a scanner for input and has a while loop that continues taking input until an end character is entered. I want the scanner to take input and add a string to the stack list. I'm trying to figure out why this code doesn't terminate the while loop when a space is typed.
import java.util.Scanner;
public class ReverseString<E> {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Stack<String> stack = new Stack();
//while(scan.hasNext() && !stack.equals(" ")){
// while(!scan.nextLine().equals("")){
while (scan.hasNext()) {
stack.push(scan.next());
if (scan.equals(" ")) {
break;
}
}
System.out.print(stack.pop() + " ");
}
}

You should use nextLine instead
while (scan.hasNextLine()) {
String nextInput = scan.nextLine();
stack.push(nextInput );
if (nextInput.equals(" ")) {
break;
}
}

while (scan.hasNext()) {
stack.push(scan.next());
if (scan.equals(" ")) {
break;
}
}
change to
while (scan.hasNextLine()) {
String value = scan.nextLine();
if (" ".equals(value)) {
break;
}
stack.push(value);
}
scan is a Scanner, it's not a String, scan.equals(" ") would always return false.

You're doing,
if (scan.equals(" ")) {
break;
}
which means you're comparing the Scanner object scan to a space. Try doing the following instead(you have to compare the scan.next() with a space):
import java.util.Scanner;
public class ReverseString<E> {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Stack<String> stack = new Stack();
//while(scan.hasNext() && !stack.equals(" ")){
// while(!scan.nextLine().equals("")){
while (scan.hasNext()) {
String nextInput = scan.next();
stack.push(nextInput );
if (nextInput.equals(" ")) {
break;
}
}
System.out.print(stack.pop() + " ");
}
}

Related

Make the program the you if the word you've inputed in the console is a palindrome or not in Java

I've been trying to make this program work, have the person write a word in the console and make the console have an output saying if that word is or isn't a palindrome.
package sct;
import java.util.Scanner;
public class Assignment3Problem4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a a string: ");
String DAWORD = reader.nextLine();
reader.close();
int n = DAWORD.length();
boolean isPalindrome = true;
for (int i = 0; i < n; ++i) {
if (DAWORD.charAt(i) != DAWORD.charAt(n - i - 1)) {
isPalindrome = false;
break;
}
if (isPalindrome)
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
}
}
}
Sadly, this didn't work and the console doesn't let me input a string, can someone find out why and fix the code?
You shouldn't print whether the word is a palindrome (or not) until after the for loop. That's the only issue I had running the posted code.
Scanner reader = new Scanner(System.in);
System.out.println("Enter a a string: ");
String DAWORD = reader.nextLine();
reader.close();
int n = DAWORD.length();
boolean isPalindrome = true;
for (int i = 0; i < n; ++i) {
if (DAWORD.charAt(i) != DAWORD.charAt(n - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome)
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
You might want to remove reader.close() (as that also closes System.in).
Another approach you could consider is putting your input into a StringBuilder object, reverse it, then check if it equals your input.
Something like:
import java.util.Scanner;
public class StackOverflow {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a string: ");
String DAWORD = reader.nextLine();
reader.close();
if (new StringBuilder(DAWORD).reverse().toString().contentEquals(DAWORD))
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
}
}
Result:
Enter a string:
racecar
This word is a palindrome
You can also use an external apache lang library from here https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.7. Then you can use StringUtils.reverse() method which reverses a string and then compare reversed string with the normal one , like so:
import org.apache.commons.lang3.StringUtils;
public class Main4 {
public static void main(String[] args) {
String str = "kajak";
String str2 =StringUtils.reverse(str);
if (str2.equals(str)){
System.out.println("It's a palidrom");
}
else{
System.out.println("Not a palidorm");
}
}
}

Not printing out correctly

I am trying to write a program that breaks string by '+' sign. For example, if my input is "1+2+3*4". the program will print 1, 2, 3*4. I used \s*\+\s* as my pattern. However, it doesn't print out when it matches the pattern?
private Scanner kbd = new Scanner(System.in);
private String tokenPattern = "\\s*\\+\\s*"; //pattern
public void repl() {
while(true) {
try {
System.out.print("-> ");
String input = kbd.nextLine();
if (input.equals("quit")) break;
Scanner tokens = new Scanner(input);
while(tokens.hasNext(tokenPattern)) { //figure out why its not printing
String token = tokens.next(tokenPattern);
System.out.println(token);
}
tokens.close();
} catch(Exception e) {
System.out.println("Error, " + e.getMessage());
}
}
System.out.println("bye");
}
You should use findWithHorizon

Java palindrome until EOF

I have a program that is supposed to ask the user for a number and it will determine whether it is a palindrome or not. It's supposed to keep asking for numbers until EOF is input - So far it asks for the number twice and doesn't seem to be doing the while loop correctly.
Any insight is appreciated
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
String num = scanner.nextLine();
String reverse = "";
while (scanner.hasNextLine())
{
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
num = scanner.nextLine();
reverse = "";
}
System.out.println("\nProgram ended on request");
}
}
This worked for me; unless you need num or reverse outside the while loop it should work.
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
while (scanner.hasNextLine())
{
String num = scanner.nextLine();
String reverse = "";
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
}
System.out.println("\nProgram ended on request");
}
}
I would separate the palindrome test into its' own method. You could do that in a one line method like
public static boolean isPalindrome(String str) {
return new StringBuilder(str).reverse().toString().equals(str);
}
but I would prefer to iterate the first half of the characters and compare them to the second half in reverse like
public static boolean isPalindrome(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i * 2 <= chars.length; i++) {
if (chars[i] != chars[chars.length - i - 1]) {
return false;
}
}
return true;
}
Then your main can invoke that in an infinite loop (terminating on the lack of input) like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number to check if it is a palindrome:");
if (!scanner.hasNextLine()) {
break;
}
String num = scanner.nextLine();
if (isPalindrome(num)) {
System.out.printf("%s is a palindrome%n", num);
} else {
System.out.printf("%s is NOT a palindrome%n", num);
}
}
System.out.println("Program ended on request");
}

new to programming - error reached end of file while parsing when running code in repl.it/CD18/4

I'm new to programming and trying to write a script that outputs a line containing pangram if the input s is a pangram, or otherwise not pangram. When I compile the script I get an error "reached end of file while parsing." I believe I have balanced parenthesis. Any help would be greatly appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
boolean flag = false;
Scanner key = new Scanner(System.in);
String s = key.nextLine();
String upperCaseStr = s.toUpperCase();
for(char alphabet = 'A'; alphabet <='Z'; alphabet++) {
if(upperCaseStr.indexOf(alphabet)==-1){
flag=true;
break;
}
}
if (flag){
System.out.print("not ");
}
System.out.println("pangram");
}
}
Try this if you want to keep doing multiple inputs:
import java.util.*;
class Main {
public static void main(String[] args) {
boolean continue = true;
while (continue){
boolean flag = false;
Scanner key = new Scanner(System.in);
String s = key.nextLine();
String upperCaseStr = s.toUpperCase();
//if (upperCaseStr.trim() == "QUIT"){
// continue = false;
//} -> don't compare Object's values by their references
continue = "QUIT".equals(s.toUpperCase());
for(char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
if(upperCaseStr.indexOf(alphabet)==-1){
flag=true;
break;
}
}
if (flag){
System.out.print(s + " is not a pangram");
}
else
System.out.println(s + " is a pangram");
}
}
}
Though you need to do something to break out the while loop, like look for if the user types quit or something, but should help
[Edit] Added quit clause

Multi-word scanner input in java?

So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}

Categories

Resources