I made a program that accepts numbers from the user.
Sample of my program:
int strength, health, luck;
JOptionPane.showMessageDialog(null,"Welcome to Yertle's Quest");
String name = JOptionPane.showInputDialog("Enter the name of your character");
Scanner in = new Scanner(System.in);
System.out.println("Enter strength (1-10): ");
strength = in.nextInt();
System.out.println("Enter health (1-10): ");
health = in.nextInt();
System.out.println("Enter luck (1-10): ");
luck = in.nextInt();
My problem is this:
The user is only able to give 15 points. If he puts more than 10 points to each stats (strength,health,luck), the default value will be assign to each stats -which is 5. And if the total points on each stats(strength,health,luck) is more than 15, the default value will be assigned to each stats.
Given I understand the question correctly:
if ( luck + health + strength > 15) {
luck = 5;
health = 5;
strength = 5;
}
if (luck > 10) { luck = 5; }
// same for the other attributes
if(strength > 10)
{
defaultToFive(strength);
}
if(health > 10)
{
defaultToFive(health);
}
if(luck > 10)
{
defaultToFive(luck);
}
if((strength + health + luck) > 15)
{
defaultToFive(strength);
defaultToFive(health);
defaultToFive(luck);
}
private void defaultToFive(int stat)
{
stat=5;
}
Use simple if statements:
import java.util.Scanner;
public class CheckLuck {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);int strength,health,luck;
System.out.println("Enter strength (1-10): ");
strength = in.nextInt();
if(strength>10) /* chech for each value, should not be >10 */
strength=5;
System.out.println("Enter health (1-10): ");
health = in.nextInt();
if(health>10)
health=5;
System.out.println("Enter luck (1-10): ");
luck = in.nextInt();
if(luck>10)
luck=5;
if(strength+health+luck>15) /* If sum is >15 assign 5 to each value */
strength=health=luck=5;
}
}
UPDATE : USING public void decide()
(sorry if this sounds funny)
import java.util.Scanner;
public class TestDecide {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);int strength,health,luck;
System.out.println("Enter strength (1-10): ");
strength = in.nextInt();
if(strength>10)
strength=5;
System.out.println("Enter health (1-10): ");
health = in.nextInt();
if(health>10)
health=5;
System.out.println("Enter luck (1-10): ");
luck = in.nextInt();
if(luck>10)
luck=5;
if(strength+health+luck>15)
{
strength=health=luck=5;
decide();
}
else
{
System.out.println("Congrats!!!!!!!!!!!! for your scores");
}
}
public static void decide()
{
System.out.println("You have given your character too many points! Default values have been assigned: Character, strength: 5, health: 5, luck: 5");
}
}
Related
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 1 year ago.
I have been working on a project, and I'm encountering a mistake which I can't seem to solve. I encounter an error "non-static variable initBalance cannot be referenced from a static context". I've researched what this is about, but I don't understand what it means.
Here is my code:
import java.util.Scanner;
public class ATM {
Scanner kbd = new Scanner(System.in);
int initBalance = 0;
public static void main(String[] args) {
System.out.print("\n---------------------ATM----------------\n1. Withdraw\n2. Deposit\n3. Transfer\n4. Check balance\n5. EXIT");
System.out.print("\nChoose operation: ");
int option = kbd.nextInt();
while (option<5) {
if(option==1)
withdraw();
else
if(option==2)
deposit();
else
if(option==3)
transfer();
else
if(option==4)
balanceCheck();
}
}
public static void withdraw() {
System.out.print("Enter amount to be withdrawn: ");
int withdrawBalance = kbd.nextInt();
if (withdrawBalance > initBalance) {
System.out.print("Collect your money.");
initBalance = initBalance - withdrawBalance;
System.out.print("Chceck balance? 1. Yes 2. No : ");
int balanceOption = kbd.nextInt();
if (balanceOption==1) {
System.out.print("Remaining balance: " + initBalance);
}
}
else {
System.out.print("Insufficient Balance");
}
}
public static void deposit() {
System.out.print("Enter amount you want to deposit: ");
int depositBalance = kbd.nextInt();
initBalance = initBalance + depositBalance;
System.out.print("Chceck balance? 1. Yes 2. No : ");
int balanceOption = kbd.nextInt();
if (balanceOption==1)
System.out.print("Remaining balance: " + initBalance);
else
if(balanceOption==2)
System.out.print("\nThank you for using this ATM!");
else
System.out.print("Number not in the option.");
}
public static void transfer() {
System.out.print("Enter Account number: ");
int accNum = kbd.nextInt();
System.out.print("Enter amount to be transferred: ");
int moneySent = kbd.nextInt();
if(moneySent > initBalance) {
System.out.print("Transfer Success!");
initBalance = initBalance - moneySent;
System.out.print("Chceck balance? 1. Yes 2. No : ");
int balanceOption = kbd.nextInt();
if (balanceOption==1)
System.out.print("Remaining balance: " + initBalance);
else
if(balanceOption==2)
System.out.print("\nThank you for using this ATM!");
else
System.out.print("Number not in the option.");
}
else {
System.out.print("Insufficient Balance");
}
}
public static void balanceCheck() {
System.out.print("Remaining balance: " + initBalance);
}
}
Static methods (in your case: withdraw, deposit, transfer, balanceCheck) cannot use not static variable (in your case: initBalance).
In order to use the non static variable you must create an object somewhere ( ATM anATM = new ATM()) and to use the static methods you do not create the object you just do for example: ATM.withdraw())
Everything works so far in my program but I'm having trouble with this section of my code:
else if(input.equals("2")) {
System.out.println("Enter the stock symbol:");
symbol2 = in.next();
System.out.println("Enter the number of shares you wish to sell:");
sellshares = in.nextInt();
String tempsymbol = "";
for(int i=0; i<array1.size(); i++) {
tempsymbol = (array1.get(i)).getSymbol();
if(symbol2.equals(tempsymbol)) {
System.out.println("The dollar cost averaged price per share (LIFO): " + (array1.get(i)).averageCost(sellshares));
System.out.println("The dollar cost averaged price per share (FIFO): " + (array2.get(i)).averageCost(sellshares));
}
}
}
It'll go through the loop but tempsymbol will always = "". Why doesn't array1 return anything?
Here's all my code. Apologies ahead of time if any parts are redundant or messy.
import java.util.*;
public class Whoop {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = "";
String symbol = "";
String name = "";
int shares = 0;
double price = 0;
String symbol2 = "";
int sellshares = 0;
int rolling = 0;
stack theStack = null;
queue theQ = null;
String loopcheck = "1";
ArrayList<stack> array1 = new ArrayList<stack>();
ArrayList<queue> array2 = new ArrayList<queue>();
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine();
in.nextLine();
System.out.println("Enter the stock name:");
name = in.nextLine();
System.out.println("Enter the number of shares bought:");
shares = in.nextInt();
System.out.println("Enter the price per share when purchased");
price = in.nextDouble();
theStack = new stack(symbol,name,shares,price);
theQ = new queue(symbol,name,shares,price);
System.out.println("Press 1 to continue entering new shares or press 2 to finish input for " + theStack.getName());
rolling = in.nextInt();
while(rolling == 1) {
System.out.println("Enter the number of shares bought:");
shares = in.nextInt();
System.out.println("Enter the price per share when purchased");
price = in.nextDouble();
theStack.bigPush(shares, price);
theQ.bigAdd(shares, price);
System.out.println("Press 1 to continue entering new shares or press 2 to finish input for " + theStack.getName());
rolling = in.nextInt();
}
array1.add(theStack); //I added the objects after all the values were finalized
array2.add(theQ);
}
else if(input.equals("2")) {
System.out.println("Enter the stock symbol:");
symbol2 = in.next();
System.out.println("Enter the number of shares you wish to sell:");
sellshares = in.nextInt();
String tempsymbol = "";
for(int i=0; i<array1.size(); i++) {
tempsymbol = (array1.get(i)).getSymbol();
if(symbol2.equals(tempsymbol)) {
System.out.println("The dollar cost averaged price per share (LIFO): " + (array1.get(i)).averageCost(sellshares));
System.out.println("The dollar cost averaged price per share (FIFO): " + (array2.get(i)).averageCost(sellshares));
}
}
}
else {
System.out.println("Input invalid ):");
System.exit(0);
}
System.out.println("Press 1 to continue working with your stocks or press anything else to finish up");
loopcheck = in.next();
}
System.out.println("END");
}
}
This is my queue class which works perfectly fine.
import java.util.LinkedList;
public class queue<E> {
private LinkedList<Double> linklist;
private String symbol;
private String name;
private int shares;
private Double price;
public queue(String symbol2, String name2, int shares2, Double price2) {
linklist = new LinkedList<Double>();
shares = shares2;
price = price2;
symbol = symbol2;
name = name2;
bigAdd(shares, price);
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public void add(Double e) {
linklist.add(e);
}
public Double take() {
return linklist.poll();
}
public void bigAdd (int shares2, Double price2) {
while(shares2>0) {
linklist.add(price2);
shares2--;
}
}
public double averageCost(int shares2) {
double average = 0;
int sizer = 0;
while(sizer < shares2) {
average = average + linklist.poll();
sizer++;
}
average = average/shares2;
return average;
}
And this is my stack class which also works fine.
import java.util.*;
public class stack {
private ArrayList<Double> stackArray = new ArrayList<Double>();
private int top;
private String symbol;
private String name;
private int shares;
private Double price;
public stack(String symbol2, String name2, int shares2, Double price2) {
symbol = symbol2;
name = name2;
shares=shares2;
price=price2;
top = -1;
bigPush(shares, price);
}
public double averageCost(int shares2) {
double average = 0;
int sizer = shares2;
while(sizer > 0) {
average = average + stackArray.get(top--);
sizer--;
}
average = average/shares2;
return average;
}
public void push(Double value) {
stackArray.add(++top, value);
}
public Double pop() {
return stackArray.get(top--);
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public void bigPush(int shares2, Double price2) {
while(shares2>0) {
stackArray.add(++top, price2);
shares2--;
}
}
public static void main(String[] args) {
stack theStack = new stack("Dave", "Franco", 2,10.0);
theStack.bigPush(2,20.0);
System.out.println(theStack.getSymbol());
}
}
Also heres an example of my output:
Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold
1
Enter the stock symbol:
DAVE
Enter the stock name:
FRANCO
Enter the number of shares bought:
5
Enter the price per share when purchased
5
Press 1 to continue entering new shares or press 2 to finish input for FRANCO
2
Press 1 to continue working with your stocks or press anything else to finish up
1
Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold
2
Enter the stock symbol:
DAVE
Enter the number of shares you wish to sell:
1
//AND THEN NOTHING HERE WHEN IT SHOULD RETURN AVERAGECOST()
Press 1 to continue working with your stocks or press anything else to finish up
Following your long code,
tt looks like it all boils down to a wrong usage of the Scanner class :
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine(); // problem here
in.nextLine();
this assigns an empty String to symbol, because it consumes the end of line of the previous in.next().
If you change it to :
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
in.nextLine();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine();
it will work.
Edit :
It looks like you are aware of the need to sometimes call in.nextLine() without using its returned value, but you put in.nextLine() in the wrong place.
I need to design and implement an application called CinemaPrice to determine how much a person pays to go the the cinema. The program should generate an age from 1 - 100 using the Random class and prompt the user for the full ticket price. Then display the appropriate ticket price using the currency format (an example in your book ). You may want to refer to the example we did together in class to help you with the "if statement". Decide ticket price on the following basis:
1. under 5, free;
2. aged 5 to 12, half price;
3. aged 13 to 54, full price;
4. aged 55, or over, free.
I would really like some help on this I'm new to java and been spending hours on this now I would love to finish it :)
This is what I have so far:
import java.util.Scanner; //Needed for the Scanner class
import java.util.Random;
import java.text.DecimalFormat;
public class CinemaPrice
{
public static void main(String[] args) //all the action happens here!
{ Scanner input = new Scanner (System.in);
int age = 0;
double priceNumber = 0.00;
Random generator = new Random();
age = generator.nextInt(100) + 1;
if ((age <= 5) || (age >=55) {
priceNumber = 0.0;
}else if (age <= 12){
priceNumber = 12.50;
}else {
system.out.println("Sorry, But the age supplied was invalid.");
}
if (priceNumber <= 0.0) {
System.out.println("The person age " + age + " is free!);
}
else {
System.out.println("Price for the person age " + age + "is: $" + priceNumber);
}
} //end of the main method
} // end of the class
I don't know how to prompt and read input from a user though - can you help?
The first issue that I see is that you need to update your conditional statement here as anything from 13 to 54 will be an invalid age...
if ((age <= 5) || (age >=55) {
priceNumber = 0.0;
}else if (age <= 12){
priceNumber = 12.50;
}else if (age < 55){
//whatever this ticket price is
}else {
system.out.println("Sorry, But the age supplied was invalid.");
}
Something like that would work...
You have stated that your real problem is getting data into your program, the following should demonstrate using the Scanner class
public static void main(String[] args) {
System.out.println("Enter an age");
Scanner scan=new Scanner(System.in);
int age=scan.nextInt();
System.out.println("Your age was " + age);
double price=scan.nextDouble();
System.out.println("Your price was " + price);
}
Now thats the basic idea, but if you provide an incorrect input (like a word) you can get an exception, you can however check that the input you're getting is correct and only accept it if its what you want, like this;
public class Main{
public static void main(String[] args) {
System.out.println("Enter an age");
Scanner scan=new Scanner(System.in);
while (!scan.hasNextInt()) { //ask if the scanner has "something we want"
System.out.println("Invalid age");
System.out.println("Enter an age");
scan.next(); //it doesn't have what we want, demand annother
}
int age = scan.nextInt(); //we finally got what we wanted, use it
System.out.println("Your age was " + age);
}
}
I am writing some code to help teach me how code in java and I have been using arrays. I have an error that I can't work out why it is occurring.
The Code:
import java.util.Scanner;
public class pubQuizArray {
private static Scanner kb = new Scanner (System.in);
static String[] questions;
static String[][] answers;
static char[] realAnswers;
static char ans;
static char yn;
static int questionNum;
static int questionNumArray;
static int numQ;
static int score = 0;
public static void writeQuiz()
{
getQNum();
getQ();
}
public static void getQNum()
{
System.out.println("How many Questions?");
numQ = kb.nextInt();
questions = new String[numQ];
}
public static void getAns()
{
questionNumArray = questionNum - 1;
answers = new String[numQ][];
System.out.println("What are the answers?");
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
System.out.println("b: ");
answers[questionNumArray][1] = kb.nextLine();
System.out.println("c: ");
answers[questionNumArray][2] = kb.nextLine();
System.out.println("d: ");
answers[questionNumArray][4] = kb.nextLine();
realAnswers = new char[numQ];
System.out.println("What is the correct Answer?");
realAnswers[questionNum] = kb.next().charAt(0);
}
public static void getQ()
{
questionNum = 0;
System.out.println("What is the First Question?");
questions[questionNum] = kb.nextLine();
getAns();
questionNum ++;
while(questionNum < numQ)
{
System.out.println("What is the next Question?");
questions[questionNum] = kb.nextLine();
getAns();
questionNum ++;
}
}
public static void askQ()
{
questionNum = 0;
while(questionNum < numQ)
{
System.out.println("Q1: " + questions[questionNum]);
System.out.println("a: " + answers[questionNum][0]);
System.out.println("b: " + answers[questionNum][1]);
System.out.println("c: " + answers[questionNum][2]);
System.out.println("d: " + answers[questionNum][3]);
ans = kb.next().charAt(0);
if(ans == realAnswers[questionNum])
{
System.out.println("That was correct");
score ++;
}
}
}
public static void menu()
{
System.out.println("Would you like to write a new Quiz? y/n");
yn = kb.next().charAt(0);
while(yn == 'y')
{
writeQuiz();
System.out.println("Would you like to play the Quiz? y/n");
yn = kb.next().charAt(0);
while(yn == 'y')
{
askQ();
System.out.println("Would you like to play again? y/n");
yn = kb.next().charAt(0);
}
}
}
public static void main(String[] args)
{
menu();
}
}
The error is this:
Would you like to write a new Quiz? y/n
y
How many Questions?
10
What is the First Question?
What are the answers?
a:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at pubQuizArray.getAns(pubQuizArray.java:34)
at pubQuizArray.getQ(pubQuizArray.java:56)
at pubQuizArray.writeQuiz(pubQuizArray.java:17)
Thanks in advance for any help that you can give. Please bear in mind that this is just a trial program and that I am still learning java.
OK I have another problem this time it says:
Would you like to write a new Quiz? y/n
y
How many Questions?
1
What is the First Question?
and
What are the answers?
a: a
Exception in thread "main" java.lang.NullPointerException
at pubQuizArray.getAns(pubQuizArray.java:34)
at pubQuizArray.getQ(pubQuizArray.java:57)
at pubQuizArray.writeQuiz(pubQuizArray.java:17)
at pubQuizArray.menu(pubQuizArray.java:96)
at pubQuizArray.main(pubQuizArray.java:110)
and i've updated the other previous code.
At this point, inside getAns()
questionNumArray = questionNum - 1;
answers = new String[numQ][];
System.out.println("What are the answers?");
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
questionNumArray contains the value -1 which is an invalid index for an array.
It comes from
public static void getQ()
{
questionNum = 0; // set to 0
System.out.println("What is the First Question?");
questions[questionNum] = kb.nextLine();
getAns(); // still 0
questionNum ++; // too late
...
}
Edit
The NPE you are getting boils down to
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
you haven't initialized answers[questionNumArray] so it is null. Do the following first
answers[questionNumArray] = new String[someSize]; // someSize should probably be 5 looking at your code
When I enter input that satisfies everything and doesn't trigger any of my errors, the program just exits after last input like it is skipping over the for or if loop.
Also after System.out.printf("Enter the name of your second species: "); it won't allow for any input, it just skips to the next prompt. I'm not sure why that is. The section above it asking for the first species' info works fine.
import java.util.Scanner;
public class HW2johnson_pp1 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Please enter the species with the higher" +
" population first\n");
System.out.printf("Enter the name of your first species: ");
String Species1 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop1 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth1 = keyboard.nextInt();
System.out.printf("Enter the name of your second species: ");
String Species2 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop2 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth2 = keyboard.nextInt();
if (Pop2 > Pop1) {
System.out.printf("The first population must be higher. \n");
System.exit(0);
}
Species input1 = new Species();
input1.name = Species1;
input1.population = Pop1;
input1.growthRate = Growth1;
Species input2 = new Species();
input2.name = Species2;
input2.population = Pop2;
input2.growthRate = Growth2;
if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <=
(input1.predictPopulation(2) - input2.predictPopulation(2))){
System.out.printf(Species2 + " will never out-populate " +
Species1 + "\n");
}
else {
for (int i = 0; input2.predictPopulation(i) <=
input1.predictPopulation(i); i++) {
if (input2.predictPopulation(i) == input1.predictPopulation(i)) {
System.out.printf(" will out-populate \n");
}
}
}
}
}
This for the predictPopulation():
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;
return result;
}
This is because you never print anything after Species 2 overtakes Species 1, except in the very special case that Species 2 and Species 1 have exactly the same population in some year.
This is because, when you enter Species 1's growth rate, you enter an integer, and then press Enter. keyboard.nextInt() swallows the integer, but leaves the newline on the input-buffer, so the subsequent keyboard.nextLine() thinks there's an empty line there waiting for it.