Array Issues with Java - 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.

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"));
}
}

My Do-While loop breaks when I hit my keyboard input for the second time

I am only a few weeks in on coding so I'm really new. This is a simple program that assists the user in customizing a new car. The program uses different methods for each of the respective menus. each method that isn't main asks the user which of 2 custom car options they would like then the method sends back a cost to the main. Each method that isn't main uses the same format as the method engineCost. I can't figure out why my keyboard input only functions during the first iteration of my do while loop. This is the error I am prompted with on eclipse:
Exception in thread "main" java.lang.IllegalStateException
I did some looking on stack overflow and I don't think I'm knowledgeable enough to search for the answer properly. Any help would be much appreciated.
import java.util.Scanner;
public class Ch5HW {
public static void main(String[] args){
double baseCar = 14000;
double addCost = 0;
double ttlCost = 0;
int userOpt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Basic Car includes: Silver color, 4 cilinder engine, Cooper Tires; cost: $14,000");
System.out.println("");
//this do-while loops until the user enters 4 to exit
do{
System.out.println("Build Car Quote");
System.out.println("1. Engine");
System.out.println("2. Color");
System.out.println("3. Tires");
System.out.println("4. Exit");
System.out.print("Enter Option: ");
userOpt = 0;
// this keyboard input only works on the first iteration of the loop
userOpt = keyboard.nextInt();
System.out.println(userOpt);
//nested switch to determine userOpt
switch (userOpt)
{
case 1:
// calls the engineCost method
addCost = engineCost();
//adds the value received to a total value
ttlCost += addCost;
break;
case 2:
//calls the colorOpt method
addCost = colorOpt();
//adds the value received to a total value
ttlCost += addCost;
break;
case 3:
//calls the tireOpt method
addCost = tireOpt();
//adds the value received to a total value
ttlCost += addCost;
break;
}
//System.out.print(addCost + baseCar);
keyboard.close();
}
while (userOpt !=4);
//once loop has finished the total of additional purchases is added to the base car price
System.out.print("Total cost: " + (ttlCost + baseCar));
}
// this method has options for the engine
static double engineCost()
{
double engineCost = 0;
double addCost =0;
int engineOpt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Engine Options: ");
System.out.println("1. 8 cylinder: $5000.00");
System.out.println("2. 6 cylinder: $3500.00");
System.out.println("3. Exit");
System.out.println("Enter Option: ");
engineOpt = keyboard.nextInt();
switch (engineOpt)
{
case 1:
engineCost = 5000.00;
addCost += engineCost;
break;
case 2:
engineCost = 3500.00;
addCost += engineCost;
break;
case 3:
engineCost = 0;
addCost += engineCost;
}
keyboard.close();
return addCost;
}
}
This is because of the line: keyboard.close(); within your loop. This closes the Scanner after your first iteration. After this you try to call nextInt() which (from the docs) will throw:
IllegalStateException - if this scanner is closed
You should only close a resource after you are completely done with it.
That being said do not close System.in. The general rule is that if you did not open it, your should not close it.

Java program crashing when attempting to show a menu and retrieve input from user (NoSuchElementException)

