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);
}
}
}
Related
I'm writing sort of main practice project, where I can just continually add classes that do completely different fun things. For example, I have a CoinFlipperCmd and a poker PotOddsCmd, and the code currently works fine, but I want to be able to repeatedly enter commands without having to rerun the program. Example console currently:
FLIP 10 // coinflips 10 times and notes the outcome
You flipped 5 heads and 5 tails
After this, the code will exit, but I want to be able to keep entering commands. Like so:
FLIP 5
You flipped 4 heads and 1 tails
FLIP 6
You flipped 3 heads and 3 tails
POTODDS 0.5 1
You have pot odds of 2:1
I'm using a scanner for input
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args) {
InputScanner();
}
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter command");
String command = myObj.nextLine(); // Read user input
ParseAndDirect(command);
}
private static void ParseAndDirect(String command) {
String[] commandSplit = command.split(" ", 2);
String usercommand = commandSplit[0];
if (usercommand.equals("FLIP")){
CoinFlipperCmd.CoinFlipperCmd(commandSplit[1]);
} else if (usercommand.equals("POTODDS")){
PotOddsCmd.PotOddsCmd(commandSplit[1]);
} else System.out.println("Invalid Command");
}
}
You need to put the input part inside a loop e.g.
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String command;
do {
System.out.print("Enter command (q to quit): ");
command = myObj.nextLine(); // Read user input
if (!command.equalsIgnoreCase("q")) {
ParseAndDirect(command);
}
} while (!command.equalsIgnoreCase("q"));
}
Another way of using the loop can be as follows:
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String command;
while(true)
System.out.print("Enter command (q to quit): ");
command = myObj.nextLine(); // Read user input
if (command.equalsIgnoreCase("q")) {
break;
}
ParseAndDirect(command);
}
}
On a side note (because it won't have any impact on the execution of the program), you should always follow Java naming conventions e.g the method, ParseAndDirect should be named as parseAndDirect and InputScanner should be named as inputScanner.
Apart from allowing the user to repeatedly enter commands, I think you should also allow some way to quit the program (besides having to kill it via the operating system :-) In the below code, I have arbitrarily used the word quit as the way to exit the loop. Feel free to use a different string.
Scanner myObj = new Scanner(System.in);
String command = "";
while (!"quit".equalsIgnoreCase(command)) {
System.out.println("Enter command");
if (!"quit".equalsIgnoreCase(command)) {
ParseAndDirect(command);
}
}
By the way, according to java naming conventions the method name should be parseAndDirect, i.e. it should start with a lowercase letter.
In oder to check the value entered by the user AND to see what random number has been calculated, I want to let those numbers projected in the console (eclipse). But what sketches my astonishment?? the last two system.out.println's (right above invoermax.close())) do NOT appear in the console screen after I entered the number???? It's like java doesn't even read or notice these code lines, How come???
Here my code:
package Package1;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class test6KOPIE1 {
public static void main(String[] args)
{
Scanner Invoermax = new Scanner(System.in);
System.out.println("Under which number you want to guess");
int Invoer = Invoermax.nextInt();
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
System.out.println("So a guess under max: " + Invoer);
System.out.println("The random number has become " + Hoogte);
Invoermax.close();
}
}
every time you call Scanner.nextInt() it will wait for input from you.
The problem is that you are calling it twice, replace:
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
With the variable you already got:
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoer);
And BTW, usually in java you start field/variable name with lower case letter, so should be hoogte, inoverMax, inover etc.
You can do something like this.
// code
Scanner Invoermax = new Scanner(System.in);
System.out.println("Under which number you want to guess");
int Invoer = Invoermax.nextInt();
Invoermax.nextLine(); // reading empty space left
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
// code
You have two scanner.nextInt() calls, so there are two input readings, two input waitings.
int Invoer = Invoermax.nextInt(); // the first input reading
int Hoogte = ThreadLocalRandom.current().nextInt(1,
Invoermax.nextInt()); // the second input reading
When you enter two int values in a console (any of the kind) you'll see your ending print rows.
If your design was to have a single input, then use cashed value for the second usage
int Invoer = Invoermax.nextInt(); // the first input reading
int Hoogte = ThreadLocalRandom.current().nextInt(1,
Invoer ); // use cashed value
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.");
}
}
// 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);
I have a college assignment where I need to print out items sold by a hardware store, take input from a user, perform some calculations on that input, and then print out an invoice.
I have been able to successfully print out the items sold by the hardware store, but am encountering problems with the while loop that takes the input.
The program asks the user to enter a CODE and then asks for the corresponding QUANTITY. This works fine on the first iteration of the loop, but on the second iteration the user prompts for "CODE:" and "QUANTITY:" appear on the same line, despite my use of println when prompting the user.
I would greatly appreciate a detailed response appropriate for someone new in programming.
Here's the code:
import java.util.Scanner;
class HardwareStore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO THE HARDWARE STORE!");
System.out.println("----------------------------------------------------------------------");
String sticky = "G22";
String keyring = "K13";
String screwy = "S21";
String padlock = "I30";
int stickyprice = 10989;
int keyringprice = 5655;
int screwyprice = 1099;
int padlockprice = 4005;
System.out.println("CODE\t\tDESCRIPTION\t\t\t\t\tPRICE");
System.out.println("----\t\t-----------\t\t\t\t\t-----");
System.out.println(sticky + "\t\tSTICKY Construction Glue, Heavy Duty, \n\t\t7oz, 12 Pack \t\t\t\t\t$" + stickyprice);
System.out.println(keyring + "\t\tCAR-LO Key Ring, Quick Release, \n\t\t1 Pack\t\t\t\t\t\t$ " + keyringprice);
System.out.println(screwy + "\t\t!GREAT DEAL! SCREW-DUP Screwy Screws, \n\t\tDry Wall Screws, 3 in. Long, 50 Pack\t\t$ " + screwyprice);
System.out.println(padlock + "\t\tLET-IT-RAIN, Weather Proof Padlock, \n\t\tPortable, One Push Functionality\t\t$ " + padlockprice);
System.out.println("----------------------------------------------------------------------");
int i = 10000;
String [] usercode = new String[i];
int [] userquantity = new int[i];
System.out.println("PLEASE ENTER YOUR ORDER:");
while (true) {
System.out.println("CODE: (X to terminate)");
usercode[i] = in.nextLine();
if (usercode[i].equalsIgnoreCase("x")) {
break;
}
System.out.println("QUANTITY: ");
userquantity[i] = in.nextInt();
}
}
}
when you enter the QUANTITY you're pressing enter. That newline character isn't used by in.nextInt();, it remains in the scanner buffer, until you roll around to in.nextLine() again.
At that point in.nextLine() reads until it finds a newline character, which just happens to be the next one in the buffer. So it skips straight to QUANTITY again.