Text not printing - java

In school I had to make a calculator program. In the program, we ask the user if they want to add, subtract, multiply, or divide. At the end, we ask the user of they want to continue the program or no. I haven't put in the looping part yet, but my problem here is that after the "Would you like to continue" is displayed, the program just exits.
package calculator;
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
{
int o1; //first operand
int o2; //second operand
Scanner input = new Scanner (System.in);
System.out.println("Enter a choice:");
System.out.println("+ to add");
System.out.println("- to subtract");
System.out.println("* to multiply");
System.out.println("/ to divide");
System.out.println("X to exit");
String userChoice = input.nextLine();
if (userChoice.equals("X to exit")) {
System.exit(0);
}
System.out.println("Enter the first operand:");
o1 = input.nextInt();
System.out.println("Enter the second operand:");
o2 = input.nextInt();
if (userChoice.equals("+ to add")) {
System.out.println( (o1) + (o2) ); }
else if (userChoice.equals("- to subtract")) {
System.out.println( (o1) - (o2) ); }
else if (userChoice.equals("* to multiply")) {
System.out.println( (o1) * (o2) ); }
else if (userChoice.equals("/ to divide")) {
System.out.println( (o1) / (o2) ); }
System.out.println("Would you like to continue?");
System.out.println("Yes");
System.out.println("No");
String userPick = input.nextLine(); {
if (userPick.equals("Yes")) {
System.out.println("Ok."); }
else if (userPick.equals("No")) {
System.exit(0); }
}
}
}
// TODO Auto-generated method stub
}

Try this:
Scanner input = new Scanner (System.in);
while(true){
System.out.println("Enter a choice:");
System.out.println("+ to add");
......
if (userPick.equals("Yes")) {
System.out.println("Ok."); }
else if (userPick.equals("No")) {
System.exit(0); }
}
}
It will continue to loop around the logic until the terminating condition is met. You may also like to close the scanner before System.exit(); and before any termination in fact.

System.out.println("Would you like to continue?");
System.out.println("Yes");
System.out.println("No");
// add this lline, it can make a difference
input.nextLine();
String userPick = input.nextLine();

You need a while(true) {} loop at the place in the program where you want it to restart. This way, you can go back to the beginning if the user says yes, but the program will exit if the user says no.

You can add a line before your code
String userPick = input.nextLine(); which line is input.nextLine();
it can work well, which can receive enter break line.you can try.
ps:my english is bad,I am not sure I expressed clearly.

Related

how to break or continue a loop from user input

I'm trying to write a code that loops when y is entered and stops when n is entered, this is what I have so far.
Scanner input = new Scanner(System.in);
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
}while (input.hasNext());{
input.hasNext("y");
}
I have no clue how to continue.
For more readable code you can use a boolean variable and assign it to true according to your input equals to "y" condition
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean stopFlag= false;
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
String userInput =input.next();
if(!userInput.equals("y"))
stopFlag=true;
}while (!stopFlag);
}
You can do this:
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
String temp = input.next();
if(temp.equals("y")) {
// if you need to do something do it here
continue; // will go to the next iteration
} else if(temp.equals("n")) {
break; // will exit the loop
}
}
If you are persistent on using do...while then you can try:
Scanner input = new Scanner(System.in);
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
}while (input.hasNext() && !input.next().equals("n"));

Read in input text Yes/No Boolean from user to proceed the next step

I amm at my very beginning at java and just wanted to ask.
I want to ask the user to put Yes/No to a question and proceed to the next question. How do I do it?
import java.util.Scanner;
public class sff {
public static void main (String args[]) {
System.out.println("Hello There! We want to ask you some questions! but first: ");
System.out.print("Enter your age: ");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int age = num;
if( age == 12){
System.out.println("Hello Dan, I know you very well! ");
}
{
System.out.println("First question: ");
System.out.println("Do you exercise?(Yes/No) ");
// how do i proceed from here??
Use Scanner and get next line, then check if that line is yes or no then handle respectively.
In the example below, I used a while loop to keep asking them to input yes or no in case they enter something different like "maybe".
For example:
Scanner in = new Scanner(System.in);
// Loop until they enter either yes or no.
while(true){
String line = in.nextLine();
// Use this to check if it is yes or no
if(line.equalsIgnoreCase("yes")){
// Process yes
break;
}else if(line.equalsIgnoreCase("no")){
// Process no
break;
}else{
// Tell them to enter yes or no since they entered something else.
}
}
Are you looking for something like this?
//import to use the Scanner
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
//get the user input and store it as a String
String exerciseQuestion = in.nextLine();
//check what the user said.
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do you code when he exercises
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}
System.out.println("Ask your next question so on....");
}//main
}//class
If you want to deal with answers other than yes/no you can use this code:
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
String exerciseQuestion;
while (true){
//get the user input
exerciseQuestion = in.nextLine();
//check if user input is yes or no
if((exerciseQuestion.equalsIgnoreCase("yes")) ||
exerciseQuestion.equalsIgnoreCase("no"))
//if yes break and continue with your code
break;
else
//else loop back to get user input until answer is yes/no
System.out.println("Please answer with yes or no only");
}//while . i.e answer not yes or no
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do your code
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}//else
}//main
}//class

How do I stop a loop from indefinitely looping in Java?