So I have a program that takes orders for vehicle purchases (meant to learn the basics of java. Right now this iteration of the assignment is focusing on inheritance). Hierarchy: Orders.java (Main program), Vehicle.java (parent class), Boat.java/Car.java/Truck.java(child classes).
I was showing my menus manually in the main program before but tried to delegate that responsibility to my Vehicle class so it would be more generic and each child could pass in a Question Prompt and Array of Choices to the showMenu function. So nothing was being done manually anymore.
Here's what happened when it was done manually (worked fine):
System.out.println("What type of Car is this?");
System.out.println("\t1. Sedan");
System.out.println("\t2. Coupe");
System.out.println("\t3. Wagon");
System.out.print("Choice: ");
while (!sc.hasNext("[123]")) {
System.out.println("");
System.out.println("");
System.out.println("That's not an option! Please try again.");
System.out.println("What type of Car is this?");
System.out.println("\t1. Sedan");
System.out.println("\t2. Coupe");
System.out.println("\t3. Wagon");
System.out.print("Choice: ");
sc.next();
}
choice = sc.next();
if(choice.equals("1")){
car.setCarType("Sedan");
} else if (choice.equals("2")){
car.setCarType("Coupe");
} else if (choice.equals("3")){
car.setCarType("Wagon");
} else{
car.setCarType("unknown");
}
Here's how it works now (crashes before stopping to let the user give input):
public int showMenu(String prompt, String[] choices){
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
String choiceIdentifiers = "";
int choice;
for(int i = 0; i < choices.length; i++){
Integer j = i+1;
System.out.println("\t\t" + j + ". " + choices[i]);
choiceIdentifiers = choiceIdentifiers + j.toString();
}
System.out.print("Choice: ");
while (!sc.hasNext("[" + choiceIdentifiers +"]")) {
System.out.println("");
System.out.println("");
System.out.println("That's not an option! Please try again.");
System.out.println(prompt);
for(int i = 0; i < choices.length; i++){
System.out.println("\t\t" + (i+1) + ". " + choices[i]);
}
System.out.print("Choice: ");
sc.next();
}
choice = Integer.parseInt(sc.next());
sc.close();
return choice - 1;
}
Also here's a link to my github repo with the full program.
What could be happening in the showMenu function to crash the program and throw the NoSuchElementException?
Any help would be greatly appreciated.
The problem is that you're closing the System.in stream when you call sc.close().
When you construct a new Scanner that uses the closed System.in stream and you call next() on it, you'll get this error.
To solve the problem, don't close the System.in (don't call close() on any Scanner that uses this stream) until you're done processing user input.
Here is a MCVE:
public class Example {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
sc1.close();
Scanner sc2 = new Scanner(System.in);
sc2.next();
}
}
The problem is in Vechile.java show menu method
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
String choiceIdentifiers = "";
int choice;
for(int i = 0; i < choices.length; i++){
Integer j = i+1;
System.out.println("\t\t" + j + ". " + choices[i]);
choiceIdentifiers = choiceIdentifiers + j.toString();
}
so here after iterating on choices array you are concatinating choiceIdentifiers string that will become 12 after loop but you are expecting input from user as 1 or 2 for model type of vechile so if you will put 1 for model then
!sc.hasNext("[" + choiceIdentifiers +"]")
is not having 1 so it will throw no such element error , hope this will help you

how to add try and catch validation and how to fix my switch, do-while error java

I cant post the code in here not sure why error so i post on reddit
https://www.reddit.com/r/javahelp/comments/3izvy2/how_to_add_try_and_catch_validation_and_how_to/
Your try/catch syntax is fine, what's the problem?
However, your do/while is wrong, I see the while is all the way down there, so remove your last curly bracket from the do and put it right before the while:
do{
try{
System.out.println("Choose your option");
System.out.println(" 1. Create List of used car");
System.out.println(" 2. Print list of used car");
System.out.println(" 3. Search ");
System.out.println(" 4. Exit");
int choose = read.nextInt();
if ( choose <= 4){
throw new Exception();
}
}catch (Exception e){
System.out.println("Please enter input option from 1-4");
..rest of code...
}while(choose <= 4);
and in your switch, choose is not avaliable - choose is a local variable for the try/catch only, nothing other than the try/catch can access it. It would be best to make choose a global variable by putting it at the top of the do:
do{
int choose;
..blah blah..
}
And reference to it without the int - just choose:
choose = read.nextInt();
Finally, you need a break at the end of every case, and what's the point of the returns?:
case 1:
for(int i=0; i<a.length; i++){
System.out.print("Enter Model: ");
Model = read.next();
System.out.print("Enter Plate Number: ");
PlateNo = read.next();
System.out.print("Enter Manufactured Year: ");
ManufacturedYear = read.nextInt();
System.out.print("Enter Transmission Type: ");
TransmissionType = read.next();
System.out.print("Enter Color: ");
Color = read.next();
CarList used = new CarList(Model, PlateNo, ManufacturedYear,
TransmissionType, Color);
a[i] = used;
return;
}
break;
...keep on going....
You shouldn't rely on others to fix your simple syntax problems, don't panic when you get an error, just go through your code and learn how to debug messages!

array display method difficulty

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");
}
}

Categories

Resources