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
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())
I was working on a project for class and everything works fine until the code the professor gave us that will prompt the user to "doOver" the code if they choose to, it's coming out with this error and I'm frankly confused.
I tried changing the sc.nextLine to a .hasNextLine as I've seen in other posts, but it comes up with an error stating it needs to be a boolean and then says I can not use the next doOver.trim() code on a boolean.
final static String TITLE = "ISBN-13 Generator!";
final static String CONTINUE_PROMPT = "\nDo this again? [y/n] ";
static Scanner input = new Scanner(System.in);
private static void process(Scanner sc, String args[]) {
boolean numberChecker;
String isbn;
do {
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
input.close();
isbn = isbn.trim();
numberChecker = true;
int s = 0;
do {
numberChecker = numberChecker && Character.isDigit(isbn.charAt(s));
s++;
} while (s < isbn.length() || numberChecker == false);
} while (isbn.length() != 12 & numberChecker == false);
int sum = 0;
int s = 0;
do {
if (s % 2 == 0) {
sum = sum + isbn.charAt(s) - 48;
} else {
sum = sum + 3 * (isbn.charAt(s) - 48);
}
s++;
} while (s < 12);
{
sum = 10 - (sum % 10);
if (sum == 10)
sum = 0;
}
System.out.println("Your ISBN is " + isbn + sum);
}
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.trim().equalsIgnoreCase("Y");
}
public static void main(String args[]) {
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using the " + TITLE);
}
It should display "Do this again? [y/n]" with you inputting "y" to start the process over and entering "n" to stop and have the system print out ("Thank you for using the " + TITLE)
This is happening because you have closed the scanner instance already using line input.close();
Just comment out or delete input.close(); and your program will work as expected.
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
//input.close();
Let me know if it helps! :)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically my professor told me to make use of arraylist? I don't get his point to be honest.. i think he wants me to add objects to arraylist? which right now, I really have no idea how to do it..
My code is running and is really fine. However, he still wanted me to make use of arraylist to make it look better?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ahaprogram2;
import java.util.ArrayList;
import java.util.Scanner;
public class AhaProgram {
public static Container container1 = new Container("Container 1: ");
public static Container container2 = new Container("Container 2: ");
public static Container container3 = new Container("Container 3: ");
public static Container container4 = new Container("Container 4: ");
public static Container container5 = new Container("Container 5: ");
public static boolean loop = false;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Hello! This is the AHA Program of Jalosjos,
Parreno and Alfonso");
System.out.println("Please type the letter of your option");
while (loop != true) {
showOptions();
InputHandler();
}
}
public static void InputHandler() {
Scanner reader = new Scanner(System.in);
String optionletter = reader.nextLine();
if (optionletter.equals("A")) { // OPTION A
System.out.println("There are 5 containers.. What container
will you name? ");
System.out.print("Type the number of your container: ");
String contInput = reader.nextLine();
if (contInput.equals("1")) {
System.out.print("Input the name of Container 1: ");
String ContInp1 = reader.nextLine();
container1.renameCont(ContInp1);
container1.printContainer();
} else if (contInput.equals("2")) {
System.out.print("Input the name of Container 2: ");
String ContInp2 = reader.nextLine();
container2.renameCont(ContInp2);
container2.printContainer();
} else if (contInput.equals("3")) {
System.out.print("Input the name of Container 3: ");
String ContInp3 = reader.nextLine();
container3.renameCont(ContInp3);
container3.printContainer();
} else if (contInput.equals("4")) {
System.out.print("Input the name of Container 4: ");
String ContInp4 = reader.nextLine();
container4.renameCont(ContInp4);
container4.printContainer();
} else if (contInput.equals("5")) {
System.out.print("Input the name of Container 5: ");
String ContInp5 = reader.nextLine();
container5.renameCont(ContInp5);
container5.printContainer();
}
}
if (optionletter.equals("B")) { // for option B
System.out.println("Which container will you use?");
System.out.print("Type a number for the container: ");
String contforAdd = reader.nextLine();
if (contforAdd.equals("1")) {
System.out.print("How many cans will you add?: ");
int numofCans1 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans1; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container1.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("2")) {
System.out.print("How many cans will you add?: ");
int numofCans2 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans2; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container2.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("3")) {
System.out.print("How many cans will you add?: ");
int numofCans3 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans3; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container3.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("4")) {
System.out.print("How many cans will you add?: ");
int numofCans4 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans4; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container4.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("5")) {
System.out.print("How many cans will you add?: ");
int numofCans5 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans5; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container5.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
}
if (optionletter.equals("C")) {
System.out.println("Which container will you use?");
System.out.print("Type a number for the container: ");
String contforRemove = reader.nextLine();
if (contforRemove.equals("1")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container1.RemoveCan(canRemove);
}
if (contforRemove.equals("2")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container2.RemoveCan(canRemove);
}
if (contforRemove.equals("3")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container3.RemoveCan(canRemove);
}
if (contforRemove.equals("4")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container4.RemoveCan(canRemove);
}
if (contforRemove.equals("5")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container5.RemoveCan(canRemove);
}
}
if (optionletter.equals("D")) {
showOptionsDisplay();
System.out.print("Type a letter: ");
String letterDisplay = reader.nextLine();
if (letterDisplay.equals("A")) {
container1.printContents();
System.out.println("");
}
if (letterDisplay.equals("B")) {
container2.printContents();
System.out.println("");
}
if (letterDisplay.equals("C")) {
container3.printContents();
System.out.println("");
}
if (letterDisplay.equals("D")) {
container4.printContents();
System.out.println("");
}
if (letterDisplay.equals("E")) {
container5.printContents();
System.out.println("");
}
if (letterDisplay.equals("F")) {
container1.printContents();
System.out.println("");
container2.printContents();
System.out.println("");
container3.printContents();
System.out.println("");
container4.printContents();
System.out.println("");
container5.printContents();
System.out.println("");
}
}
if (optionletter.equals("E")) {
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Thank you for using our program. MWAH!");
loop = true;
}
}
public static void showOptions() {
System.out.println("A = Name Containers");
System.out.println("B = Add Cans");
System.out.println("C = Remove Cans");
System.out.println("D = Display Cans");
System.out.println("E = Quit");
System.out.print("Type a Letter: ");
}
public static void showOptionsDisplay() {
System.out.println("Pick an Option");
System.out.println("A = Display container 1");
System.out.println("B = Display container 2");
System.out.println("C = Display container 3");
System.out.println("D = Display container 4");
System.out.println("E = Display container 5");
System.out.println("F = Display all containers");
}
}
Here is the other class
package ahaprogram2;
import java.util.ArrayList;
import java.util.Scanner;
public class Container {
Scanner reader = new Scanner(System.in);
public ArrayList<String> CanContainer = new ArrayList<String>();
public int Contsizep;
public String contName;
public String changeName;
public Container(String contname){
this.contName = contname;
}
public void AddCan(String CantoAdd) {
this.CanContainer.add(CantoAdd);
}
public void RemoveCan(String CantoRemove) {
if (this.CanContainer.contains(CantoRemove)) {
this.CanContainer.remove(CantoRemove);
System.out.println("** " + CantoRemove + " Can removed
successfully**");
}
else {
System.out.println("Can cannot be found.. make sure to put the
exact name!!");
}
}
public void renameCont(String changename) {
this.contName += changename;
}
public void printContents() {
System.out.println("Here are the contents of " + contName);
System.out.println("");
for(String counter : this.CanContainer){
System.out.println(counter); }
}
public void printContainer() { // for OPTION A ONLY
System.out.println("CONTAINER NAME SUCCESSFUL: ** " + contName +
"**");
}
}
I just would like to put everything to an arraylist
please help.. again my professor doesn't teach us face to face that's why
I'm really trying my best to watch videos in youtube and to ask here also..
A lot of your code seems to predicate on interacting one of five Container objects in similar (if not identical) ways. To start, you can use an ArrayList to store a list of Container objects, instead of manually declaring each container:
public static ArrayList<Container> containerList = new ArrayList<Container>();
You can then populate this list with new containers using ArrayList.add(E e), combined with a for loop or some other construct:
for (int i = 1; i <= 5; i++) {
Container container = new Container("Container " + i + ": ");
containerList.add(container);
}
Likewise, you can access any particular container using ArrayList.get(int index) (if you know the index) or ArrayList.indexOf(Object o) (if you have a reference to a specific container). This can replace or supplement your conditional statements. For instance, your list of (contInput.equals("X")) statements could be replaced with:
int index = Integer.parseInt(contInput);
System.out.print("Input the name of Container " + index + ": ");
Container container = containerList.get(index - 1); // arrays start at 0, but your numbering starts at 1
String contImp = reader.nextLine();
container.renameCont(contImp);
container.printContainer();
Hope this helps.
You can add your containers to ArrayList like this:
ArrayList<Container> containers = new ArrayList<>();
containers.add(new Container("Container 1: "));
containers.add(new Container("Container 2: "));
containers.add(new Container("Container 3: "));
then get them like this:
Container firstContainer = containers.get(0);
Container secondContainer = containers.get(1);
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");
}
}
I have a question with the display array method. I can't figure how to make it to format this:
Credit Card # 4:
8908 9014 8812 1331
What I need to do is for each array element call the display method and pass the index of the array in a string for the label, I just cant figure out how to do this, I tried this but it is wrong:
System.out.println(display("Credit Card # %d", cred1[i]));
Can anyone please suggest a way to do this?
package homework4;
import java.util.Scanner;
public class Prog4 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{ CreditCardNumber[] cred1;
CreditCardNumber cred2 = getInput();
Display("The complete number from your input:", cred2);
cred1 = getInputArray();
DisplayArray(cred1);
TryAnother();
}
public static CreditCardNumber getInput() {
String ID;
String accNum;
CreditCardNumber tempCred;
System.out.printf("Please enter issuer ID:");
ID = scanner.next();
System.out.printf("Please enter account number:");
accNum = scanner.next();
tempCred = new CreditCardNumber(ID, accNum);
return tempCred;
}
public static void Display(String ch, CreditCardNumber cred2)
{
System.out.println(ch);
System.out.println(cred2.toString().replaceAll(".{4}", "$0 "));
}
public static CreditCardNumber[] getInputArray()
{
CreditCardNumber[] tempArray;
String tempID;
int size;
System.out.printf("Please enter size of the aray:");
size = scanner.nextInt();
if(size < 1)
{
size = 1;
}
tempArray = new CreditCardNumber[size];
System.out.printf("Please enter issuer ID:");
tempID = scanner.next();
System.out.print(tempArray.length);
for(int i = 0; i < tempArray.length; i++)
{
tempArray[i] = new CreditCardNumber();
tempArray[i].CreateCred(tempID);
}
return tempArray;
}
public static void DisplayArray(CreditCardNumber[] cred1)
{
for(int i = 0; i< cred1.length; i++)
{
System.out.println(display("Credit Card # %d", cred1[i]));
}
}
public static boolean TryAnother()
{
String s;
System.out.printf("Get more credit card numbers? (n for no):");
s = scanner.next();
if(s.charAt(0) != 'N' && s.charAt(0) != 'n')
{
return true;
}
return false;
}
}
sounds like all you need is a new line character. For example.
System.out.println("Credit Card # " + cred1[i] + "\n" + cred2.toString());
The new line character "\n" will drop the output onto it's own line.
Do this:
System.out.format("Credit Card # %d:\n%s", i, cred1[i].toString());