array display method difficulty - java

newbie here. So i'm testing out arrays, it's the next topic in the tutorial that i have been reading. I made a simple program to specify how many numbers to get or to input. The problem is on the getArray() method, i can't seem to display it. It's giving me an exception in thread error. Any help and advice is much appreciated. :) Sorry for the newbie question. :))
So here's the code.
import java.util.Scanner;
public class ArrayNumbers {
Scanner input = new Scanner(System.in);
int totalNum, counter, count = 0, display;
double arrayNum[];
public void setArrayNum() {
System.out.print("How many numbers?: ");
totalNum = input.nextInt();
double arrayNum[] = new double[totalNum];
for (counter = 0 ; counter < arrayNum.length ; counter++) {
System.out.print("Num "+(count = counter + 1)+": ");
arrayNum[counter] = input.nextInt();
}
}
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
System.out.print(arrayNum[display]);
}
}
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Numbers NumbersObject = new Numbers();
ArrayNumbers ArrayNumbersObject = new ArrayNumbers();
String name;
int choice;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.println("Menu");
System.out.println("1. Math Operations");
System.out.println("2. Grade Computation");
System.out.println("3. Counting Numbers");
System.out.println("4. Array Numbers");
System.out.print("Enter choice: ");
choice = input.nextInt();
switch(choice) {
case 1:
System.out.println("Choose Operation");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter choice: ");
choice = input.nextInt();
NumbersObject.setNum();
if (choice == 1)
System.out.println("The answers is "+(NumbersObject.getNum1() + NumbersObject.getNum2()));
else if (choice == 2)
System.out.println("The answers is "+(NumbersObject.getNum1() - NumbersObject.getNum2()));
else if (choice == 3)
System.out.println("The answers is "+(NumbersObject.getNum1() * NumbersObject.getNum2()));
else if (choice == 4)
System.out.println("The answers is "+(NumbersObject.getNum1() / NumbersObject.getNum2()));
else
System.out.print("Invalid Input!");
break;
case 2:
NumbersObject.setNum();
System.out.println("Your average grade is "+((NumbersObject.getNum2() + NumbersObject.getNum2()) / 2));
break;
case 3:
System.out.println("Welcome to Counting Numbers!");
System.out.println("Enter 2 numbers to start and end!");
NumbersObject.setNum();
for (int counter = (int) NumbersObject.getNum1() ; counter <= NumbersObject.getNum2() ; counter++) {
System.out.println(counter);
}
System.out.println("End!");
break;
case 4:
ArrayNumbersObject.setArrayNum();
ArrayNumbersObject.getArray();
break;
default:
System.out.println("Mr/Ms "+name+" you entered an Invalid Choice!");
break;
}//end of switch
}// end of main
}// end of class
Sorry about that, for not including the main.
And here's the error:
Exception in thread "main" java.lang.NullPointerException
at ArrayNumbers.getArray(ArrayNumbers.java:23)
at MainProgram.main(MainProgram.java:67)
Guys, the only i problem i have is in the getArray()
It asks for what number in the array i want to see but when i input it, it gives an exception in the thread error. The only problem is how am i going to display the array[number i specified]? Sorry for the newbie questions.

It throws an exception because you create an array of size display and you try to print the element at the display position but arrays are 0 base indexed in Java.
This figure should be useful :
So imagine that display = 10 :
double arrayNum[] = new double[display]; //create an array that can holds 10 elements
System.out.print(arrayNum[display]); //try to access at the 10th element of the array but it doesn't exists !
You don't have to create a new array because you want to display the number in the arrayNum you created in your class.
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
System.out.print(arrayNum[display]);
}
Also you need to check if display is in the correct bounds range [0,...,displayNum.length-1] before trying to access its elements.
Edit :
In setArrayNum() replace double arrayNum[] = new double[totalNum]; by arrayNum = new double[totalNum];

