Issue with looping in Java code - java

Use a while loop to keep asking the user to enter the order of
numbers until the user does give two numbers in the right order (first
smaller than second
Hi! i'm a beginner in java and I have this code but I can't loop the "error" message. it just prints 2 times
import java.util.Scanner;
public class Q6 {
public static void main(String[] args) {
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if (num1 < num2) {
int counter = num1;
while (counter <= num2) {
System.out.print(counter + " ");
counter = counter + 1;
}
}
else {
System.out.println("Error: the first number must be smaller than the second");
System.out.print("Please type two numbers: ");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
}
}

int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers");
System.out.printn("first number must be smaller than the second:)";
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}

int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if(num1>=num2) {
System.out.println("Error: First number must be smaller than the second.");
}
}

Related

Using Loops to Reset Basic Financial Calculator

I cannot quite figure out how to make my basic financial calculator be able to run a new set of numbers without closing the program. What I currently have allows me to run one set of numbers, and when I get to "Would you like to continue?", when I press 1 it simply will print "Would you like to continue?" however many times I press 1. Here is what I have so far:
package Register;
import java.util.Scanner;
public class Register {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
{
System.out.println("Electricity Bill: $" + total);
}
System.out.println("");
boolean keepLooping = true;
while (keepLooping) {
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}
You have used while loop around asking choice statements only. So use while loop at the beginning in main method as below:
import java.util.Scanner;
public class Register{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
boolean keepLooping = true;
while(keepLooping) {
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
System.out.println("Electricity Bill: $" + total);
System.out.println("");
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}

Strings as sentinel values in a while loop

I'm trying to write a program that asks the user if they want to enter a real number. If yes, then prompt the user to enter a number. Keep prompting for number inputs until user says "no." Once this happens, output the average of the numbers entered.
I think I'm stuck trying to implement a string for the sentinel value. I want the sentinel value to be "no." But with this last attempt I have here, when I enter "yes" I get an InputMismatchException. Also, not sure if this is a job for do/while or just while. Kind of new to all this and not sure how to go about this, as we don't have examples of using strings for sentinels.
public static void main(String[] args) {
int count = 0;
float total = 0;
float inputNumber;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = "";
inputNumber = scan.nextFloat();
do {
reply = scan.nextLine();
if (reply.equalsIgnoreCase("yes")) {
System.out.println("Enter a number > ");
total+= inputNumber ;
count++ ;
System.out.println("Enter another number, or " +
"enter \"no\" to terminate > " );
inputNumber = scan.nextFloat();
}
}
while (! reply.equalsIgnoreCase("no")) ;
if (count != 0) {
System.out.println("The average of the numbers is " +
(total / count));
}
}
}
Remove first inputNumber = scan.nextFloat();
Fix loop.
Add scan.nextLine() after scan.nextFloat()
public static void main(String[] args) {
int count = 0;
float total = 0f;
float inputNumber = 0f;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = scan.nextLine();
while (reply.equalsIgnoreCase("yes")) {
System.out.println("Enter a number > ");
inputNumber = scan.nextFloat();
scan.nextLine();
total += inputNumber;
count++;
System.out.println("Enter another number, or enter \"no\" to terminate > ");
reply = scan.nextLine();
}
if (count != 0) {
System.out.println("The average of the numbers is " + (total / count));
}
}
EDIT
public static void main(String[] args) {
int count = 0;
float total = 0f;
float inputNumber = 0f;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = scan.nextLine();
if (!reply.equalsIgnoreCase("yes"))
return;
System.out.println("Enter a number > ");
while (!reply.equalsIgnoreCase("no")) {
reply = scan.nextLine();
try {
inputNumber = Float.parseFloat(reply);
} catch (NumberFormatException e) {
continue;
}
total += inputNumber;
count++;
System.out.println("Enter another number, or enter \"no\" to terminate > ");
}
if (count != 0) {
System.out.println("The average of the numbers is " + (total / count));
}
}

How to use methods with a while loop

I want to get the output when I enter a odd number (eg. 3) it will be give the output '3' and if I enter a even number it will print 'wrong input'.
I know I can use if else but I want to use the while loop to get it.
I am a beginner in programming so I would appreciate if someone can help me thanks
This are my codes right now. When I run it there is an error.
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
int num;
num = readOddNum();
System.out.println("The odd integer is" + num);
}
public static int readOddNum() {
int num = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter an odd number: ");
int num1 = sc.nextInt();
sc.close();
while ((num < 0) &&(num % 2 == 0)) {
System.out.println("Wrong input!");
}
return readOddNum();
}
}
You should change your code to
public static int readOddNum() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an odd number: ");
int num1 = sc.nextInt();
while ((num1 < 0) || (num1 % 2 == 0)) {
System.out.println("Wrong input! - try again");
num1 = sc.nextInt();
}
sc.close();
return num1;
}
Change your readOddNum logic to this..
public static int readOddNum() {
int num;
Scanner sc = new Scanner(System.in);
num = readNumber(sc);
while ((num < 0) || (num % 2 == 0)) {
System.out.println("Wrong input!");
num = readNumber(sc);
}
sc.close();
return num;
}
public static int readNumber(Scanner sc){
System.out.print("Enter an odd number: ");
return sc.nextInt();
}
The code can be rewritten in the following way
import java.util.Scanner;
public class UserInput
{
public static void main(String[] args)
{
//int num;
readOddNum();
//System.out.println("The odd integer is" + num);
}
public static void readOddNum()
{
int num = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter an odd number: ");
int num1 = sc.nextInt();
sc.close();
while ((num1 < 0) ||(num1 % 2 == 0))
{
System.out.println("Wrong input!");
break;
}
System.out.println("The odd integer is" + num1);
// return readOddNum();
}
}
As you can see, I have directly called the method readOddNum(); and defined it as void instead of the earlier version. Also, notice the changes in the while loop. You were initialising num with 0 and using it in the while loop whereas the loop should run on num1 which is the actual user input, not num.
Next thing is you used &&(logical AND) instead of ||(logical OR) and both obviously have different meanings. && will mean that even if user enters an even number like 2 it should also be less than 0 which isn't the case. So you need to use ||. Also, you will need to use break to stop the loop once the statement is printed, else it will keep on executing infinitely as there's no other stopping condition. Remember that if else has been created for scenarios like these where you have to choose between two or more situations and execute only one, so while loop will work but it will also execute the print statement, thereby stating wrong input and odd number. This is the output you get
C:\Java\jdk1.8.0_141\bin>java UserInput
Enter an odd number: 3
The odd integer is3
C:\Java\jdk1.8.0_141\bin>java UserInput
Enter an odd number: 2
Wrong input!
The odd integer is2
Hope you understood the concept. Appreciate it, if you like it. Thank you.

