// Week 3 Checkpoint1: Payroll Program Part 2
// Due May 04, 2012
// Created by: Kennith Adkins
import java.util.Scanner;
public class Assignment1
{
public static void main ( String[] args )
{
Scanner input = new Scanner(System.in);
// Variables
String employeeName = null;
int hours;
double rate;
double pay;
while ( employeeName != "stop")
{
// Request information from user
System.out.print ( "Employee Name: ");
employeeName = input.nextLine();
System.out.print ( "Hourly Rate: ");
rate = input.nextDouble();
System.out.print ( "Number of Hours worked this week: ");
hours = input.nextInt();
// Calculate pay
pay = rate * hours;
// Display information
System.out.printf ("%s will get paid $%.2f this week.\n", employeeName, pay);
}
}
}
When I run the program it runs fine. When it hits the loop and repeats, Employee Name: and Hourly Rate seem to bunch up. Also how would I get it to immediately stop after typing stop as employee Name?
As this appears to be a homework question I'll point you in a learning direction.
So for the employee name question I will redirect you to How do I compare strings in Java?
The scrunching issue is because when you reenter the loop and call scanner(input).nextLine it ends up actually reading the input text that it had not seen yet. So one option is to switch to something else lick a BufferedReader or move the scanner deceleration down in to the loop.
More research
I haven't worked much with the scanner class and after seeing this I was somewhat confused. The issue is actually the nextInt and nextDouble. They dont claim the return charter and as such when you call next line next time it is picking up the leftover return character.
So my option of reseting the scanner when reentering works in this specific case but you should either use 2 scanners or move off of scanners.
Scanner txtinput = new Scanner(System.in);
Scanner numberinput = new Scanner(System.in);
Related
I am having a problem where my program is scanning for two different inputs at the same time.
import java.util.Scanner;
public class Person {
public static void main(String[] args){
Person p1 = new Person();
System.out.println("1: Add Person");
System.out.println("2: Delete Person");
System.out.println();
System.out.print("Please make a selection: ");
Scanner keyboard = new Scanner(System.in);
int selection = keyboard.nextInt();
switch(selection){
case 1:
System.out.print("Please enter name: ");
String name = keyboard.nextLine();
p1.addPerson(name);
break;
}
}
public Person(){
}
public void addPerson(String name){
int day, month, year;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter date of birth in the format dd mm yyyy: ");
day = keyboard.nextInt();
month = keyboard.nextInt();
year = keyboard.nextInt();
}
}
This is the output:
1: Add Person
2: Delete Person
Please make a selection: 1
Please enter name: Please enter date of birth in the format dd mm yyyy:
The program does not wait for the name to be entered, how do i fix this?
The problem is when you do nextInt() it scans an integer, but not the new line character(\n), so when you call nextLine() it just consumes \n you typed when was doing selection and returns empty string.
Several ways to fix it:
First is to call nextLine() after nextInt. To fix your code you would do this:
int selection = keyboard.nextInt();
keyboard.nextLine();
Second option is to call nextLine() but when you need int wrap in in Integer.parseInt(). So, for example, your selection would look like:
int selection = Integer.parseInt(keyboard.nextLine());
Other option would be to use next() instead of nextLine, however, this approach wouldn't work if name contains spaces.
You should use keyboard.next()
From the java docs:
next(): Finds and returns the next complete token from this scanner.
This is what keyboard.nextLine() does:
nextLine(): Advances this scanner past the current line and returns the input that was skipped.
I need to write a program that helps a convenience store clerk decide whether or not to sell beer to a customer. Beer can only be sold to somebody who is 21 years old or more, and has enough money (beer costs $5.00). If the customer is too young, tell them how many years they must wait before returning. If they have too little money, tell them how much more is needed. I don't know what to do, please help.
import java.util.Scanner;
public class example1 {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
int age;
double beerPrice;
double cash;
System.out.print( "Please type customer age:" );
age = scan.nextInt();
System.out.println();
System.out.print ("Type customer cash amount:");
cash= scan.nextDouble();
System.out.println();
if (age <= 21) {
System.out.println(21-age);
}
}
}
This is all I have so far. Each time I run the program, if the age is 21 or greater, it still prints age when I don't want it to. Please help me complete this program. Not asking for a hand out.
Your code looks fine. Sometimes the compiler gets confused and doesn't register new changes when it should. Try saving the file you're working on, then compiling, then try restarting the compiler. If that fails, there is usually a 'clean project' function in many compilers that can help.
You can use the following code
public class example1{
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
int age;
double beerPrice;
double cash;
System.out.print( "Please type customer age:" );
age = scan.nextInt();
System.out.println();
System.out.print ("Type customer cash amount:");
cash= scan.nextDouble();
System.out.println();
if (age < 21) {
System.out.println(""+(21-age)+" years till you can buy beer");
}
if(cash<5.0)
{
System.out.println("$"+(5.0-cash)+" more is required");
}
}
}
I am new to the forums so first of all I'd like to say "Hi"! I'm new to Java programming and am trying to make a simple payroll calculating program with three while loops.
The first while loop keeps the program going until the user enters the sentinel "stop". The second and third loops are error traps that ensure the user enters a positive number before continuing.
For some reason, the while loops are not working and I have tried every variation I can think of. The program runs just fine, it just ignores the while loops. If someone could provide some suggestions as to what I'm doing wrong, I'd really appreciate it.
I'm using NetBeans 8.0 IDE if that helps.
Here is my code:
Import java.util.*;
Import java.text.*;
public class PayrollProgramVersion2
{
//begin main program
public static void main(String[] args)
{
//declare new scanner
Scanner sc = new Scanner (System.in); // declare new scanner object
DecimalFormat Dollars = new DecimalFormat ("$0.00"); //format for dollars
String Employee; //employee's name
Double Hours, //hours worked
Rate, //pay rate
Pay; // Hours * Rate
Boolean Continue = true; // sentinel for program loop
//welcome user, prompt for employee name, and assign input to Employee
System.out.println ("Welcome to the payroll program!");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
// while loop continues program until user enters "stop"
while (Continue == true)
{
if (Employee.equalsIgnoreCase("stop"))
{
Continue = false;
} // end if
else
{
//prompt for hours worked and assign to Hours
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
}
//prompt for pay rate and assign to Rate
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Rate < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
}
Pay = Hours * Rate; // calculate payrate
//display results
System.out.println(Employee+ "'s paycheck is " +(Dollars.format(Pay))+ ".");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
} //end else
} //end while
System.out.println ("Thank you for using the payroll program. Goodbye!");
} // end main
} // end program
From what I can see you should make your while (hours<0) to while (hours<0 || hours == null).
This is because... As far as I can see you initialise hours. But no value is input into it. So it remains as null. You could also try changing the while to an if.
Hope this helps. It may be that it does default to 0 but it may be worth for testin purposes to have a console output.
System.out.println(hours);
Befor the while loop to see what your program is reading hours as.
Hope this helps.
The error is that nextDouble does not eat the newline. It skips newlines at the beginning, so in effect only the last nextDouble is concerned.
Best to make a utility function:
Instead of
Hours = sc.nextDouble();
call your own function:
Hours = nextDouble(sc);
private static double nextDouble(Scanner sc) {
double value = -1.0;
if (sc.hasNextDouble()) {
value = sc.nextDouble();
}
sc.nextLine();
return value;
}
Use a small initial letter for field and method names.
Use double/boolean/int instead of the Double/Boolean/Integer as the latter are Object wrappers (classes); the first primitive types.
Call sc.close(); (for good order).
Aside from what has been said above:
sc.nextDouble consumes and returns the next input from the current line. It does not forward the line.
sc.nextLine consumes and returns the input from the current line and forwards to the next line
At the end of your while loop you call Employee = sc.nextLine(); If you follow your logic and only input allowed values, this will always return an empty string as it consumes the current line where your most previously removed double was stored(now empty string "")
When you do something like:
Hours = sc.nextDouble();
you trust the user to enter a double value, and in case the user entered illegal value, a String for example, this line will throw an exception.
You can solve it like this:
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
String hours = sc.nextLine();
try {
Hours = Double.valueOf(hours);
}
catch (NumberFormatException e) {
// keep looping until we get a legal value
Hours = -1.0;
}
}
Making just a simple basketball program where I ask for the home team name, how many games are in the season, and then in a loop ask for the next team game. Basically when I start the do-while loop, it works great, unless the user types in for example, "Ohio State." The out put will then go from "6 games remaining" to "4 games remaining" for example. Usually it will just ask opponent?, then decrement by one game.
How can I fix so that a 2 word basketball team name doesn't decrement twice?
import java.util.Scanner;
public class Basketball2 {
public static void main(String[] args) throws java.io.IOException {
Scanner scanInput = new Scanner(System.in);
String sHomeTeam;
String sAwayTeam;
int iNumGames;
int iGamesLeft = 0;
System.out.println("Enter home team's name: ");
sHomeTeam = scanInput.nextLine();
System.out.println(sHomeTeam);
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
System.out.println(iNumGames);
//start looping
do {
System.out.println("Enter opponent team's name: ");
sAwayTeam = scanInput.next();
System.out.println(sAwayTeam);
iGamesLeft = --iNumGames;
System.out.println("There are " + iGamesLeft + " games left in the basketball season");
}//end do
while(iGamesLeft > 0);
Replace: sAwayTeam = scanInput.next(); with sAwayTeam = scanInput.nextLine(); The reason it loops twice is because scanInput.next(); only returns one token (e.g. word) at a time. When you enter two words it doesn't need receive more input from the user before continuing a second time because it already has another word to return. Hence the double loop.
You also need to take care of the line of code that calls nextInt(). This works like the next() method, but, instead of a token (word), it scans in just one character as an int. Try this: after iNumGames = scanInput.nextInt(); put scanInput.nextLine(); This should clear scanInput of anything that is making it skip. Note: because of the way that your code is written, this will only read one character. If you need to read more than one character you should use nextLine() and assign its value to an integer.
Whatever is said in the answer given by Donny Schrimsher is correct. All that you have to do now is after getting the number of games in the home team's basketball season i.e.
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
You have to add
scanInput.nextLine();
This is because after entering the number of games you press enter key (end of line) and nextInt() method takes the number of games and not the end-of-line. This end-of-line is consumed by the nextLine() method which Donny Schrimsher mentioned in the do-while loop. SO to avoid this you add an extra nextLine() method.
Thus it has to be
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
scanInput.nextLine();
System.out.println(iNumGames);
plus the changes mentioned by Donny Schrimsher.
Thanks
try below code with all exit functionality also.
import java.util.Scanner;
public class Basketball2 {
public static void main(String[] args) throws java.io.IOException {
Scanner scanInput = new Scanner(System.in);
String sHomeTeam;
String sAwayTeam;
int iNumGames;
int iGamesLeft = 0;
System.out.println("Enter home team's name: ");
sHomeTeam = scanInput.nextLine();
System.out.println(sHomeTeam);
System.out
.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
System.out.println(iNumGames);
// start looping
do {
System.out.println("Enter opponent team's name: ");
scanInput = new Scanner(System.in);
sAwayTeam = scanInput.nextLine();
if(!"".equals(sAwayTeam.trim()) && !"exit".equals(sAwayTeam.trim()))
{
System.out.println(sAwayTeam);
iGamesLeft = --iNumGames;
System.out.println("There are " + iGamesLeft+ " games left in the basketball season");
}
}// end do
while (iGamesLeft > 0 && !"exit".equalsIgnoreCase(sAwayTeam));
}
}
Subject: 'Java Loops' with Scanner
The simple Java program I wrote is working perfectly, you can try for yourself...and you also can convert this program easily into 'while loop', 'do - while loop' and 'for - each loop'.
Rafiq,
VA, USA,
Dated: 04/17/2015
//Examples: 'for loop' with Scanner
package com.java_basics;
import java.util.Scanner;
public class ForLoop_Examples_With_Scanner
{
public static void main(String[] args)
{
//Creating instance of Scanner to allows a user's input to read from System.in
Scanner mySC = new Scanner(System.in);
System.out.println("Please, enter the value of 'int i' between '0 and 2' : ");
int i = mySC.nextInt();
System.out.println("Please, enter the value of 'exitPoint' between '10 and 1000' :");
int exitPoint = mySC.nextInt();
System.out.println("Please, enter the value of 'increment' between '1 and 2' :");
int increment = mySC.nextInt();
mySC.close();//Releasing memory to the OS (Operating System) for reuse
System.out.println("Output:\n" + "======");
for(;i<exitPoint ; i=i+increment)//i++==>i=i+1==>i=i+increment
{
System.out.println(i);
}
}
}
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}