Arrays are 0-based. So if you create an array of size display you can access indexes 0..display-1

You are creating local array double arrayNum[] = new double[display]; within getArray() method.
You need to remove double arrayNum[] = new double[display]; from getArray() method.
After that your method like below.
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
if(display >0 && display <=arrayNum.length){
System.out.print(arrayNum[display-1]);
}else{
System.out.print(display + " is out of range");
}
}

Related

Check if array is already created in Java

class CreateArray{
Scanner input = new Scanner(System.in);
public void Create(){
System.out.print("How many numbers numbers do you want to enter? Minimum of 5 and a maximum of 20 only: ");
int num = input.nextInt();
if (num >=5 || num >20){
int array[] = new int[num];
System.out.println("Enter the numbers you want: ");
if(array.length != 0){
for(int i = 0 ; i<array.length; i++){
array[i] = input.nextInt();
}
}
System.out.print("Your array of numbers are: ");
for(int i = 0 ; i<array.length; i++){
System.out.print(array[i] + " ");
}
}
else{
System.out.print("Please input a the right numbers of array");
} }}
I would like to know how to identify if array is already created so that i can display an error message. I have two classes as you can see above theres the class CreateArray and here is the main class: I am new to java actually so forgive me. And also the logic is that when user create an array then they decide to continue and check again the code will output "you have already created an array" Thank you so much for answering.
public class Lab3
{public static void main(String[] args){
Scanner ans = new Scanner(System.in);
String choice;
String choices;
do{
System.out.println("[1] Create Array");
System.out.println("[2] Insert Element");
System.out.println("[3] Search");
System.out.println("[4] Display");
System.out.println("[5] Delete");
System.out.println("[0] Stop");
System.out.print("\nEnter Choice: ");
choice = ans.nextLine();
if(choice.equals("1")){
CreateArray myObj = new CreateArray();
myObj.Create();
}
else{
System.out.print("Array has been created please procedd to other options!");
}
System.out.println();
System.out.print("Do you want to continue? : ");
choices =ans.nextLine();
}
while(!choices.equals("-1") || !choices.equals("-1"));
}}
You can check if an array is already created by using a global array variable that you can check from your main class.
Add this line int array[]; to the CreateArray class as a global variable, and replace int array[] = new int[num]; with array = new int[num]; so that it referances to the global vairable.
Then from your main/Lab3 class you can simply use if (myObj.array == null) to check if the array has NOT been created, or use if (myObj.array != null) to check if the array HAS been created.
Note, you also need to place the following code outside of the do{} while () loop CreateArray myObj = new CreateArray(); otherwise it will create a new object every loop and you will not be able to keep the inputs.
The complete code might look like this (with a few other changes to make more sense):
class CreateArray {
Scanner input = new Scanner(System.in);
//place a global variable here
int array[];
public void Create() {
System.out.print("How many numbers numbers do you want to enter? Minimum of 5 and a maximum of 20 only: ");
int num = input.nextInt();
//Fix this line as shown by Scary Wombat in comments:
if (num <= 5 || num <= 20) {
//Initialize the array here (This will make it a non null value)
array = new int[num];
System.out.println("Enter the numbers you want: ");
if (array.length != 0) {
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
}
System.out.print("Your array of numbers are: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
} else {
System.out.print("Please input a the right numbers of array");
}
}
}
And the Lab3 class could look like this:
public class Lab3 {
public static void main(String[] args) {
Scanner ans = new Scanner(System.in);
String choice;
String choices;
//Place the CreateArray object here so that it can be re-used between selecting options, otherwise you will lose all progress
CreateArray myObj = new CreateArray();
do {
System.out.println("[1] Create Array");
System.out.println("[2] Insert Element");
System.out.println("[3] Search");
System.out.println("[4] Display");
System.out.println("[5] Delete");
System.out.println("[0] Stop");
System.out.print("\nEnter Choice: ");
choice = ans.nextLine();
//Only call this method if it has not been created yet
if (choice.equals("1") && myObj.array == null) {
myObj.Create();
}
//If another option is chosen but the array has not been created, then give an error message
else if (myObj.array == null) {
System.out.print("Array has not been created yet, please choose option 1.");
}
else if (choice.equals("1")) {
System.out.print("THe array has already been created, please choose another option.");
}
//Place all other value checkes after the above checks:
else if (choice.equals("2")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("3")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("4")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("5")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("0")) {
System.out.print("This opetion is not yet supported.");
break;
} else {
System.out.print("Invalid option.");
}
System.out.println();
System.out.print("Do you want to continue? : ");
//What does this do?
choices = ans.nextLine();
} while (!choices.equals("-1"));
}
}

How can I avoid my loop to take the previous answer of the user?

I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.

How to store the data on every instance of do-while loop in Java?

I am currently studying Java and I need to add the values of every instance in my do-while loop. Is there some way to store the values so it won't be overwritten every loop?
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
int itemQty = input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
You can define a variable for the totalSum outside of the loop and then everytime the user enters a number, add itemQty to it.
int totalSum = 0;
do {
...
int itemQty = input.nextInt();
totalSum += itemQty;
...
} while (...);
// Here totalSum is the sum of all user inputs
you can update your program like this below -
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char userChar;
int itemQty = 0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty += input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next().charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
int itemQty=0;
int totalQty=0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty = input.nextInt();
totalQty+=itemQty;
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
As suggested by Lino, Keep itemQty outside the loop and initialize it to zero.
Do you also want to store the value of itemQty for every loop iteration?
If yes then use ArrayList.
ArrayList<int> valuesList = new ArrayList<int>();
and change your loop code to
int itemQty=0;
int totalQty=0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty = input.nextInt();
valuesList.add(itemQty*10);//New line to be added
totalQty += itemQty;
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next().charAt(0);
} while (userChar == 'y');
And then after the loop ends, display the values in each stage.
for (int i = 0; i < valuesList.size(); i++) {
System.out.println("The value of Qty in stage "+(i+1)+" is $"+valuesList.get(i));
}
And this will be your final output
Apples are $10
How many do you want?
10
Do you wish to buy more? (y/n)
y
Apples are $10
How many do you want?
5
Do you wish to buy more? (y/n)
n
The total is: $150
The value of Qty in stage 1 is $100
The value of Qty in stage 2 is $50

