I'm creating a program to call another code that creates an RPN Calculator
RPNCalculator Calculator = new RPNCalculator();
System.out.println("Please enter a valid post-fix expression one token " +
"at a time with a space between each token (e.g. 5 4 + 3 2 1 - + *)");
System.out.println("Each token must be an integer or an operator (+,-,*,/)");
Scanner reader= new Scanner(System.in);
System.out.println();
System.out.println("That expression equals " + result);
System.out.println();
while (true)
{
equation = reader.nextLine();
result=Calculator.evaluateEquation(equation);
}
However when the program runs, it does not even give the chance to input anything and will return "That expression equals 0"
You have your while loop on the wrong side of the System.out.println()'s.
Scanner reader= new Scanner(System.in);
while (true)
{
equation = reader.nextLine();
//YOU ALSO need a reason to break out of this loop.
//LIKE IF equation == "EXIT" or "0"
//BREAK
result=Calculator.evaluateEquation(equation);
}
System.out.println();
System.out.println("That expression equals " + result);
System.out.println();
Related
I have created a program that allows a user to keep guessing numbers until they either guess the correct number or enter end. I have used a do-while loop to do this. When I create a new scanner inside the loop body it works as expected. However if I create it outside the loop body, it works fine if the input is integers or the first input is end However if the input end follows integer inputs it doesn't
pick up the nextLine() until the next loop. Is there a way to do this without having to creat a new scanner object each time.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
do {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.nextLine();
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}while(number != answer && !(input.equals("end")));
}
Example output for when end follow an integer input:enter code here
number is: 3
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
end
input is:
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
input is: end
Hope you enjoyed the game
input before while is: end
you can solve this by using a while loop .
See the following code.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
while(!input.equals("end")) {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.next(); //Edited here . Changed nextLine() to next().
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}
}
In here , at first , input will always be empty String . On while loop, it gets assigned to your String input i.e, end . Till it encounters end , your loop will be running.
Edited
Change input=sc.nextLine(); to input=sc.next(); . This is because , your scanner waits for next Line and doesn't consider "end" as input string .
I'm trying to make a system that asks the user how many times they want a phrase to be repeated and then it checks if the answer is an integer or a string. The program works well when I don't try to implement this system and leave it just at asking the phrase and how many times it should be repeated but it falls appart when I try to check if the amount of times is an integer or not.
import java.util.*;
public class Phrase {
public static Scanner phraseScan = new Scanner (System.in);
public static Scanner amountScan = new Scanner (System.in);
public static void main (String[] args ) {
System.out.println("What phrase do you want repeated?");
String phrase = phraseScan.nextLine();
int phraseLoops = 0;
System.out.println("How many " + phrase + "s" + " do you want?");
int desiredPhraseLoops = amountScan.nextInt();
for (;;) {
if (!amountScan.hasNextInt()) {
System.out.println("Integers only please");
amountScan.next();
}
desiredPhraseLoops = amountScan.nextInt();
if (desiredPhraseLoops >= 0) {
System.out.println("Valid amount!");
continue;
} else {
break;
}
}
System.out.println(desiredPhraseLoops + " " + phrase + "s coming your way!");
do {
System.out.println(phrase);
phraseLoops++;
} while (phraseLoops != desiredPhraseLoops);
System.out.println("You printed " + phraseLoops + " " + phrase + "s" );
}
}
What I've tried:
try {
desiredPhraseLoops = amountScan.nextInt();
} catch (InputMismatchException exception) {
System.out.println("This is not an integer.");
}
if (!amountScan.hasNextInt()) {
System.out.println("Good.");
} else {
System.out.println("Enter an Integer please.");
}
Any time I tried anything, it would ask which phrase I wanted and how many times I wanted it repeated. And then the program just stopped afterward, no matter if I put in an integer or a string, it just didnt give me any other prompts.
The output is this:
What phrase do you want repeated?
Test
How many Tests do you want?
3
And that's it.
To begin with, just use one Scanner object. You don't need more than that for keyboard input.
If you like, you can just stick with the Scanner#nextLine() method, for example:
Scanner userInput = new Scanner(System.in);
String phrase = "";
while (phrase.equals("")) {
System.out.println("What phrase do you want repeated?");
phrase = userInput.nextLine();
// VALIDATION:
// Was anything other than a empty string (spaces)
// or longer than 2 characters supplied?
if (phrase.trim().equals("") || phrase.length() < 3) {
// Nope!
System.err.println("Invalid Input!. Enter a proper phrase!");
phrase = "";
}
// Yes, allow the prompt loop to exit.
}
String phraseLoopsNumber = "";
while (phraseLoopsNumber.equals("")) {
System.out.println("How many " + phrase + "s" + " do you want?");
phraseLoopsNumber = userInput.nextLine();
// VALIDATION:
// Did the User supply a string representation of an integer value?
if (!phraseLoopsNumber.matches("\\d+")) {
// Nope!
System.out.println("Invalid Input (" + phraseLoopsNumber + ")! An integer value is expected!");
phraseLoopsNumber = "";
}
// Yes he/she/it did...Allow prompt loop to exit.
}
int numberOfLoops = Integer.parseInt(phraseLoopsNumber);
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
In the above code, the String#matches() method was used along with a small Regular Expression (RegEx). The "\\d" expression passed to the matches() method checks to see if the string it is working against contains all (1 or more) digits.
If however you're hell bent on using the Scanner#nextInt() method then you can do it this way:
int numberOfLoops = -1;
while (numberOfLoops == -1) {
System.out.println("How many " + phrase + "'s" + " do you want?");
// Trap any input errors against the Scanner.nextInt() method...
// This would be a form of validation.
try {
numberOfLoops = userInput.nextInt();
// Consume the newline from ENTER key in case a nextLine() prompt is next.
userInput.nextLine();
} catch (Exception ex) {
System.out.println("Invalid Input! An integer value is expected!");
// Consume the newline from ENTER key in case a nextLine() prompt is next.
// The first one above would of been skipped past if nextInt() threw an exception.
userInput.nextLine();
numberOfLoops = -1;
continue; // continue loop so as to re-prompt
}
// Further Validation:
// Did the User supply a number greater than 0?
if (numberOfLoops < 1 ) {
// Nope!
System.out.println("Invalid Input (" + numberOfLoops + ")! A value 1 or greater is expected!");
numberOfLoops = -1;
}
// Yes he/she did...Allow prompt loop to exit.
}
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
There are two places where there is a problem:
The first one sc.nextInt() method - which only reads the int
value by keeps current reading buffer on the same line. So to
ignore/skip everything what is after int on the input line (which is
probably \n or \r\n if you only enter the number) you have to
use sc.nextLine().
The second one is sc.next() method - which
only reads first token(or simply word) from your line. That is
probably why you only get "less" value assigned to response
and that will never be .equals to "less than". So you will
have to replace sc.next() one with sc.nextLine() and remove
unnecessary sc.nextLine() from the next line.
Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.
If my explanation is still not clear have a look at the code I have modified for you below:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
I'm making a program that takes a string from the user and separates it word by word with a delimiter, and it's almost complete. However, after the first full loop, the next input from the user doesn't pass through the last while loop.
Here's the segment of code I'm talking about:
do
{
System.out.println ("\nEntered String: " + s1 + "\n");
while (input.hasNext())
{
word++;
System.out.println ("Word #" + word + ": \t" + input.next());
}
System.out.print ("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while (!s1.equals("q"));
I'm thinking that I need another while loop around the word increment and print line and have the continue sequence within the input.hasNext() loop, because that's how I got a similar program using int to work, but I'm not sure how that would work with strings.
Any advice?
EDIT: to clarify, right now the output of my code looks like this:
Enter a sentence: this is a sentence
Entered String: this is a sentence
Word #1: this
Word #2: is
Word #3: a
Word #4: sentence
Enter 'q' to quit, enter string to continue: another sentence
Entered String: another sentence
Enter 'q' to quit, enter string to continue:
I need 'another sentence' to print out like 'this is a sentence'
I do not understand exactly what's the problem since your code does not compile. But there is no need for another loop. Here is a bit of code that works:
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter a sentence:");
String s1 = scan.nextLine();
do
{
System.out.println("\nEntered String: " + s1 + "\n");
Scanner input = new Scanner(s1);
int word = 0;
while (input.hasNext())
{
word++;
System.out.println("Word #" + word + ": \t" + input.next());
}
System.out.print("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while(!s1.equals("q"));
scan.close();
You can try this if it works. It has the same results with the one you need.
Scanner scan = new Scanner(System.in);
String s1 = scan.nextLine();
do {
String input[] = s1.split(" ");
System.out.println ("\nEntered String: " + s1 + "\n");
for(int i = 0; i < input.length; i++) {
System.out.println ("Word #" + i+1 + ": \t" + input[i]);
}
System.out.print ("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while (!s1.equals("q"));
You are using
while (input.hasNext())
I suppose input is a Scanner object, so you should do something like this before using it (but before entering the loop):
Scanner input = new Scanner(System.in);
Instead of using scanner.next() in while loop, I would recommend doing the following API:
String.split
Scanner.nextLine
Something like this:
while(input.hasNextLine()) {
String line = input.nextLine();
String[] words = line.split("delimeter");
if(words.length < 1 || words[words.length - 1].equals("q")) {
break;
}
}
This question already has answers here:
Java being able to choose wether to add or subract
(3 answers)
Closed 9 years ago.
the idea is that if for example they choose * if will say wrong operator please try again but at the moment that is just looping if I choose the wrong operator and also if I choose the right operator the program needs to end , I cant seem to figure it out
my code is as follows
import java.util.Scanner;
public class Uppgift5 {
public static void main (String[] args){
int tal1, tal2;
int sum = 0;
int sub=0;
String operator;
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
System.out.println("write in first digit");
tal1 = input.nextInt();
System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
System.out.println("Enter + to add and - subtract ");
operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*") || operator.equals(("/")) ){
if (operator.equals("+")){
sum = tal1+tal2;
System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
sub = tal1-tal2;
System.out.println("the subtracted value is " + sub);
}
if (operator.equals("*") || operator.equals("/")){
System.out.println("You have put in the wrong operator, your options are + or -");
}
}
}
}
Your problem is here:
operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*") || operator.equals(("/")) )
Assume operator is +. The value of operator does not change within the while loop, so operator will always be +, and you have an infinite loop.
Your operator will never be different. For that reason, your loops never end. You should use if instead of while
Instead of using a while loop, use a do loop that starts before you read operator from the input and only loops back if operator is not + or -. Ideally the while at the end of the do loop should come before you attempt the calculation.
Well, of course your code never ends... because you have no stopping condition. Also, your looping condition is incorrect. As long as the operator is one of those values, the loop will run. Also, you never ask for an input inside the loop. The code below should work:
import java.util.Scanner;
public class tt {
public static void main (String[] args){
int tal1, tal2;
int sum = 0;
int sub=0;
String operator = "";
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
System.out.println("write in first digit");
tal1 = input.nextInt();
System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
System.out.println("Enter + to add and - subtract ");
while (true){
operator = input2.nextLine();
if (operator.equals("+")){
sum = tal1+tal2;
System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
sub = tal1-tal2;
System.out.println("the subtracted value is " + sub);
}
if (operator.equals("*") || operator.equals("/")){
System.out.println("You have put in the wrong operator, your options are + or -");
break;
}
}
}
}