First of all, this is my assignment question, and I was totally struggling for 2 weeks. If I want to calculate the ticket price, but the first three ticket price is 50, and the subsequence ticket is 45, but I tried do while loop, while loop and for loop, it will start over the program and start with the price 50, so how do I change the price to 45 when the program loop for 4 times?
public void setPrk(){
int[] ticket_add= new int[9999];
ticket_amount= ticket_add.length;
Ticket ticket= new Ticket();
Scanner s= new Scanner(System.in);
ticket.setTicketAmt();
for(int i=0;i<ticket_amount;i++){
System.out.print("Enter your choice (T/W/A): ");
prk=s.next().toLowerCase().charAt(0);
while(!(prk=='t'||prk=='T'||prk=='w'||prk=='W'||prk=='a'||prk=='A')){
System.out.println("Invalid option, try again");
System.out.print("Enter your choice: ");
prk=s.next().toLowerCase().charAt(0);
}
switch(prk){
case't':
ticket.setAge();
Ticket.ThemePark();
break;
case'w':
ticket.setAge();
Ticket.WaterPark();
break;
case'a':
ticket.setAge();
Ticket.AllPark();
break;
default:
break;
}
System.out.println("Your ticket fee will be "+(sum+(sum*0.06)));
}
}
public char getPrk(){
return prk;
}
public void setTicketAmt(){
Scanner s=new Scanner(System.in);
System.out.print("Enter your ticket amount: ");
while(!s.hasNextInt()){
System.out.println("This is not an integer, try again");
System.out.print("Enter your ticket amount: ");
s.next();
}
ticket_amount=s.nextInt();
while(ticket_amount<=0||ticket_amount>9999){
System.out.println("Invalid ticket amount, try again");
System.out.print("Enter your ticket amount: ");
while(!s.hasNextInt()){
System.out.println("This is not an integer, try again");
System.out.print("Enter your ticket amount: ");
s.next();
}
ticket_amount=s.nextInt();
}
}
public static int getTicketAmt(){
return ticket_amount;
}
public static void ThemePark(){
double[] ticket= new double[2];
double ticketSize[]={0};
if(age<17){
if(ticket_amount<=3){
ticket[0]=50;
ticketSize[0]=ticket[0];
}
if(ticket_amount>3){
for(int i=0;i<=3;i++){
ticket[0]=50;
ticketSize[0]=ticket[0];
}
for(int i=0;i>3&&i<ticket_amount;i++){
ticket[1]=45;
ticketSize[0]=ticket[1];
}
}
for(int k=0;k<ticketSize.length;k++){
sum+=ticketSize[k];
}
}
}
The question is vastly unclear.
I assumed you tried to put in most relevant parts. However, some important variables are missing (e.g., age), and unrelated parts (e.g., the switch(pkg)) could be removed from your question.
On the other hand, if that is all of the source code, it is best to state what are you trying to do in which functions.
Anyway, I presume you are trying to work on the price in the ThemePark function, and here's my solution to it:
public double ThemePark(int age, int ticket_amount) {
// I used a double variable to store the total value, but the `static` attribute
// is removed for demonstrating a whole function.
double ticketSum = 0;
if (age < 17) {
for (int i = 0; i < ticket_amount; i++) {
// The above fucntion of `for(int i=0; i>3&&i<ticket_amount:i++)` is genuinely
// incorrect, as i would never increment to i>3 in such case, it should be set
// as `i=4`. However, in such case it cannot registered the ticket_amount=4. As
// a result, it should also be set as `<=ticket_amount`.
if (i <= 3) {
ticketSum += 50;
} else {
ticketSum += 45;
}
}
}
return ticketSum;
}
Please state in the question if there's more specifications, and I hope this answer helps.
Related
I am trying to call the method gasCost from the main method. I give the user the choice of entering a number to bring up a certain calculation, in this instance the user has selected option 3. The integer gallons_Gas is defined in the main method, so I am passing that into gasCost method.
I get an error after the else statement and can't compile. Says .class expected where the variable name gallons_Gas starts and after gallons_Gas says ; expected. What am I doing wrong and how do I fix this?
public class Deryck_HW2_TripCalculatorMenu
{
public static void main(String[] args)
{
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask for gallons of gas consumed
System.out.print("Gallons of Gas Consumed: ");
//Save gallons of gas consumed
int gallons_Gas = userInput.nextInt();
//Give user options menu
menu();
//Ask user choice
System.out.print("Choose from options above (enter number 1-4): ");
//Get user choice 1-4
int choice = userInput.nextInt();
//Test choice
if (choice == 1)
{
//avgSpeed();
}
else if (choice == 2)
{
//mpg();
}
else if (choice == 3)
{
gasCost(int gallons_Gas);
}
else
{
System.out.print("Error: selection invalid. Restart program and enter a number between 1 and 4.");
}
}
public static void gasCost(int gallons_Gas)
{
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask cost of gallon of gas
System.out.print("What is the cost per gallon of gas? ");
//Save cost per gallon
double gallon_Cost = userInput.nextDouble();
//Calculate total cost
double total_cost = (gallons_Gas * gallon_Cost);
System.out.print("Total cost of gas for this trip was $" + total_cost);
}
Try to understand what these lines mean and note how to call methods, how to pass in variables, when to declare variables etc...
import java.util.Scanner;
public class GasCalculator {
public static void main(String[] args) {
final int GALLONS_GAS = 100; // change this to whatever. It's good practice to use constants for variables that does not need to be immuted.
Scanner sc = new Scanner(System.in);
int user_choice = -1;
try {
user_choice = sc.nextInt();
} catch (Exception e) {
System.out.println("Only enter integers.");
main(args);
return;
}
switch(user_choice) {
case 1:
// do something.
break;
case 2:
// do something.
break;
case 3:
gasCost(GALLONS_GAS);
break;
default:
System.out.println("Bad input");
main(args);
break;
}
sc.close();
}
public static void gasCost(int gallons_Gas) {
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask cost of gallon of gas
System.out.print("What is the cost per gallon of gas? ");
//Save cost per gallon
// should try using a try-catch here to handle InputMismatchException
double gallon_Cost = userInput.nextDouble();
//Calculate total cost
double total_cost = (gallons_Gas * gallon_Cost);
System.out.print("Total cost of gas for this trip was $" + total_cost);
userInput.close();
return;
}
}
I don't know if this is a pseudo-code or just the real code. If it is the real code, there are several mistakes:
gasCost(int gallons_Gas);
You should know the differences between formal parameters and actual parameters. In the actual parameters type of variable is not required, instead of formal parameters. Link:
What is a formal parameter in Java?
So, that code should be like:
int gallons_gas = 5; //Just for example
gasCost(gallons_Gas);
After that, you should listen to the guys in the comments: be sure where that else if statement is, if you put it in the wrong way it won't work.
Hope it helps
gasCost(int gallons_Gas);
should be
int gallons_Gas;
if (...) {
gasCost(gallons_Gas);
}
You cannot declare an int within the parameter list of a method call.
Hello guys I am having a problem with an array and a .nextInt(); this is causing my output line at the 3rd prompt to shift up instead of under, and seriously cannot figure out what's wrong.
I have tried .hasNextInt(); but nothing, it actually gives me an error, so here is the code:
import java.util.Random;
import java.util.Scanner;
public class birthday {
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn); //my problem
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //my problem
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2];
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
// Method for calculations
public static double compute(int numOfSimulation, int numOfPeople)
{
for (int i =0; i < numOfPeople; i++)
{
Random rnd = new Random(1);
//Generates a random number between 0 and 364 exclusive
int num = rnd.nextInt(364);
System.out.println(num);
System.out.println(num / 365 * numOfPeople * numOfSimulation);
}
return numOfPeople;
}
}
Found it!!!!!!!!!!!
do this:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return(userInput);
}
To return the array
Let me know!
I actually don't think you can do it there with that userInput, I am saying this because the methodology of doing this program is quite arcane.
You are then calling 2 arrays at prompting, I wonder if you might change that to one what will change such as:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
As also the return promptAndRead(stdIn); might be part of the problem
Don't know though just trowing suggestions at Markov ;)
I created a method that returns a row of arrays via user input. I managed to display the set of inputted number on the same class using System.out.println by assigning each value in userDigits.
My question is, how can I pass the same value in another class?
public class LottoTicket extends Ticket {
public int NUM_DIGITS = 5;
public int[] userDigits = new int[NUM_DIGITS];
#Override
public void buyTicket() {
Scanner input = new Scanner(System.in);
int number = 0;
double amount = 0;
System.out.println("-------=======LOTTO TICKET SCREEN=======--------");
System.out.println("");
System.out.println("There are three Types (Prima, Ambo and Terro)");
System.out.print("Please select one (P, A, T): ");
String lotteryOption = input.next();
switch (lotteryOption) {
case "P": {
break;
}
case "A": {
break;
}
case "T": {
amount = getAmount(amount);
getUserData(userDigits);
int ticketSold;
ticketSold = +1;
int tik = ticketSold +1;
System.out.println(amount);
System.out.println("Your numbers are: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " ");
System.out.println("Ticket/s Sold: " + tik);
System.out.println("Thank you for playing");
Ticket.pressAnyKeyToContinue();
LotteryApplication.loginScreen();
break;
}
default: {
System.out.println("Invalid Input. Please try again.");
System.out.println("");
buyTicket();
break;
}
}
}
#Override
public double getAmount(double amount) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter amount of money: ");
amount = input.nextDouble();
//input.close();
return amount;
}
#Override
public int getUserData(int[] userInput) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a number from 1 to 90: ");
userDigits[0] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[1] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[2] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[3] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[4] = input.nextInt();
//key.close();
//Returns last value of array
return userDigits[4];
}
//public int userDigits[];
public static void printTicket(){
// System.out.println(getUserData.userDigits[4]);
// for (int i = 0; i < array.length)
}
}
Well, in this case, since you defined userDigits as public, you can do it easily - it is accessible to any class that has a visibility to your instance of LottoTicket. With the current setup you could do something like this:
// you need to instantiate LottoTicket somewhere in your app
LottoTicket ticket = new LottoTicket();
// get the input from user
ticket.buyTicket();
// at this point you can access the numbers and pass them to some other method like this
checkNumbers(ticket.userDigits);
The example posted above needs you to provide a method checkNumbers that has, for example, the following signature:
public void checkNumbers(int[] numbers) {
// the comparison code goes here...
Also, this is somewhat unrelated to your question, but I'd like to point out two issues with your current code:
defining class fields as public is done rather rarely, more common approach is to define these as private and provide methods for getting/setting the field values; this restricts the operation on these fields to only those you allow - having public field allows anyone who has a visibility to that field to perform basically any operations, which is usually not what you want
you call buyTicket() from default in case user didn't select valid lottery type; in extreme cases this could lead to StackOverflowError - better approach would be to use a loop that keeps asking user for input until a valid one is provided
Hope this helps at least a bit.
You can easily pass input array to method of another class arguments.
class PassValue{
public static void display(int[] elements){
Anotherclass obj= new Anotherclass();
obj.display2(elements);
}
}
class Anotherclass{
public void display2(int[] values){
do whatever you want
}
}
The objective is to create an account registration method for an ATM object. But I keep breaking on the if statement used to enter the loop. I assume my "wording" is off, but I'm drawing a blank on how to fix it. Any suggestions? The problem itself is at if(acc[i].getAcc()==0)where .getAcc is a getter in a class.
package atmassignment;
import java.util.Scanner;
public class AtmAssignment {
static Scanner in = new Scanner(System.in);
static int cou = 1;
static Account[] acc = new Account[10];
public static void main(String[] args) {
menu();
}
public static void menu(){
char opt;
System.out.println("Thanks for accessing ATManager.");
System.out.println("Please select a menu option to proceed.");
System.out.println("1-Register a new account, 2-Access an account, 0-Exit ATManager");
opt = in.next().charAt(0);
switch (opt) {
case '1':
newAccount();
break;
case '2':
selAccount();
break;
case '0':
System.out.println("Goodbye.");
break;
default:
System.out.println("Invalid Entry.");
break;
}
}
public static void newAccount(){
System.out.println("Account registration");
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i] = new Account(cou, bal, cus);
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
}
}
This allocates an array of object references:
static Account[] acc = new Account[10];
However it doesn't actually allocate any objects, so you are probably getting a null pointer exception when you try to access the first element. In your init code, do something like this:
for(int i = 0; i < 10; i++)
acc[i] = new Account();
You call acc[i].getAcc()==0 before actually constructing your objects. Maybe modify the for loop so that you create your objects and then gather input and update your objects later on with setter methods? This of course requires that you have some sort of default constructor for your Account class.
acc[j through maxLength] = new Account(); //where j spans the entire length of the array
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i].setContact(###);
acc[i].setBalance(###); //ETC
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
Probably you didn't populate your Account[] array. Here I only can see you declare your array like -
static Account[] acc = new Account[10];
So after that when you are trying to get you array element using for loop than you can't access them. You are getting the error at if(acc[i].getAcc()==0) this line. So I suggest remove the if check since you are populating your Account later in this line - acc[i] = new Account(cou, bal, cus);
Hope it will help.
Thanks a lot.
I am trying to make a simple text based operating system and I cant figure out why my code doesn't let me enter a command after the calculator class is done. It is supposed to continue executing the code until I type "off" but this is not the case. Eclipse says it is running but I cant do anything. can someone please help me?
here is my two classes:
public class Calculator extends Start{
public static void calStrt() {
System.out.print("\nEnter operator you wish to use: ");
StringInput = scan.nextLine();
if (StringInput.equals("+")) {
add();
} else if (StringInput.equals("-")) {
sub();
} else if (StringInput.equals("*")) {
mul();
} else if (StringInput.equals("/")) {
div();
} else {
System.out.println("\nSyntax error: Operator not recognized");
System.out.println("Please try again");
calStrt();
}
}
public static void add() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 + intVar2));
}
public static void sub() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 - intVar2));
}
public static void mul() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 * intVar2));
}
public static void div() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 / intVar2));
}
}
import java.util.Scanner;
class Start {
static Scanner scan = new Scanner(System.in);
static String StringInput;
static int intInput;
public static void main(String[] args) {
System.out.println("\nWelcome to RobOS");
passLoop: while (true) {
System.out.print("\nPlease enter password: ");
StringInput = scan.nextLine();
if (StringInput.equals("banana")) {
System.out.print("Logging in, please wait");
System.out.print(".");
System.out.print(".");
System.out.println(".");
System.out.println("\nWelcome User");
outerLoop: while (true) {
System.out.println("\nType \"help\" to see a list of programs");
StringInput = scan.nextLine();
innerLoop: while (true) {
if (StringInput.equalsIgnoreCase("cal")) {
Calculator.calStrt();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("guess")) {
GuessGame.guess();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("help")) {
System.out.println("\n\"cal\" uses the calculator");
System.out.println("\"guess\" plays guessing game");
System.out.println("\"help\" shows list of programs");
System.out.println("\"off\" turns RobOS off");
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("off")){
break passLoop;
}
}
}
} else {
System.out.println("\nWrong password. Please try again");
continue passLoop;
}
}
}
}
Brent Nash is correct. To fix the error though, try using instead of scan.nextInt(): Integer.parseInt(scan.nextLine());
Hope this works
Your code is getting into an infinite loop. When you call StringInput = scan.nextLine(), the first time it works fine. I entered cal and I can run the calculator once. The problem is that the second time scan.nextLine() gets called, it's automatically returning an empty string "" as the value of StringInput. Your set of if/else statements in the while(true) have no way to handle this, so it just loops forever.
The deeper rationale is that you call scan.nextInt() to read in the numbers, but the problem is when you read in the second number for the calculator operation, there's still a "\n" sitting on System.in. As a result, when you loop around and call scan.nextLine() again, it doesn't prompt you for anything because it just reads that "\n" that's still sitting on System.in and then that sends you into an infinite loop.