I'm almost finished, but how to loop the entire program?

My cash register program is nearly complete, it can process sales and returns and adds or subtracts this to the money in the register.
My only problem is that once I'm done adding values for example, the program closes and i cant figure out how to loop it back to the choice menu. I tried using a do loop and a do while loop but it yelled at me saying it had invalid input (probably because you have to press F to stop when you're checking out).
How can I loop this whole thing?
import java.util.Scanner;
import java.util.ArrayList;
public class Assignment3_000848913
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Integer> Prices = new ArrayList<Integer>();
ArrayList<Integer> ReturnPrices = new ArrayList<Integer>();
int totalRegisterMoney = 0;
int Choice = 0;
System.out.print("What would you like to do?");
System.out.println();
System.out.print("Press 1. Process a sale");
System.out.println();
System.out.print("Press 2. Process a return");
System.out.println();
System.out.print("Press 3. Display Money in register");
System.out.println();
System.out.print("Press 4. Exit");
System.out.println();
Choice = in.nextInt();
if(Choice == 1)
{
//THIS LOOP READS IN ALL THE PRICES//
System.out.print("Press F when finished.");
System.out.println();
do
{
System.out.print("Enter the integer price of the item: $");
int i = in.nextInt();
Prices.add(i);
System.out.println();
}
while(in.hasNextInt());
int totalPrice = processSale(Prices);
totalRegisterMoney = totalRegisterMoney + totalPrice;
System.out.print("Your total comes to $");
System.out.println(totalPrice);
}
if(Choice == 2)
{
System.out.print("Press F when finished.");
System.out.println();
do
{
System.out.print("Enter the price of the returned item: $");
int j = in.nextInt();
ReturnPrices.add(j);
System.out.println();
}
while(in.hasNextInt());
int returnTotal = processReturn(ReturnPrices);
if(returnTotal > totalRegisterMoney)
{
System.out.print("Sorry, there's not that much money in the register.");
System.out.println();
}
else
{
totalRegisterMoney = totalRegisterMoney - returnTotal;
}
System.out.print("You've completed the return.");
System.out.println();
}
if(Choice == 3)
{
viewBalance(totalRegisterMoney);
}
}
//END OF MAIN
If you were getting that error when you did the do..while, you were doing it OK.
The problem is that after writing the 'F' to exit option 1 , the loop returns and tries to convert that 'F' into
Choice = in.nextInt();
This causes an error bucause a 'F' is not a number.
You would need to put an
in.next();
after your
while(in.hasNextInt());
This also would happen on option 2 in your code