if and else statements not working java

Hi I am trying to take in an integer between 1 and 10.
If the user does not do so would like the program to run again.
I believe that I need to use an else if statement that calls on my function but I do not know how to call functions in java.
Here is my code so far:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
if (num1 >= 1 && num1 <= 10); {
System.out.println("Input = " + num1);
}
else if {
???
}
}
}
if-else always work.
You made a mistake in the if statement.
there is no ; for an if
if (num1 >= 1 && num1 <= 10) {//no semicolon
System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
...
}
What happens if I put a semicolon at the end of an if statement?.
How do I ask the user again if the input is not in between 1 and 10?
Loop until you get what you want :)
Scanner sc = new Scanner(System.in);
int num = 0;
while(true)
{
num = sc.nextInt();
if(num > 0 && num < 11)
break;
System.out.println("Enter a number between 1 and 10");
}
System.out.println(num);
Since you are expecting a number between 1 to 10, but you don't know how many numbers you will get until you get a valid number, I'd suggest to use a while loop, like so:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
while (num1 < 1 || num1 > 10) {
System.out.print("Invalid number, enter another one: ");
num1 = in.nextInt();
}
System.out.println("Input = " + num1);
}
}

Java: Ask for continue

I'm trying to make a calculator. These operators: x, +, -, / work fine.
But I want the user to be able to do 2 things after he gets the answer on his math problem.
Ask user if he wants to continue.
If user types in yes he gets to put in 2 numbers that it counts again.
If the user types no just shut down.
Here's my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Minscanner = new Scanner(System.in);
int nr1 = Integer.parseInt(Minscanner.nextLine());
int nr2 = Integer.parseInt(Minscanner.nextLine());
int yes = Integer.parseInt(Minscanner.nextLine());//trying to fix reset
int ans =0;
int reset = J;/trying to make it reset if user types in yes
String anvin = Minscanner.nextLine();
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
System.out.println(ans);
}
if(anvin.equalsIgnoreCase("yes")) {
return;
}
}
}
Put your code in a
do {
...
} while (condition);
loop, and in your case the condition would be something like wantToContinue if user say "yes".
Then the program will not end unless user no longer wants to calculate.
You can refactor your code as bellow. This may help you
boolean status=true;
while (status){
Scanner scanner = new Scanner(System.in);
Scanner scanner1 = new Scanner(System.in);
System.out.println("Enter your two numbers one by one :\n");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("Enter your operation you want to perform ? ");
int ans =0;
String option = scanner1.nextLine();
if(option.equalsIgnoreCase("+")) {
ans = num1 + num2;
}
else if(option.equalsIgnoreCase("-")) {
ans = num1 - num2;
}
else if(option.equalsIgnoreCase("*")) {
ans = num1 * num2;
}
else if(option.equalsIgnoreCase("/")) {
ans = num1 / num2;
}
System.out.println(ans);
System.out.println("you want to try again press y press j for shutdown\n");
Scanner sc = new Scanner(System.in);
String input=sc.nextLine();
if (input.equalsIgnoreCase("J")) {
System.exit(0);
} else if (input.equalsIgnoreCase("Y")) {
status = true;
}
}

Categories