I have this try/catch wrapped around a do/while loop because after the try/catch throws the error message, I want it to loop back to the top. I tried do/while, while, and I tried placing the while loop at different places in my code but nothing works. The program works fine until an exception is thrown and then it goes into an infinite loop. After is displays the error message, I just want it to loop back up to the top.
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if ( userInput == 1 )
Animal1.displayMessage ();//Display the total
if( userInput == 2 )
Animal2.displayMessage ();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
break;
}
} while (true);
}
}
This is what it does after displaying an error message.
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
Enter a number?
If I don't stop it, it just keeps going.
you can try this workaround:
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if ( userInput == 1 )
Animal1.displayMessage ();//Display the total
if( userInput == 2 )
Animal2.displayMessage ();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
input.next();
}
} while (true);
}
}
or if you want to avoid try-catch:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Integer userInput = 0;
do {
System.out.print("Enter a number? \n");
if (input.hasNextInt())
userInput = input.nextInt();
else {
System.out.println(" That's not right ");
input.next();
}
if (userInput == 1)
Animal1.displayMessage ();//Display the total
;// Display the total
if (userInput == 2)
Animal2.displayMessage ();//Display the total
} while (true);
}
You can give 3 options - one option to exit
System.out.print("Enter a number? \n 1 to display Animal1 total\n2 to display Animal2 total\n 3 to exit");
Inside while loop, you can add
if ( userInput == 3) break;
You need to put the try/catch statements outside of the loop.

How do I fix this loop validation?

I am VERY new to Java, I am trying to do a unit conversion program from Fahrenheit to Celsius and I am stun on the validation loop. This is what I got.
// Validation
do {
isNumber = true;
System.out.print("What is the temperature in Fahrenheit?: ");
// If alphabetical characters are entered
while (!input.hasNextDouble()) {
System.out.println("Oops! Try entering only numerical characters.");
System.out.println();
isNumber = false;
input.next();
}
fahrenheit = input.nextDouble();
} while (!isNumber);
as you can see what I am trying to validate is that the user doesn't enter a string. but when I run the program it gets stuck on some sort of loop and it says
What is the temperature in Fahrenheit?: something <-- what I input
Oops! Try entering only numerical characters.
and that's it. it doesn't go back to the the input or anything, it just stays there until I enter a number and then it goes back to
What is the temperature in Fahrenheit?:
To clarify, my problem is only with the validation loop, because when I enter a number it works just fine. The problem ONLY appears when I enter a string.
Example code:
import java.util.Scanner;
public class QuickTester {
public static void main(String[] args) {
double fahrenheit;
Scanner input = new Scanner(System.in);
// Validation
while(true) {
System.out.print("What is the temperature in Fahrenheit?: ");
// If alphabetical characters are entered
if (!input.hasNextDouble()) {
System.out.println("Oops! " +
"Try entering only numerical characters.\n");
// Clear away erroneous input
input.nextLine();
}
else {
fahrenheit = input.nextDouble();
break; // Get out of while loop
}
}
input.close();
System.out.println("Temperature in Fahrenheit: " + fahrenheit);
}
}
Input/Output:
What is the temperature in Fahrenheit?: abc
Oops! Try entering only numerical characters.
What is the temperature in Fahrenheit?: banana
Oops! Try entering only numerical characters.
What is the temperature in Fahrenheit?: 36.5
Temperature in Fahrenheit: 36.5
Note:
Revised the code. You do not need a while loop within a do-while loop.
Check if the input is a double, break out of while loop if it is indeed a double value.
Something like this will do
Scanner input = new Scanner(System.in);
double fahrenheit;
do {
System.out.print("What is the temperature in Fahrenheit?: ");
try {
fahrenheit = input.nextDouble();
//Do your work
break;
} catch (InputMismatchException ex) {
input.nextLine();
System.out.println("Oops! Try entering only numerical characters.");
System.out.println();
}
} while (true);
this will do the trick.
public class Main
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
System.out.print( "What is the temperature in Fahrenheit?: " );
// If alphabetical characters are entered
while ( !input.hasNextDouble() )
{
System.out.println( "Oops! Try entering only numerical characters." );
System.out.println();
input.next();
}
//Do Fahrenheit to Celsius calculation
}
}

Make a code repeat loop if user input a non-numeric character?

Goal:
If the user enters a non-numeric number, make the loop run again.
Also is there another (more efficient) way of writing the numeric inputs?
public static void user_input (){
int input;
input = fgetc (System.in);
while (input != '\n'){
System.out.println("Please enter a number: ");
if (input == '0' == '1' ..... '9'){
//Execute some code
}
else {
System.out.println("Error Please Try Again");
//Repeat While loop
}
}
}
EDIT
I need the while loop condition. Simply asking, how do you repeat the while loop? Also no scanner methods.
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue. Try this:
public static void user_input() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
}
Output
Enter a number.
w
Input is not a number, continue
Enter a number.
3
Correct input, exit
Try this one
System.out.println("Please enter a number: ");
Scanner userInput = new Scanner(System.in);
while(!userInput.hasNextInt()) {
System.out.println("Invalid input. Please enter again");
userInput = new Scanner(System.in);
}
System.out.println("Input is correct : " + userInput.nextInt());
How about this
public static void processInput() {
System.out.println("Enter only numeric: ");
Scanner scannerInput;
while (true) {
scannerInput = new Scanner(System.in);
if (scannerInput.hasNextInt()) {
System.out.println("Entered numeric is " + scannerInput.nextInt());
break;
} else {
System.out.println("Error Please Try Again");
}
}
}

Categories

Resources