public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter your salary per hour: ");
int salary = input.nextInt();
System.out.print("Enter number of hours: ");
int hours = input.nextInt();
int sum = salary * hours;
if (hours == 0) {
System.out.println("Stop!");
break;
}
System.out.println("Total salary " + sum);
}
}}
I want to be able to enter numbers until I press 0, and then I want the program to stop. It stops after two zeros, but how can I make it stop after pressing only one zero? I have tried this while-if loop and different do-while loops, I just can't make it work.
Your code does exactly what you tell it to do.
You tell it to:
first ask for TWO numbers
to then compare the first number, and stop on 0
So, the solution is:
ask for one number
compare the number, stop on 0
ask for the second number
If you want to exit whenever you type 0, then you have to check every value after its input.
There is the code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("What's your salary per hour? ");
int salary = scanner.nextInt();
if (salary == 0)
exit();
System.out.print("How many hours did you worked today? ");
int hours = scanner.nextInt();
if (hours == 0)
exit();
int sum = salary * hours;
System.out.println("Your total salary is " + sum);
}
}
private static void exit() {
System.out.println("Have a nice day!");
System.exit(0);
}
Please write a comment if that doesn't match your expectation
Related
this is guess number programme using constructor but the issue which I am facing
is not able to express user input in loop.I tried to look for it but not good explanation.
import java.util.Scanner;
import java.lang.Math;
class guessnumber{
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public String userinput(int repeats,int rand){
String e;
e="that's it";
if(repeats<rand){
String z="choose higher number";
System.out.println(z);
}
else if (repeats>rand){
String z="choose lower number";
System.out.println(z);
}
return e;
}
public String iscorrect(){
String correct="correct number";
return correct;
}
}
public class guessthenumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
guessnumber gun = new guessnumber();
System.out.println("enter number ");
int number = sc.nextInt();
System.out.println("enter max and min number");
int min = sc.nextInt();
int max = sc.nextInt();
int o=gun.getRandomNumber(min,max);
System.out.println(o);
if (number < o || number > o) {
System.out.println(gun.userinput(number, o));}
else if(number==o){
String correct= gun.iscorrect();
System.out.println(correct);
}
}
}
I want to user to keep entering data till correct number is hit
Here's a solution that behaves like you're describing, and how your code currently behaves:
ask for a few numbers up front (minimum, maximum)
determine a random "target" number for the user to guess
ask the user to guess – if they're correct, show a message; if they're incorrect, ask for another guess
repeat until their guess is correct
A few things I did:
introduce a "getNumber()" helper that will make sure the numbers make sense – put some guardrails around what a user can enter to minimize unexpected results if user enters unexpected input
use a "while" loop, go forever – while (true)
if their guess matches the target, use break to stop the loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimum = getNumber(scanner, 0, "minimum");
int maximum = getNumber(scanner, minimum + 1, "maximum");
int target = (int) ((Math.random() * (maximum - minimum)) + minimum);
while (true) {
System.out.print("enter a guess: ");
int guess = scanner.nextInt();
if (guess == target) {
System.out.println("correct guess! the number was " + target);
break;
} else {
System.out.print("nope, please try again.. ");
}
}
}
static int getNumber(Scanner scanner, int minimumAllowed, String numberType) {
while (true) {
System.out.print("enter " + numberType + " number: ");
int minimum = scanner.nextInt();
if (minimum >= minimumAllowed) {
return minimum;
} else {
System.out.println("too small, must be at least " + minimumAllowed);
}
}
}
Here's a sample run:
enter minimum number: 1
enter maximum number: -3
too small, must be at least 2
enter maximum number: 5
enter a guess: 1
nope, please try again.. enter a guess: 2
nope, please try again.. enter a guess: 3
nope, please try again.. enter a guess: 4
correct guess! the number was 4
You can use while and break statements
I have a small piece of code that continuously asks the user to input a number until it receives an input that is divisible by 10 (input % 10) and sums all inputs however it does not add the first input
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int input, sum = 0;
System.out.print("Enter a number: ");
input = in.nextInt();
while (input % 10 != 0) {
System.out.print("Enter a number: ");
input = in.nextInt();
sum += input;
if (input % 10 == 0) {
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
}
}
Example run
Enter a number: 15
Enter a number: 27
Enter a number: 45
Enter a number: 50
The total value is: 122
The last input was divisible by 10
The total value is 122 even though it should be 137 because it did not add the first input which is 15
You're tossing the first line away. This seems like a perfect opportunity to use a do-while instead.
Also, you can move the actual printing outside the loop.
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int input;
do {
System.out.print("Enter a number: ");
input = in.nextInt();
sum += input;
} while (input % 10 != 0)
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
Note that this lays on the premise that you still want to add the last value to the sum even if it was divisible by 10.
If that's not what you want, you need to make the addition conditional as well.
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int input;
do {
System.out.print("Enter a number: ");
input = in.nextInt();
if (input % 10 != 0)
sum += input;
} while (input % 10 != 0)
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
I'm writing a java program to take a bunch of doubles the user inputs into the command line, add them together, and average them. The user can enter any amount of numbers. When they enter a negative number, the program does the adding/averaging. When i enter a number into cmd line it only lets me enter one. Can anyone help me improve this?
import java.util.Scanner;
public class Average
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Statistics Program, assignment one, program
Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop,
enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
int amount = 0;
double totaladded = 0;
double userinput = 0;
userinput = keyboard.nextDouble();
while (userinput >= 0);
{
if(userinput > 0 )
{
totaladded = totaladded+userinput;
amount++;
}
}
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
}
use a do while loop instead,
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int amount = 0;
double totaladded = 0;
double userinput = 0;
do {
System.out.println("Statistics Program, assignment one, program Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop, enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
userinput = keyboard.nextDouble();
if(userinput > 0 ) {
totaladded += userinput;
amount++;
}
} while (userinput >= 0);
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
I have like 3 hours trying to solve this simple problem. Here is what I am trying to accomplished: Ask the user to enter a number, and then add those numbers. If the users enters five numbers, then I should add five numbers.
Any help will be appreciated.
import java.util.Scanner;
public class loopingnumbersusingwhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input;
System.out.println("How Many Numbers You Want To Enter");
total = kb.nextInt();
while(input <= kb.nextInt())
{
input++;
System.out.println("How Many Numbers You Want To Enter" + input);
int input = kb.nextInt();
}
}
}
Your current code is trying to use input for too many purposes: The current number entered, the amount of numbers of entered, and is also trying to use total as both the sum of all numbers entered and the amount of numbers to be entered.
You'll want 4 separate variables to track these 4 separate values: how many numbers the user will entered, how many they entered so far, the current number they entered, and the total.
int total = 0; // The sum of all the numbers
System.out.println("How Many Numbers You Want To Enter");
int count = kb.nextInt(); // The amount of numbers that will be entered
for(int entered = 0; entered < count; total++)
{
int input = kb.nextInt(); // the current number inputted
total += input; // add that number to the sum
}
System.out.println("Total: " + total); // print out the sum
Add this code after you take how many numbers the user wants to add:
int total;
for(int i = 0; i < input; i--)
{
System.out.println("Type number: " + i);
int input = kb.nextInt();
total += input;
}
To print this just say:
System.out.println(total);
import java.util.Scanner;
public class LoopingNumbersUsingWhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input=0;
int total = 0;
System.out.println("How Many Numbers You Want To Enter");
int totalNumberOfInputs = kb.nextInt();
while(input < totalNumberOfInputs)
{
input++;
total += kb.nextInt();
}
System.out.println("Total: " +total);
}
}
You seem to be asking how many numbers twice.
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter");
int howMany = kb.nextInt();
int total = 0;
for (int i=1; i<=howMany; i++) {
System.out.println("Enter a number:");
total += kb.nextInt();
}
System.out.println("And the grand total is "+total);
}
What you should pay attention to:
name classes in CamelCase starting with a big letter
initialize total
don't initialize input twice
show an appropriate operand input request to your user
take care of your loop condition
don't use one variable for different purposes
which variable should hold your result?
how to do the actual calculation
Possible solution:
import java.util.Scanner;
public class LoopingNumbersUsingWhile {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter: ");
int total = kb.nextInt();
int input = 0;
int sum = 0;
while (input < total) {
input++;
System.out.println("Enter " + input + ". Operand: ");
sum += kb.nextInt();
}
System.out.println("The sum is " + sum + ".");
}
}
I'm doing a homework assignment in my Java class. I got most of it except for this one part about elapsed time. We have to use methods. Here's the assignment and the code I have.
"You have just been hired by a company to do it’s weekly payroll. One of the functions you must perform daily is to check the employee time cards and compute the elapsed time between the time they “punch in” and “punch out”. You also have to sometimes convert hours to minutes, days to hours, minutes to hours and hours to days. Since you’ve just finished your first programming class you decide to write a program that will help you do your job.
You decide to structure your program the following way. The main function will just be a menu that the user can select from to get the information they want. Each option on the menu will call a specific method(s) to solve the task and/or output the answer.
You may assume for this program that all elapsed times will be in a single day but the others may span much further. Be sure to provide sufficient test data to demonstrate that your solutions are correct. (show at least one output for each conversion [probably several for option #5]). "
import java.util.*;
public class Prog671A
{
public static void hoursToMinutes()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter hour(s): ");
int hours = input.nextInt();
System.out.println(hours + " * 60 = " + (hours * 60) + " minutes.");
System.out.println("");
}
public static void daysToHours()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter day(s): ");
int days = input.nextInt();
System.out.println(days + " * 24 = " + (days * 24) + " hours.");
System.out.println("");
}
public static void minutesToHours()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter minute(s): ");
int minutes = input.nextInt();
System.out.println(minutes + " / 60 = " + ((double)minutes / 60) + " hours.");
System.out.println("");
}
public static void hoursToDays()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter hour(s): ");
int hours = input.nextInt();
System.out.println(hours + " / 24 = " + ((double)hours / 24) + " days.");
System.out.println("");
}
public static void elapsedTime()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the beginning hour: ");
int startingHour = input.nextInt();
System.out.print("Enter the beginning minute(s): ");
int startingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String startingAmOrPm = input.nextLine();
System.out.print("Enter the ending hour: ");
int endingHour = input.nextInt();
System.out.print("Enter the ending minute(s): ");
int endingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String endingAmOrPm = input.nextLine();
System.out.println("");
System.out.println("The elapsed time is: " + );
}
public static void main (String args [])
{
int x = 1;
while (x == 1) {
Scanner input = new Scanner (System.in);
System.out.println("Conversion Tasks");
System.out.println("\t1. Hours -> Minutes");
System.out.println("\t2. Days -> Hours");
System.out.println("\t3. Minutes -> Hours");
System.out.println("\t4. Hours -> Days");
System.out.println("\t5. Elapsed time between two times");
System.out.println("\t6. Exit");
System.out.print("Enter a number: ");
int menu = input.nextInt();
System.out.println("");
if (menu == 1)
hoursToMinutes();
if (menu == 2)
daysToHours();
if (menu == 3)
minutesToHours();
if (menu == 4)
hoursToDays();
if (menu == 5)
elapsedTime();
if (menu == 6)
x = 0;
}
}
}
I just need help here
public static void elapsedTime()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the beginning hour: ");
int startingHour = input.nextInt();
System.out.print("Enter the beginning minute(s): ");
int startingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String startingAmOrPm = input.nextLine();
System.out.print("Enter the ending hour: ");
int endingHour = input.nextInt();
System.out.print("Enter the ending minute(s): ");
int endingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String endingAmOrPm = input.nextLine();
System.out.println("");
System.out.println("The elapsed time is: " + );
}
Just convert the start and end times to minutes since the start of the day (at midnight). For p.m., just add 12 to the hour before converting to minutes. Then subtract and convert back to hours and minutes for the elapsed time.
why do you want to take the hours etc stuff manually??
Read the system date when the User logs in System.currentTimeMillis() store this time somewhere
When the User exists do the same get the System Time. Subtract it from the time you stored initially when the user logged in.
I hope this is what ur looking for ?