Java Initialization Error - java

double pullPrice(String input){
if(input.length() < 3){
System.out.println("Error: 02; invalid item input, valid example: enter code here'milk 8.50'");
System.exit(0);
}
char[] inputArray = input.toCharArray();
char[] itemPriceArray;
double price;
boolean numVal = false;
int numCount = 0;
for(int i = 0; i <= inputArray.length-1; i ++){
//checking if i need to add char to char array of price
if(numVal == true){
//adding number to price array
itemPriceArray[numCount] = inputArray[i];
numCount++;
}
else{
if(inputArray[i] == ' '){
numVal = true;
//initializing price array
itemPriceArray = new char[inputArray.length - i];
}
else{
}
}
}
price = Double.parseDouble(String.valueOf(itemPriceArray));
return price;
}
Problem: attempting to pull the sequence of chars after white space between 'milk 8.50' as input. Initialization error occurs because I am initializing char array inside an if else statement that will initialize the array if it finds whitespace.
Question: since I don't know my char count number until I find a whitespace is there another way I can initialize? Does the compiler not trust me that I will initialize before calling array.
Also, if I am missing something or there are better ways to code any of this please let me know. I am in a java data structures class and learning fundamental data structures but would also like to focus on efficiency and modularity at the same time. I also have a pullPrice function that does the same thing but pulls the item name. I would like to combine these so i don't have to reuse the same code for both but can only return items with same datatype unless I create a class. Unfortunately this exercise is to use two arrays since we are practicing how to use ADT bags.
Any help is greatly appreciated?

Try something like this:
double pullPrice(String input)
{
try
{
// Instantiate a new scanner object, based on the input string
Scanner scanner = new Scanner(input);
// We skip the product (EG "milk")
String prod = scanner.next();
// and read the price(EG 8.5)
double price = scanner.nextDouble();
// We should close the scanner, to free resources...
scanner.close();
return price;
}
catch (NoSuchElementException ex)
{
System.out.println("Error: 02; invalid item input, valid example: enter code here 'milk 8.50'");
System.exit(0);
}
}

If you are sure that you program will get only proper input data then just initialize your array with null:
char[] itemPriceArray = null;
The main problem why the compiler is complaining - what happens if your program accesses uninitialized variable (for instance with wrong input data)? Java compiler prevents this kind of situations completely.

I will add to the other answers,
since you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:
int oldItems[] = new int[10];
for (int i=0; i<10; i++) {
oldItems[i] = i+10;
}
int newItems[] = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;

char[] itemPriceArray = new char[inputArray.length];

Related

Cannot invoke because Array[] is null [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I'm still new to programming and I want to make a program that will take the food order from user until the user presses "n" to stop. But I can't seem to make it work like I want it to.
I want my output to be like this.
Buy food: Burger
Order again(Y/N)? y
Buy Food: Pizza
Order again(Y/N)? n
You ordered:
Burger
Pizza
But my output right now is this.
Buy food: Burger
Order again(Y/N)? y
Buy food: Pizza
Order again(Y/N)? n
You ordered:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Array.getFoodName()" because "food_arr2[i]" is null
at Food.main(Food.java:50)
Here is my code:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Food food = new Food();
Array[] food_arr;
boolean stop = false;
String foodName;
int k = 1;
int j = 0;
while(stop == false) {
food_arr = new Array[k];
System.out.print("Buy food: ");
foodName = s.next();
food_arr[j] = new Array(foodName);
food.setFoodArray(food_arr);
System.out.print("Order again(Y/N)? ");
String decide = s.next();
if(decide.equalsIgnoreCase("y")) {
k++;
j++;
}
else if(decide.equalsIgnoreCase("n")) {
stop = true;
}
}
Array[] food_arr2 = food.getFoodArray();
for (int i = 0; i < food_arr2.length; ++i) {
System.out.println("\nYou ordered: ");
System.out.println(food_arr2[i].getFoodName()); //This line is the error according to my output
}
}
I don't know how to fix this and I was hoping for someone to help me.
I think I see what you are trying to do with the k value setting the size of the array you are using.
However, with each iteration of the while loop:
food_arr = new Array[k];
Will create a new empty array each time!
So, for example, on the second iteration
food.setFoodArray(food_arr);
Will set foods array as something like [null, "Pizza"]
Even if this did work, creating a new array each time is not a very efficient method.
I would strongly recommend using a different, dynamically allocated data structure such as an ArrayList and defining it outside the scope of the while loop.
ArrayList<Food> food_arr = new ArrayList<Food>()
// Note that I'm just guessing the data type here - I can't see what you are actually using!
while(stop == false) {
System.out.print("Buy food: ");
foodName = s.next();
food_arr.add(foodName)
// etc, etc
}
food.setFoodArray(food_arr)
// ! Note: You will need to convert the array list into an array
// ! or change the data struture in the Food class
// etc, etc
However, this is just the first solution that popped into my head, check out different kinds of data structures and think about how else you could design this program yourself!

