I create a ProductMenu class to perform the add, search, delete and update product tasks and it only use the array. What problem that i face is how to add static variable in a method because i failed to add the maximum number of array after add a product into array. Hope can help and thank you.
public static void addProduct(){
Product product = new Product();
System.out.println("================================");
System.out.println(" Add Product ");
System.out.println("================================");
System.out.println("Product ID :- " + Product.getProdId());
System.out.print("Enter product name: ");
String prodName = input.next();
System.out.print("Enter product price: ");
double prodPrice = input.nextDouble();
product.setProductId(Product.getProdId());
product.setProductName(prodName);
product.setProductPrice((double)prodPrice);
products[productIndex] = product;
numOfArray++; // should be add ?
productIndex++; // should be add also?
ProductMenu.main(null); //back to main
}
My class
public class ProductMenu {
static Scanner input = new Scanner(System.in);
static int productIndex; //should be add after addProduct()
static int numOfArray = 1; //should be add after addProduct()
static Product[] products = new Product[numOfArray];
public static void main(String[] args) {
int menuOption;
do{
menu();
System.out.print("Enter your choice: ");
menuOption = input.nextInt();
switch(menuOption){
case 1:
addProduct();
break;
case 2:
System.out.print("halo" + products[0].toString());
break;
case 3:
break;
case 4:
break;
default:
System.out.print("Invalid option. Please try
again.\n");
break;
}
}while(menuOption!=1 && menuOption!=2 && menuOption!=3 &&
menuOption!=4 );
}
public static void menu(){
System.out.println("================================");
System.out.println(" Product Menu ");
System.out.println("================================");
System.out.println("1. Insert Product\n2. Update Product\n3.
Search Product\n4. Delete Product\n");
}
This is error msg that mean array number already more than limit and why i ask if i not wrong.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ProductMenu.addProduct(ProductMenu.java:64)
at ProductMenu.main(ProductMenu.java:21)
at ProductMenu.addProduct(ProductMenu.java:68)
at ProductMenu.main(ProductMenu.java:21)
I was wondering whether you could replace array with arraylist in your code. Arraylists are backed by arrays in background and you need not worry about arrayindexoutofbound exception while handling the data
To your problem: I would use an ArrayList or a LinkedList because it has a dynamic size. The size of an array cannot be changed after initialization and yours is set to 1. That will cause problems.
Addition: You do not need to call ProductMenu.main(null); //back to main because your addProduct function is called in the main method and after executing your function your program will continue in the main function.
As you need to use Array only then create one function add() which will first check size of array, if there is space left then add element else create new array of double size , copy all previous elements and add new one at end.
Also as size is static variable you don't have to pass to your method. Your method is also static and both method and variable in same class so you can directly use variable in method.
Related
I created a simple console based student system where basically the program will ask if you want to input name of students or view the list of names you inputted. The flow of the output is as shown below:
*******CONSOLE BASED STUDENT SYSTEM************
1. Input Student Name
2. List of students
Enter the number of choice: 1
Enter number of students to input: 3
****************************************
Student No. 1
Enter full name: Alpha Jones
****************************************
Student No. 2
Enter full name: Beta Jones
****************************************
Student No. 3
Enter full name: Gamma Jones
Do you wish to proceed back to menu?(y/n): y
*******CONSOLE BASED STUDENT SYSTEM************
1. Input Student Name
2. List of students
Enter the number of choice: 2
******LIST OF STUDENTS******
NULL
NULL
NULL
Firstly, I input three new students names Alpha Jones, Beta Jones and Gamma Jones but when I chose to view all names, everything is null. The three names should appear.
Here is the code for Student Class:
public class Student {
private String[] names;
private int numInput;
public Student(){
}
public Student(String[] fullName, int nI){
numInput = nI;
names = new String[nI];
for(int index = 0; index < nI; index++){
names[index] = fullName[index];
}
}
public String[] getList(){
return names;
}
public int getNumStudents(){
return numInput;
}
}
This is where I setup the values that will be passed on from the PracticeOne class, and later on, I will return that value back for display in PracticeOne Class.
Here is the PracticeOne Class(This is where the main method is located):
import java.util.Scanner;
public class PracticeOne {
public static void main(String[]args){
Scanner hold = new Scanner(System.in);
int menuNumChoice;
String response;
do{
System.out.println("******CONSOLE BASED STUDENT SYSTEM******");
System.out.println("1. Input Student Name");
System.out.println("2. List of Students");
System.out.print("Enter the number of choice: ");
menuNumChoice = hold.nextInt();
switch(menuNumChoice){
case 1:
inputStudentName(hold);
break;
case 2:
listStudents();
break;
default:
System.out.println("ERROR 101");
break;
}
System.out.print("Do you wish to proceed?(y/n): ");
response = hold.nextLine();
}while(response.equalsIgnoreCase("y"));
}
public static void inputStudentName(Scanner hold){
int numInput;
System.out.print("Enter number of students to input: ");
numInput = hold.nextInt();
hold.nextLine();
String[] fullName = new String[numInput];
for(int x = 0; x < numInput; x++){
System.out.println("***************************");
System.out.println("Student No. " + (x + 1));
System.out.print("Enter full name: ");
fullName[x] = hold.nextLine();
System.out.println();
}
Student s = new Student(fullName,numInput);
}
public static void listStudents(){
Student s = new Student();
System.out.println("******LIST OF STUDENTS******");
for(int y = 0; y < s.getNumStudents();y++){
System.out.println(s.getList());
}
}
}
Firstly I called an instance of Student in inputStudentName() method, which passes an argument for the fullname and the number of arrays being used, and tries to transfer it to Student class constructor, to get the values from there later on.
In the listStudents method, I tried displaying it by calling the getList() method from Student class to supposedly get back the names that was inputted earlier but everything was NULL. I also tried getting back the number of arrays through the getNumStudents() method but it also failed.
Kindly share some advice on how to work around with this problem or if theres a better way, suggest new things to achieve my goal.
public static void listStudents(){
**Student s = new Student();**
System.out.println("******LIST OF STUDENTS******");
for(int y = 0; y < s.getNumStudents();y++){
System.out.println(s.getList());
}
}
This is your listStudents logic. Instead of using the data you already created, you just create a new instance of Student. It's quite normal that this doesn't contain any information.
In your input method, you also only save the data in a local variable. This means, that once the method is finished, the data is lost.
Add a static List<Student> students = new ArrayList<>(); to your class. At the end of each input method, add the Student object to this list.
In listStudents, don't create a local student, but print the ones you stored in this List.
Based on your current system,first you can create a global variable Student[] or List then at the end of ' input Student Name()' method to save your dat.
Another Way you can use database to save your data,But this is not necessary for your system.
As the title says, I'm trying to get this Weather Station Data File into an array and be able to search for specific values in the file via a menu system. I built the menu system but have no clue on how to import the file to such an array or series of arrays. The only problem I have is that I am limited to using a one-dimensional array for the data. Neither my textbook nor professor have been of any help. Here is what I have so far:
import java.io.*;
import java.util.*;
public class VidrioTomas2 {
public static void main(String[] args)
throws FileNotFoundException {
System.out.println("Please give the data titled 'Bellevue College Weather Station Data.txt'.");
System.out.println("The data must be in the 10 minute data format.");
Scanner console = new Scanner (System.in);
System.out.print("Please type the file name: ");
String name = console.nextLine(); //Uses the user input to find the file.
if (name.equals("Bellevue College Weather Station Data.txt")) { //Needs to type the.txt and in the way the program says it is.
System.out.println("\nFile name secured. Proceeding to next step.");
File input = new File(name); //Stores the file into a value that can used in other methods.
if(input.length() == 67481){
System.out.println("\nLength of file: " + input.length() + "\nConfirmation of data. Proceeding to next step."); //Used as a confirmation that the file is true and working.
System.out.println("The following options are available. Please select one of them.");
System.out.println("1) Peak Wind Speed"
+ "\n2) Maximum Temperature"
+ "\n3) Humidity and Temperature"
+ "\n4) Solar Energy"
+ "\n5) End Program");
Scanner secondConsole = new Scanner (System.in);
System.out.print("Your selection: ");
int choice = secondConsole.nextInt();//Uses the user input to start up one of the options.
switch (choice) {
case 1:
System.out.println("Starting Peak Wind Speed Calculation. . .");
peakWindSpeedCalc(input);
break;
case 2:
System.out.println("Starting Maximum Temperature Calculation. . .");
maximumTempCalc(input);
break;
case 3:
System.out.println("Starting Humidity and Temperature Calculation. . .");
humidAndTempCalc(input);
break;
case 4:
System.out.println("Starting Solar Energy Calculation. . .");
solarEnergyCalc(input);
break;
case 5:
System.out.println("Ending program. . .");
break;
}
} else {
System.out.println("Inproper file. Ending program. . ."); //Kills if the length is not the same. The file I had had a length of 67481.
}
} else {
System.out.println("\nInproper name or type. Ending program. . ."); //Kills if file name is wrong. Caps sensitive.
}
}
public static void peakWindSpeedCalc(File rawData) {
System.out.println("Placeholder.exe is active. peakWindSpeedCalc is linked correctly.");
}
public static void maximumTempCalc(File rawData) {
System.out.println("Placeholder.exe is active. maximumTempCalc is linked correctly.");
}
public static void humidAndTempCalc(File rawData) {
System.out.println("Placeholder.exe is active. humdAndTempCalc is linked correctly.");
}
public static void solarEnergyCalc(File rawData) {
System.out.println("Placeholder.exe is active. solarEnergyCalc is linked correctly.");
}
}
It looks like you have the file object:
File input = new File(name);
Next, you need to parse it. Judging by your screenshot, the first few lines aren't totally useful, so you could skip them, then use split() on the useful lines:
String[] firstline = Files.readAllLines(file.toPath()).get(3).split("\\W");
Now you have an array with each of the values for the first line. You could set up constants to index into this list, so you could refer to it like firstline[BAR].
If you want to store everything in a single array, then you would index into it like this, for example:
data[line * numColumns + col]
I'm trying to get it where the user inputs a 1 or 2 for a predetermined values. Then using that to calculate a final cost.
Example:
Would you like the red or orange box? 1 for red, 2 for orange
The red would cost $10 and the orange $12.
How do I connect the inputs 1 and 2 to $10 and $12? Do I use switch or if?
Both options work. I personally prefer using the switch statement as it makes the code a bit more readable.
import java.util.Scanner;
public class Untitled {
public static void main (String[]args) {
Scanner s = new Scanner(System.in);
// this is where you store your items - you would obviously have to create the class and its methods first
// ArrayList <Item> items = new ArrayList<>;
// items.Add(new Item(SomePrice, SomeName);
System.out.println("Item 1 or 2");
String input = s.nextLine();
// Option 1
switch(input) {
case ("1"): {
System.out.println("Cost is 1");
// some method to retreive an item from the list of Items carrying the name one
// get user Input
// update the item in the list
break;
}
case ("2"):{
System.out.println("Cost is 2");
break;
}
}
// Option 2
if (input.equalsIgnoreCase("1"))
System.out.println("Cost is 1");
else if (input.equalsIgnoreCase("2"))
System.out.println("Cost is 2");
}
}
i am getting a "variable selection may not have been initialized in displayMenu(selection). and im not sure why. is it not initialized in the displayMenu model or am i missing something? does "selection = keyboard.nextInt" not count as an initialization? im kind of confused at why i am getting this error. here is the code:
import java.util.Scanner;
import java.io.*;
public class LanguageTranslatorIB
{
public static void main(String[] args)
{
// local variable to hold the menu selection
int selection;
do
{
// display the menu
displayMenu(selection);
// perform the selected operation
switch (selection)
{
case 1:
System.out.println("Good Morning.");
case 2:
System.out.println("Buongiorno.");
case 3:
System.out.println("Buenos dias.");
case 4:
System.out.println("Guten morgen.");
case 5:
System.out.println("GoodBye!");
}
}
while (selection != 5);
}
// the displayMenu module displays the menu and gets and validates
// the users selection.
public static void displayMenu(int selection)
{
//keyboard scanner
Scanner keyboard = new Scanner(System.in);
// display the menu
System.out.println(" select a language and i will say good morning");
System.out.println("1. English.");
System.out.println("2. Italian.");
System.out.println("3. Spanish.");
System.out.println("4. German.");
System.out.println("5. End the Program.");
System.out.println("Enter your selection");
// users selection
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
selection = keyboard.nextInt();
}
}
}
When you pass the variable selection into displayMenu the original variable does not change. The variable that is changed inside that method is a copy. Anything you do inside that method has absolutely no effect on the original selection
Therefore selection has not been initialized as is correctly pointed out by the compiler
You need to redesign the displayMenu to return a value which will be assigned to selection. No input to that method is needed
On another note, you probably want to add break after each System.out.println inside the case statements. If you don't the control will fall through to each next case.
Change displayMenu not take a parameter but rather to return the selected int. Assign that to selection:
selection = displayMenu();
and...
public static int displayMenu()
{
int selection = 0;
Scanner keyboard = new Scanner(System.in);
// ....
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
//...
}
return selection;
}
Your primitive variables are passed to methods as copy, not reference. So when you're calling
displayMenu(selection);
this method is only working with the copy within the method, not the variable out of it itself.
in Java local/block variables need to be explicitly initialized at declaration. un-initialized local variables give this error. Ifyou assume that the selection local variable will be given the default value that an int has in Java then you are wrong. The same is not the case with class level variables, the ones which you define in your class as properties. These variables are assigned their default values automatically by compiler.
Since you havent assigned any value to 'selection' before using in later on so you get this error.
In your main method, selection does not store any value at any point. You need to setup displayMenu to return an integer to selection
When you call displayMenu(selection); java passes the value of the selection variable to the displayMenu() method. The variable hasnt been initialized yet.
Then you're trying to set the value of selection variable inside the displayMenu() method.
However, the selection variable that you have as a parameter of the displayMenu() is local to that method and even though the value of the local selection variable is set, the selection variable inside the main method still remains uninitialized.
To tackle this : Create an instance variable.
public class LanguageTranslatorIB
{
int selection;
public static void main(String[] args)
{
displayMenu();
//Rest of the code follows;
}
}
public static void displayMenu()
{
//keyboard scanner
Scanner keyboard = new Scanner(System.in);
// display the menu
System.out.println(" select a language and i will say good morning");
System.out.println("1. English.");
System.out.println("2. Italian.");
System.out.println("3. Spanish.");
System.out.println("4. German.");
System.out.println("5. End the Program.");
System.out.println("Enter your selection");
// users selection
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
selection = keyboard.nextInt();
}
}
}
ok so i have a method that displays a menu and returns the user selection.
public class Menu {
public static int menuSelect(){
Scanner input = new Scanner(System.in);
System.out.println("Hello, Please Select A Function: ");
System.out.println("1) Sort All Banks Alphabetically ");
System.out.println("2) Calculate Interest And Show Balance ");
System.out.println("3) Transfer Money ");
System.out.println("4) Calulate Sum & Average Of All Accounts: ");
System.out.println("5) Richest Account: ");
System.out.println("6) Poorest Account: ");
int select = input.nextInt();
Menu.menuSelect();
//i tried this as adding Menu.menuSelect();
//after the return threw an error.
// but surprise suprise this doesnt actually
//let the method return anythign to select
return select;
}
The idea is that i want menu to come up the user selects a function, the function happens and then the menu calls itself until told otherwise.
but im unsure how to do this.
any help would be greatly appreciated.
Calling the same method from itself is called a recursion, and it's infinite in your case. You obviously don't need it here.
You want to have something like this:
private static int getInput() {
int choice = menuSelect();
while(choice < 1 || choice > 6) {
System.out.println("Invalid choice, please re-enter")
choice = menuSelect();
}
return choice;
}
Note that it's bad to give menuSelect a public modifier, you don't want anyone outside the class to have an access to it.