I'd like to make a program that asks the user to enter the number of customers for booking tickets, reads the entered number, performs the loop to ask the age of each customer, and decide the unit price for each customer.
my code so far only has the if else statements:
if (customerP <4){
System.out.println("The unit Price of customer 1 is: 0");
}else {
if(customerP <13) {
System.out.println("The unit price of customer 1 is: 5");
}else {
if(customerP <19) {
System.out.println("The unit price of customer 1 is: 8");
}else {
System.out.println("The unit price of customer 1 is: 10");
}
}
}
How do I add a while loop to ask the to ask the age for each customer?
Here you go:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter No of Customers: ");
int noCustomers = scanner.nextInt();
if (noCustomers < 1) {
throw new IllegalArgumentException("No of Customers has to be 1 or greater");
}
int[] customerAges = new int[noCustomers];
for (int i = 0; i < noCustomers; i++) {
System.out.println("Enter age for customer: " + i);
customerAges[i] = scanner.nextInt();
}
System.out.println("Ages: " + Arrays.toString(customerAges));
Below provides code using while loop
Scanner sc = new Scanner(System.in);
int customerCount = sc.nextInt();
int[] ageOfCustomers = new int[customerCount];
int i=0;
while(customerCount-- > 0) {
ageOfCustomers[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(ageOfCustomers));
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();
}
My teacher wants us to make a program that counts the total number of votes for two candidates from a variable number of precincts. So the user inputs the candidates’ names as strings and is then prompted to enter the number of precincts prior to entering the votes for each precinct. What I am having trouble with is that I have to use an array to keep each precinct's vote total. Then after all of that is done I have to keep a running total of the votes for each candidate after each precinct is completed and who is currently leading and by how much. I have already begun my program but I am honestly just lost as to where to go from here, and I know that what I have in my arrays so far is not correct.
import java.util.*;
public class Voting
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
int rerun;
int rerun2;
while (rerun == 1)
{
System.out.print("Name of candidate 1: ");
candidate1 = scan.next();
System.out.print("Name of candidate 2: ");
candidate2 = scan.next();
System.out.print("\nPlease enter amount of precincts: ");
presincts = scan.nextInt();
System.out.print("\n Please enter amount of votes for candidate 1: ");
votes1 = scan.nextInt();
System.out.print("\n Please enter amount of votes for candidate 2: ");
votes2 = scan.nextInt();
while (rerun2 == 1 && precincts >= 0 && votes1 >= 0 && votes2 >= 0)
{
int[] votes1 = new int[precincts];
for(int i = 0; i < votes1.length; i++)
{
votes1[i] = int [i];
System.out.println ("\n" + votes1);
}
int[] votes2 = new int[precincts];
for(int i = 0; i < votes2.length; i++)
{
votes2[i] = int [i];
System.out.println ("\n" + votes2);
}
}
}
}
}
I don't know what the function of rerun is so I've left it out of this answer.
First thing you're going to want to do is initialize your variables at the start of your class:
String candidate1;
String candidate2;
int precincts;
int vote1;
int vote2;
int total1;
int total2;
int[] votes1;
int[] votes2;
Note you had a typo in precincts
Then you need to get the name of the candidates and the number of precincts (you've done this correctly already):
Scanner scan = new Scanner(System.in);
System.out.print("Name of candidate 1: ");
candidate1 = scan.next();
System.out.print("Name of candidate 2: ");
candidate2 = scan.next();
System.out.print("\nPlease enter amount of precincts: ");
precincts = scan.nextInt();
Then you need to iterate through the number of precincts, and get the number of votes for each candidate from each precinct. You can do this by initializing an empty array which will keep the votes stored (eg, the votes for the first candidate in precinct 1 will be stored in votes1[0]). Additionally, the easiest way to keep a running total is to use a separate variable total1 and total2:
total1 = 0;
total2 = 0;
votes1 = new int[precincts];
votes2 = new int[precincts];
for (int i = 0; i < precincts; i++) {
System.out.print("\nPlease enter amount of votes for candidate 1 in precinct " + (i + 1) + ": ");
vote1 = scan.nextInt();
votes1[i] = vote1;
total1 = total1 + vote1;
System.out.print("\nPlease enter amount of votes for candidate 2 in precinct " + (i + 1) + ": ");
vote2 = scan.nextInt();
votes2[i] = vote2;
total2 = total2 + vote2;
}
From inside the for loop you can do things like print the current total votes for a candidate:
System.out.println(candidate1 + " has " + total1 + " votes in total");
And print out who is the current leader and by how many votes:
if (total1 > total2) {
System.out.println(candidate1 + " is winning by " + (total1-total2) + " votes");
} else {
System.out.println(candidate2 + " is winning by " + (total2-total1) + " votes");
}
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
I'm trying to print a message saying "Wrong", followed by another chance to enter the value every time the user enters something that's not an int.
I have the following code:
do {
System.out.println("Enter last name: ");
lastName = input.next();
System.out.println("Enter first name: ");
firstName = input.next();
do {
System.out.println("Enter exam 1 score: ");
if (input.hasNextInt()) {
ex1 = input.nextInt();
System.out.println("Enter exam 2 score: ");
ex2 = input.nextInt();
System.out.println("Enter exam 3 score: ");
ex3 = input.nextInt();
valid = true;
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
} while (!valid);
which seems to work fine only if the user makes a mistake for exam 1, but if they do it on exam 2 or 3, it gives me an error.
I'll appreciate your help.
Try not to write the same code again and again. Use a loop.
final int MAX_SCORES = 3;
while (true) {
System.out.println("Enter last name: ");
String lastName = input.next();
System.out.println("Enter first name: ");
String firstName = input.next();
int scores = new int[MAX_SCORES];
for (int i = 0; i < MAX_SCORES; ) {
System.out.printf("Enter exam %d score: ", i + 1);
if (input.hasNextInt()) {
scores[i++] = input.nextInt(); // increment 'i' after assignment
} else {
System.out.println("Incorrect choice. Write the score in numbers.\n");
// Loop will repeat at same value of 'i'
}
}
System.out.println("Again? (Y/N)");
if (input.next().equalsIgnoreCase("n")) break; // Prevents infinite loop
}
You've only made the check for input user 1. You need to do seperate if statements for each user.
if (input.hasNextInt()) {
ex1 = input.nextInt();
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
System.out.println("Enter exam 2 score: ");
if (input.hasNextInt()) {
ex2 = input.nextInt();
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
System.out.println("Enter exam 3 score: ");
if (input.hasNextInt()) {
ex3 = input.nextInt();
valid = true;
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
It would be better to wrap up the else code in a method or something, but that's the idea.
My program has no syntax error, I can input all the value, but I just can't get the final average number right. Can anyone help me find out the problem?
The following is what I input:
How many employees do you have? 4
How many days was Employee #1 absent? 4
How many days was Employee #2 absent? 2
How many days was Employee #3 absent? 1
How many days was Employee #4 absent? 3
Final answer should be: 2.5
This is the code I use:
import java.util.Scanner;
class Number {
public static void main(String[] args) {
int numEmployee = Number.workers();
int absentSum = Number.totaldays(numEmployee);
double averageAbsent = Number.average(numEmployee, absentSum);
}
public static int workers() {
int number = 0;
Scanner input = new Scanner(System.in);
while (number > 0 || number < 0 || number == 0) {
System.out.println("How many employees do you have?");
number = input.nextInt();
if (number >= 0) {
return number;
} else {
System.out
.println("You can not enter a negative number."
+ " Please enter another number.");
}
}
return number;
}
public static int totaldays(int numEmployee) {
int absentDays = 0;
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
return absentSum;
}
public static double average(int numEmployee, int absentSum) {
double averageAbsent = (double) absentSum / (double) numEmployee;
System.out.println("Your employees averaged " + averageAbsent
+ " days absent.");
return averageAbsent;
}
}
Move absentSum += absentDays; into the loop body in totaldays. If you restrict the visibility of absentSum then the compiler will tell you that you are accessing it out of scope. Something like
public static int totaldays(int numEmployee) {
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
int absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
// absentSum += absentDays;
return absentSum;
}
With the above output (and your provided input) I get (the requested)
2.5