Really struggling to find the answer to this.
I'm creating a game where it asks how many players there are and the max number of players the user can enter is 3 (either 1, 2 or 3). Is this creating a for loop or can I just enter a parameter in the scanner function?
Code below:
System.out.println(" How many players are there? ");
int numberOfPlayers = scan.nextInt();
Player[] players = new Player[numberOfPlayers]; //this is where the players scores are stored
int currentPlayer = 0; //because arrays start at 0: +1 is added
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.next();
players[i] = new Player(playerName);
You can use Scanner's nextLine() which reads the newline instead of next() as shown below:
System.out.println(" How many players are there? ");
int numberOfPlayers = Integer.parseInt(scan.nextLine());
Player[] players = new Player[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.nextLine();
players[i] = new Player(playerName);
}
I suggest to use Integer.parseInt(scan.nextLine()) with a loop for example :
int numberOfPlayers = 0;
boolean correct = false;
do {
try {
System.out.println(" How many players are there? ");
numberOfPlayers = Integer.parseInt(scan.nextLine());
if (numberOfPlayers >= 1 && numberOfPlayers <= 3) {
correct = true;
}
} catch (NumberFormatException e) {
}
} while (!correct);
So if the user enter incorrect number or a number > 3 or < 1 it will ask the user to enter the number again until the the user enter the correct number 1,2,3
Related
Here is my code:
double carsPrice = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of cars you would like to drive");
String [] numberOfCars = new String[sc.nextInt()];
while (numberOfCars.length > 5) {
System.out.println("Enter a number that is less than 5 and try again");
numberOfCars = new String[sc.nextInt()];
}
System.out.println("Enter the names of cars you would like to hire");
String [] chosenCarNames = new String[5];
sc.nextLine();
for (int i=0; i<numberOfCars.length; i++) {
int nameA = i+1;
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
while ("lamborghini".equals(chosenCarNames[i]) && "toyota".equals(chosenCarNames[i]) && "audi 5".equals(chosenCarNames[i])) {
if (!"lamborghini".equals(chosenCarNames[i]) && !"toyota".equals(chosenCarNames[i]) && !"audi 5".equals(chosenCarNames[i])) {
System.out.println("Name of car " + nameA + " is invalid. Please try again");
chosenCarNames[i] = sc.nextLine();
}
}
}
if ("lamborghini".equals(chosenCarNames[i])) {
carsPrice = 59;
}
else if ("toyota".equals(chosenCarNames[i])) {
carsPrice = 49;
}
else {
carsPrice = 39;
}
I have made a java program that asks customers to enter the number of cars they would like to hire and after that the program should allow the user to enter the names of cars they would like to hire depending on the number of cars they would like to hire. My problem is that if the customer wants to hire more than one car, I am not able to calculate the total price the customer has to pay. If the customer wants to hire only one car, I have used if statements to calculate and display the total number of money the customer has to pay
You could move the price calculation into the loop and accumulate it:
for (int i = 0; i < numberOfCars.length; i++) {
int nameA = i+1;
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
// Input validation omitted for brevity
if ("lamborghini".equals(chosenCarNames[i])) {
carsPrice += 59;
}
else if ("toyota".equals(chosenCarNames[i])) {
carsPrice += 49;
}
else {
carsPrice += 39;
}
}
This is some interesting logic here:
while ("lamborghini".equals(chosenCarNames[i]) && "toyota".equals(chosenCarNames[i]) && "audi 5".equals(chosenCarNames[i])) {
If the entered value was "lamborghini", then the first part would be true, but then how could it also be equal to "toyota" and "audi" at the same time?
If the intention was to only allow "lamborghini", "toyota", or "audi 5", then move that compound boolean expression from the inner if statement out to the while loop, and get rid of the inner if:
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
while (!"lamborghini".equals(chosenCarNames[i]) && !"toyota".equals(chosenCarNames[i]) && !"audi 5".equals(chosenCarNames[i])) {
System.out.println("Name of car " + nameA + " is invalid. Please try again");
chosenCarNames[i] = sc.nextLine();
}
Here I am using a do while loop to execute a program that allows the user to score student scores in an array and then print them. I am struggling with implementing a system that sends an error message when the user inputs a number below 0 or above 100 and then lets the user try again.
import java.util.Scanner;
public class storeScore {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int scores [] = new int [7];
int numberOfStudents = 7;
//User input all scores. For loop works by asking for user input until it reaches the number as input in numberOfStudents.
do
{
for(int i = 0; i<numberOfStudents; i++) {
scores[i] = input.nextInt();
if (i == 0) {
System.out.print("Enter the score for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the score for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the score for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the score for the " + (i+1) + "th student: ");
}
}
//Error output if input is incorrect
}
while (scores[i] < 0 || scores[i] > 100) {
System.out.println("Input out of bounds. Score can only be between 0 and 100");
}
//Printing all scores.
System.out.println("Thank you for your input. Your entered scores are: ");
for (int i=0; i<numberOfStudents; i++)
{
System.out.print(scores[i] + ", ");
}
input.close();
}
}
You have your error message printing in a while loop without any way of breaking out of that loop.
Try capturing your user's input as an int variable first that you can check to see if it's valid before assigning it to scores[].
for(int i = 0; i<numberOfStudents; i++) {
String message;
if (i == 0) {
message = "Enter the score for the 1st student: ";
}
else if (i == 1) {
message = "Enter the score for the 2nd student: ";
}
else if (i == 2) {
message = "Enter the score for the 3rd student: ";
}
else if (i >= 3) {
message = "Enter the score for the " + (i + 1) + " student: ";
}
System.out.println(message);
int score = input.nextInt();
//Now check if the input value is valid
while (score < 0 || score > 100) {
System.out.println("Input out of bounds. Score can only be between 0 and 100");
System.out.println(message);
score = input.nextInt();
}
score[i] = score;
}
Now, the loop will print the message for student i, then take in the score. If the score is invalid, the while loop will print out the error message, and take input again. If the input is valid this time, the while loop breaks and assigns the new score to student i, otherwise it reprints the error message and takes input again.
I want to apply this function in java. Inside while loop, you need to input number of repetition you want to input a number. if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again. This code is not finish yet. I hope u understand what i want to achive. thank you
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
}
Let's use a temp variable to store the value of previous input. If new input is same as previous input, the iterator i should not increase, so we use i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one. I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
See the code for that:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}
so I have another homework question. First, I'll list the instructions and then I'll list my code and hopefully someone can help me/guide me in the right direction.
DIRECTIONS:
Write a program that calculates the occupancy rate for a hotel. The program should start by asking the user how many floors the hotel has. A for loop should then iterate once for each floor. In each iteration of the for loop, the program should ask the user for the number of rooms of the floor and how many of them are occupied. After all of the iterations are complete the program should display how many rooms the hotel has, how many of them are occupied, and the percentage of rooms that are occupied.
It is traditional that many hotels do not have a 13th floor. The for loop in >this program should skip the entire thirteenth loop iteration.
Input validation (remember to use a loop never ever an "if"): Do not accept a value of less than one for the number of floors. Do not accept a value of less than 10 for the number of rooms on a floor.
MY CODE:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework7Hotel
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
DecimalFormat formatter = new DecimalFormat("%#,##0.00");
int numFloors = 0;
int numRooms = 0;
int totalRooms = 0;
int numOccupied = 0;
int totalOccupied = 0;
int percentOccupied = 0;
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
while (numFloors <1)
{
System.out.println("You have entered an invalid number of floors. ");
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
}
for (int counter = 1; counter <=numFloors; counter++)
{
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms=keyboard.nextInt();
totalRooms += numRooms;
while (numRooms <10)
{
System.out.println("You have entered an invalid number of rooms. ");
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms = keyboard.nextInt();
}
System.out.println("Please enter the number of occupied rooms on floor #: " + counter);
numOccupied = keyboard.nextInt();
totalOccupied += numOccupied;
// *not sure of how to do this* percentOccupied = totalOccupied/totalRooms;
}
System.out.println("The hotel has a total of " + totalRooms + " rooms.");
System.out.println(totalOccupied + " of the rooms are occupied.");
System.out.println (percentOccupied + "% of the rooms are occupied.");
}
}
So, the issue I am having is:
1) As per the instructions, how would I skip the 13th floor entirely in the loop?
Any help would be greatly appreciated! Thank you!
You could use a continue keyword in a forloop like.
for(int i = 0;i <20;i++){
if(i == 13){
continue;
}
//Do rest of your steps
}
If you donot want to use continue use
for(int i = 0;i <20;i++){
if(i != 13){
//Do rest of your steps
}
//This should also work it will not do anything when loop is at its 13th iteration.
}
Using continue though is better.
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
DecimalFormat formatter = new DecimalFormat("%#,##0.00");
int numFloors = 0;
int numRooms = 0;
int totalRooms = 0;
int numOccupied = 0;
int totalOccupied = 0;
int percentOccupied = 0;
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
while (numFloors <1)
{
System.out.println("You have entered an invalid number of floors. ");
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
}
for (int counter = 1; counter <=numFloors; counter++)
{
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms=keyboard.nextInt();
//REMOVE totalRooms += numRooms; from here
while (numRooms <10)
{
System.out.println("You have entered an invalid number of rooms. ");
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms = keyboard.nextInt();
}
totalRooms += numRooms; //ADD it here
System.out.println("Please enter the number of occupied rooms on floor #: " + counter);
numOccupied = keyboard.nextInt();
totalOccupied += numOccupied;
// *not sure of how to do this* percentOccupied = totalOccupied/totalRooms;
}
System.out.println("The hotel has a total of " + totalRooms + " rooms.");
System.out.println(totalOccupied + " of the rooms are occupied.");
System.out.println (percentOccupied + "% of the rooms are occupied.");
}
Without continue, you can try if() else block to do the work.
for(int i = 0; i < 20; i++)
{
if(i == 13)
{
// Do the stuff for 13th floor if any
}
else
{
// Do the stuff for floors other than 13
}
}
My code is currently unable to start at the beginning of the program which is 'Please type in...'. I want the code to be able to return to the beginning statement everytime choice 1 or 2 is executed. The while statement does not satisfy this as I cant use the while statement before 'choice' is declared. I understand that I'm suppose to be using a do while loop but everytime I try to implement it - it gives me an error with braces.
The following is a snippet of my code:
System.out.println("Please type in 1 for a customer to view their portfolio, 2 to trade stocks or 3 to exit the application");
int choice = Integer.parseInt(input.nextLine());
{
while (!"3".equals(choice));
{
if (choice == 1) {
System.out.println(mycustomers[menuchoice].toString());
return;
}
if (choice == 2) {
String StockSelect = "Please select a stock";
for (int i = 0; i < mystocks.length; i++) {
// [i] is the element we are accessing
StockSelect += " " + i + " " + (mystocks[i].getSymbol());
}
System.out.println(StockSelect);
int stockchoice = Integer.parseInt(input.nextLine());
System.out.println("Select 1 to buy or 2 to sell?");
int choice2 = Integer.parseInt(input.nextLine());
if (choice2 == 1) {
System.out.println("How many stocks would you like to buy ");
int volumebought = Integer.parseInt(input.nextLine());
for (int i = 0; i < numofstocks; i++) {
mycustomers[menuchoice].setBalance(
mycustomers[menuchoice].getBalance() - (volumebought * mystocks[i].getprice()));
mycustomers[menuchoice].setPortfolio();
}
System.out.println(mycustomers[menuchoice].toString());
return;
}
if (choice2 == 2) {
System.out.println("How much stocks would you like to sell ");
int volumesold = Integer.parseInt(input.nextLine());
for (int i = 0; i < numofstocks; i++) {
mycustomers[menuchoice].setBalance(
mycustomers[menuchoice].getBalance() + (volumesold * mystocks[i].getprice()));
mycustomers[menuchoice].setPortfolio();
}
System.out.println(mycustomers[menuchoice].toString());
return;
}
}
if (choice == 3) // how to exit application
{
System.out.println("Thank you for using the application");
System.out.println("The current state of all customers are:");
for (int i = 0; i < mycustomers.length; i++) {
System.out.println(mycustomers[i].toString());
}
System.out.println("The current state of all stocks are:");
for (int i = 0; i < mystocks.length; i++) {
System.out.println(mystocks[i].toString());
}
System.exit(0);
}
}
}}}
How would I implement the do-while loop so that it goes back to the initial statement every time after executing the code - if only if the input is not 3?
Ask for input inside the while loop, like this:
choice = Integer.parseInt(input.nextLine());