why "while(Scanner.hasNext())" causes OutOfMemoryError in java?

import java.util.*;
import java.io.*;
public class Main {
public static void problem1 () {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
int[][] nums = new int[n][2];
for (int i = 0; i < n; i++) {
nums[i][0] = scanner.nextInt();
nums[i][1] = scanner.nextInt();
}
Arrays.sort(nums, (a, b) -> {
return a[0] - b[0];
});
int[] dp = new int[n];
Arrays.fill(dp, 1);
int res = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i][1] >= nums[j][1]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
if (dp[i] > res)
res = dp[i];
}
System.out.println(res);
}
}
public static void main(String[] args) throws IOException {
problem1();
}
}
enter link description here
While coding the above-mentioned code, I found that while(scanner.hasNext()) will cause "OutOfMemoryError: Java heap space"while the input data is more than 1000000; And the bug can be solved by removing while loop; but in my limited experience with JVM, I don't know why; Any ideas?
We really need to see the input to be sure why this is failing. But if you are getting an OOME in hasNext(), what is happening is that your application's input includes a token that is monstrously long.
The hasNext() call is going to read ahead on the input stream from the current position until it encounters a character (or EOF) that indicates the end of the next token. The characters that are read ahead need to be buffered in memory. The OOME means that you have managed to fill up the heap while buffering characters.
A possible "quick and dirty" workaround would be to make the heap size big enough to buffer the entire input. But I don't think that will work.
Why?
Suppose you manage to buffer a monstrously big token so that hasNext() can return true. The next thing that you do is to call nextInt() to read a value for n. But that is most likely going to fail, because either the token (found by hasNext()) is not a number, or is too large a number to be returned as an int. So nextInt() will throw an exception.
The real way to solve this is to figure out what the monstrous token actually is. That entails looking at the input that your application is reading.
And the bug can be solved by removing while loop;
Hmmm.
I read that as meaning that the OOME goes away if you remove the outer loop. You haven't actually solved the problem. Now your code will only process a single dataset.
You should do scanner.hasNextInt() before calling scanner.nextInt(). Not sure why you get OOM but this may help.

Values are not initializing under try block?