Array Issues with Java

Im having Difficulty with programming, I'm new at this so I'll send the whole program so far and I just need help with case '2' please! it says It cannot find symbol Variable array.
import java.util.Scanner ;
public class jakegrimson20062582 {
public static void main(String[] args) {
// Local variable
int option;
String squareFootage;
int noBed;
Scanner input = new Scanner( System.in );
Scanner user_input = new Scanner( System.in );
// Display menu graphics
System.out.println(" ");
System.out.println("| *****Rental Menu******* |");
System.out.println("| 1. Enter rental property Details ");
System.out.println("| 2. Enter monthly rent ( 12 Months ) ");
System.out.println("| 3. Display Annual Rent");
System.out.println("| 4. Display rental report ");
System.out.println("| 5. Display Monthly rents falling below a certain threshold ");
System.out.println(" ");
System.out.println(" Please Select an option: ");
option = input.nextInt();
// Switch construct
switch (option) {
case 1:
System.out.println("Enter Rental Details: ");
System.out.println("Property Code: ");
String propertyCode = user_input.next();
System.out.println("Property Type: ");
String propertyType = user_input.next();
System.out.println("Square Footage: ");
squareFootage = user_input.next();
System.out.println("Number Of bedrooms ");
noBed = input.nextInt();
break;
case 2:
{
Scanner keyboardScanner = new Scanner(System.in);
int[] array;
array = new int[12];
// creates for loop
for (int i=0; i<12; i++)
{
System.out.println("Enter Rental for month");
array[i] = keyboardScanner.nextInt();
}
for (int i=0; i<array.length; i++)
{
System.out.println(array[i]);
}
}
System.out.println("");
break;
case 3:
System.out.println("Exit selected");
break;
default:
System.out.println("Invalid selection");
break;
}
}
}
I require help with completing this code, NOT JUST THIS ISSUE all help On the finished code would be MUCH appreciated, as On the topic I'm having general issues with arrays, I may need a string version of this code rather than INT due to the fact that numbers put in with have a decimal point. thanks!
Indent your code to be human-readable:
case 2:
{
Scanner keyboardScanner = new Scanner(System.in);
int[] array;
array = new int[12];
// creates for loop
for (int i=0; i<12; i++) {
System.out.println("Enter Rental for month");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
for (int i=0; i<array.length; i++) {
System.out.println(array[i]);
}
This makes the error a lot more obvious. You're creating a code block in the case 2 block with some curly braces {}, and you declare your array variable inside of that block. That means the variable is scoped only to that block. Then you try to access the variable outside of that block, where it no longer exists.
Should that for loop be inside the {} block? Or perhaps should the curly braces for that block be omitted entirely, since a case doesn't need them?
Use proper formatting so you can see where your case 2 ends. The array variable only exists inside case 2, and you're trying to use it outside of that scope.

Categories

Resources