trying to make program rotation of array, it was giving an Exception by user misinput so I use try block but now, under try block it is not initializing values....
Can some one tell the reason or solution for this....
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
System.out.println("Enter T : ");
int t = sc.nextInt();
sc.nextLine();
while(t!=0){
System.out.println("\nEnter N D : ");
String s = sc.nextLine();
s.trim();
String st[] = s.split(" ");
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
System.out.println("Enter Element : ");
s=sc.nextLine();
st = s.split(" ");
ar.rotateArray(st,n,d);
t--;
}
}
If you need valid input and you did not get valid input, the thing to do is to try again to get valid input, after telling the user the input was invalid. Don't just proceed with the invalid data. You therefore need an inner loop:
while (t!=0) {
boolean validInput = false;
while (!validInput) {
System.out.println("\nEnter N D : ");
String s = sc.nextLine().trim();
String[] st = s.split(" ");
int n,d;
try {
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
validInput = true;
}
catch (Exception e) {
System.out.println("Invalid input");
}
}
… process n and d as before …
}
For my taste the loop to get the valid input would be better off being a subroutine in its own right - for clarity.
Variable in local scope should be initialized , that is what error , so do initialize the variables n and d to some integer value say as below
int n = 0 ,d = 0;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}
When a method throws an exception, that method never returns.
This means that if n = Integer.parseInt(st[0]); throws an exception, it does not return a value, which means n will not be assigned a value (since there is no return value to assign to it).
You are ignoring the exception and trying to continue as if nothing went wrong. But something did go wrong—n was never assigned a value. So the compiler tells you that it is not safe to use n in any subsequent code.
To solve this, you first must decide what to do if the user provides invalid input. You can’t just ignore the exception. If the input doesn’t represent two integers, you don’t have any values to work with. You can’t continue in any meaningful way.
The best course of action is to remove your try and catch. This will cause the program to terminate if Integer.parseInt fails, which is almost certainly what you want (unless your assignment requires you to do something different). Remember that it is not possible to continue in any meaningful way without values assigned to n and d.
In other words, change this:
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
to this:
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
As a side note, this line does nothing:
s.trim();
…because Strings cannot be changed. s.trim() returns a new String which you must capture in a variable. You probably want to do this:
s = s.trim();
Your image is quite misleading and really doesn't point to the actual problem, it only points to what you perceive to be the problem. Your mistake was placing the initialization of variables n and d into a try block which takes your call to the rotateArray() method out of scope for that initialization of those variables.
The bigger problem is... What in the world are you rotating? Where is the Array to rotate? Is it actually a String Array or is it suppose to be an Integer Array? Please don't tell me it's the st[] String Array (which is what you're trying to do) because according to your code that array is used to establish the array size (n) portion to work with and the number of elements (d) the User wants to rotate by. No rocket science to rotate an Array with only two elements. Give the rotateArray() method an array to actually rotate.
Let's provide an Integer Array and a way to do this without a try/catch mechaism:
// The Array to carry out rotations on.
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String ls = System.lineSeparator();
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
int t = 0;
String value = "";
while (value.equals("")) {
System.out.print("Enter Number of times to Rotate Array: --> ");
value = sc.nextLine().trim();
/* Make sure a String representation of a Integer value is supplied.
The regular Expression "\\d+" in the String#matches() method
ensures the a numerical integer string is supplied. */
if (!value.matches("\\d+" || value.length() > 9) {
/* Will handle situations where nothing is supplied, alpha
characters might be supplied, or the supplied numerical
value is outrageously large. */
System.out.println("Invalid integer numerical value supplied!" + ls);
value = "";
}
}
t = Integer.parseInt(value);
while (t != 0) {
System.out.println();
System.out.print("Enter the Size (portion) of the Array to consider and the" + ls
+ "number of elements to rotate (separated with a space): --> ");
String s = sc.nextLine().trim();
// Quit if anything starting with the letter "Q"
// (like "q" or "quit") is supplied.
if (s.substring(0, 1).equalsIgnoreCase("q")) {
System.out.println("\"Quit\" Supplied!");
System.exit(0);
}
String st[] = s.split(" ");
/* Make sure two values were supplied and that
they are both numerical integer strings. */
if (st.length != 2 || !st[0].matches("\\d+") || !st[1].matches("\\d+")) {
System.out.println("Invalid Input! Try again and make sure 'both' "
+ "values are numerical Integers.");
continue;
}
// Declare and initialize the n and d variables.
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
/* If the number of elements to rotate is greater
than the portion of array to rotate in. */
if (d >= n) {
System.out.println("Invalid Input! The size of the Array portion to rotate" + ls
+ "must be greater than the number of elements to rotate.");
}
/* If the supplied Array size to deal with is
out of bounds of the Array itself. */
else if (n < 1 || n > array.length) {
System.out.println("You have supplied an invalid Array Size! (" + n
+ ") Size must be between 1 and " + array.length + "!"
+ ls);
}
/* If the supplied number of elements to rotate
is less than 1 or greater than the total number
of elements - 1. */
else if (d < 1 || d > (array.length - 1)) {
System.out.println("You have supplied an invalid number of elements to rotate! (" + d
+ ") Value must be between 1 and " + (array.length - 1) + "!" + ls);
}
// All is good - Do the rotation.
else {
ar.rotateArray(array, n, d); // Rotate the Array
// Display the current rotation...
System.out.println("Current Rotation: --> " + Arrays.toString(array));
t--;
}
}
// Done
The error you outline in your image is a general compilation error and is relatively generic for all data types. This error occurs when you are trying to use a local variable without first initializing it. You won't get this error if you use a uninitialized class or instance variable because they are initialized with their default value (for example: Reference types are initialized with null and integer types are initialized with zero), but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If the compiler believes that a local variable might not have been initialized before the next statement which is going to use it, you will receive this error. You of course will not get this error if you just declare the local variable but don't use it but then, why declare it in the first place.
Everyone is stating to initialize the local variables n and d because in reality, in order to successfully compile your code that is exactly what needs to be done in order for the rotateArray() method (which uses these uninitialized variables) to function. Again in reality, you do initialize them however your code does it within a try{} block which alters scope and the compiler is smart enough to know that if the initialization fails within the try{} block then the catch{} block could let that failure be ignored. In fact, if you were to place the call to the rotateArray() method within that try{} block then you would not get this compile time error since the call is within the scope of of where the variables n and d are actually initialized. You know, a decent IDE (line Eclipse, NetBeans, InteliJ, etc) should catch this error for you long before you try to compile.
According to your code, the actual intent of the try/catch blocks would be to handle the case of invalid input whereas a non-numerical integer value was supplied by the User. In this case it would be up to your catch{} block to handle that particular situation which should be to inform the User of the invalid input and then continue to re-prompt for proper input. At compile time the compiler really doesn't care about this mechanism since this would be a Runtime Error unless of course it is syntax related.
Nothing wrong with try/catch, I just like to avoid them if I can.

Java: Saving User Input to be Calculated in a Loop

Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);

Null Pointer that makes no sense to me?

Im currently working on a program and any time i call Products[1] there is no null pointer error however, when i call Products[0] or Products[2] i get a null pointer error. However i am still getting 2 different outputs almost like there is a [0] and 1 or 1 and 2 in the array. Here is my code
FileReader file = new FileReader(location);
BufferedReader reader = new BufferedReader(file);
int numberOfLines = readLines();
String [] data = new String[numberOfLines];
Products = new Product[numberOfLines];
calc = new Calculator();
int prod_count = 0;
for(int i = 0; i < numberOfLines; i++)
{
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
if(data[i].contains("input"))
{
continue;
}
Products[prod_count] = new Product();
Products[prod_count].setName(data[1]);
System.out.println(Products[prod_count].getName());
BigDecimal price = new BigDecimal(data[2]);
Products[prod_count].setPrice(price);
for(String dataSt : data)
{
if(dataSt.toLowerCase().contains("imported"))
{
Products[prod_count].setImported(true);
}
else{
Products[prod_count].setImported(false);
}
}
calc.calculateTax(Products[prod_count]);
calc.calculateItemTotal(Products[prod_count]);
prod_count++;
This is the output :
imported box of chocolates
1.50
11.50
imported bottle of perfume
7.12
54.62
This print works System.out.println(Products[1].getProductTotal());
This becomes a null pointer System.out.println(Products[2].getProductTotal());
This also becomes a null pointer System.out.println(Products[0].getProductTotal());
You're skipping lines containing "input".
if(data[i].contains("input")) {
continue; // Products[i] will be null
}
Probably it would be better to make products an ArrayList, and add only the meaningful rows to it.
products should also start with lowercase to follow Java conventions. Types start with uppercase, parameters & variables start with lowercase. Not all Java coding conventions are perfect -- but this one's very useful.
The code is otherwise structured fine, but arrays are not a very flexible type to build from program logic (since the length has to be pre-determined, skipping requires you to keep track of the index, and it can't track the size as you build it).
Generally you should build List (ArrayList). Map (HashMap, LinkedHashMap, TreeMap) and Set (HashSet) can be useful too.
Second bug: as Bohemian says: in data[] you've confused the concepts of a list of all lines, and data[] being the tokens parsed/ split from a single line.
"data" is generally a meaningless term. Use meaningful terms/names & your programs are far less likely to have bugs in them.
You should probably just use tokens for the line tokens, not declare it outside/ before it is needed, and not try to index it by line -- because, quite simply, there should be absolutely no need to.
for(int i = 0; i < numberOfLines; i++) {
// we shouldn't need data[] for all lines, and we weren't using it as such.
String line = reader.readLine();
String[] tokens = line.split("(?<=\\d)\\s+|\\s+at\\s+");
//
if (tokens[0].equals("input")) { // unclear which you actually mean.
/* if (line.contains("input")) { */
continue;
}
When you offer sample input for a question, edit it into the body of the question so it's readable. Putting it in the comments, where it can't be read properly, is just wasting the time of people who are trying to help you.
Bug alert: You are overwriting data:
String [] data = new String[numberOfLines];
then in the loop:
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
So who knows how large it is - depends on the success of the split - but your code relies on it being numberOfLines long.
You need to use different indexes for the line number and the new product objects. If you have 20 lines but 5 of them are "input" then you only have 15 new product objects.
For example:
int prod_count = 0;
for (int i = 0; i < numberOfLines; i++)
{
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
if (data[i].contains("input"))
{
continue;
}
Products[prod_count] = new Product();
Products[prod_count].setName(data[1]);
// etc.
prod_count++; // last thing to do
}

Categories

Resources