Im getting a null pointer exception in my array - java

I'm getting a null pointer exception whenever I enter a value to be added at that point in my int[] array and I'm uncertain where I should go from here or if another array is necessary. Any help would be greatly appreciated.
import java.util.Scanner;
public class Range
{
private int[] range;
private int begin,end,falseLoop,numInts,count;
Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
Range r = new Range();
r.getRange();
r.getAmount();
r.getInts();
//r.printAll();
}
private void getRange()
{
System.out.println("Please enter the first number in the range you would like to use: ");
begin = scan.nextInt();
System.out.println("Please enter the second number in the range you would like to use: ");
end = scan.nextInt();
falseLoop = end;
int[] range = new int[(Math.abs(begin) + Math.abs(end))];
for(int x = 0; x < range.length; x++)
{
range[x] = 0;
}
}
private void getAmount()
{
System.out.println("Please enter the amount of integers you would like to enter "
+ "in the range of " + begin + " to " + end);
numInts = scan.nextInt();
}
private void getInts()
{
for(int y = 0; y < numInts; y++)
{
System.out.println("Please enter an integer: ");
range[scan.nextInt()]++;
}
}
private void printAll()
{
for(int i = 0; i < range.length; i++)
{
System.out.println("Value: " + falseLoop + "equals: " + range[i]);
falseLoop++;
}
}
}

You're shadowing your class variable inside of getRange.
int[] range = new int[(Math.abs(begin) + Math.abs(end))];
Should actually be:
range = new int[(Math.abs(begin) + Math.abs(end))];
You get null pointers because you've declared an array, but nothing's been allocated for it.

Don't understand statement from your code
ragne[x] = new int[0];
You are here trying to assign array of integer to a integer variable. Like
integer = integerArray;

Related

Printing out the array position from a number input by a user

Question:
I need to create an array that holds 1000 integers ranging from 1-100. I then need to ask the user for an input and find out if the number the user has input is present in the array. If its not, then I have to output the message that it is not in the array.
I populated the array with random numbers, just need to find out how to search for the number in the array. I tried using a while loop to condition the for loop, but cant because the random generator and searcher would be in the same loop. Is there a way to linearly search for the number?
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] numbers = new int[1000];
System.out.println("Please enter a number: ");
int n = Integer.parseInt(reader.nextLine());
for(int i = 0; i < 1000; i = i + 1)
{
numbers[i] = (int)(Math.random()*100);
}
}
}
Try this
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] numbers = new int[1000];
boolean found = false;
System.out.println("Please enter a number: ");
int n = Integer.parseInt(reader.nextLine());
for(int i = 0; i < 1000; i = i + 1)
{
numbers[i] = (int)(Math.random()*100);
}
for(int i =0; i < 1000; i++){
if(numbers[i] == n){
found = true;
System.out.println(numbers[i] + " Appears first at index " + i);
break;
}
}
if(!found){System.out.println("Number " + n + " is not in the list");}
}

Java Average of integers

i seem to be having trouble figuring out what to set the variable intValue to under the read value methods. The program is supposed to take 10 integers and average them, it works fine as far as catching exceptions and input, but the output displays all the numbers as 0 (because i set it to 0 temporarily but can not figure out what to change it to). Heres the code
package averagenumdriver;
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class AverageOfIntegers {
//Declare variables
private int numberOfValues;
private int[] integerValues;
private double average;
public AverageOfIntegers(int numberOfValues){
this.numberOfValues = numberOfValues;
}
//Define the readValues()
public void readValues(){
String stringValue = null;
int intValue = 0, i;
Scanner console = null;
i = 0;
integerValues = new int[numberOfValues];
while(i < numberOfValues){
try
{
console = new Scanner(System.in);
System.out.print("Enter value : ");
//read the value
stringValue = console.nextLine();
//check for number
intValue = 0;
parseInt(stringValue);
//Store only integer values
integerValues[i++] = intValue;
}
catch(NumberFormatException ex)
{
//Catch exception and handle it
System.out.println("Invalid Number entered" + "Reenter again ");
continue;
}
}
}
//read integer values
public void printValues()
{
System.out.println("Given values are ");
for (int i = 0; i < numberOfValues; i++)
{
System.out.println("Number: " + (i + 1) + " = " +
integerValues[i]);
}
}
public double getAverage()
{
int sum = 0;
//Calcualte the sum of integer values
for (int i = 0; i < numberOfValues; i++)
{
sum += integerValues[i];
}
//calculate average
average = (double)sum / numberOfValues;
return(average);
}
}
EDIT* question seems to be marked as a duplicate, but I am not asking about why division with two integers where the denominator is greater than numerator yields a 0.
Change
//check for number
intValue = 0;
parseInt(stringValue);
TO
//check for number
intValue = parseInt(stringValue);

How to determine why a Java program is not accepting 7 console inputs?

I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}

Counting occurrences of integers in an array program java

I am trying to find the occurrences of all integers submitted by the user into the program and so far here's what I got. It works but I don't think it's a legit way to do it, is there any way I can try to do this without using the list[10]=9999;? Because if I don't do it, it'll show out of boundary error.
import java.util.*;
public class OccurrencesCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[11];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++){
list[i] = scan.nextInt();
list[10] = 9999;
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<11;i++){
if(list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Personally, I think this is a perfectly good solution. It means that you can deal with the last group in the same way as all others. The only change I would make is putting the line list[10] = 9999; outside the for loop (there's no reason to do it 10 times).
However, if you want to use an array of length 10, you can change the line
if(list[i-1]==list[i])
to
if(i < 10 && list[i-1]==list[i])
If you do this, you won't get an ArrayIndexOutOfBoundsException from list[i] because the expression after the && is not evaluated when i == 10.
import java.util.*;
class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] list = new int[101];
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++) {
int x = scan.nextInt();
list[x]++;
}
for(int i = 1; i <= 100; i++)
if(list[i] != 0)
System.out.println(i + " occurs " + list[i] + " times ");
}
}
To store count of numbers from 1 to 100 you need to use a list of 100 integers each one storing the number of occurrences of itself. Better approach would be to use a Map.
I have made use of ArrayList and Collections package instead of regular arrays as a different flavor if it interests you check it out.
import java.util.*;
public class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
Collections.sort(list);
Integer prevNumber = null;
for (int number : list) {
if (prevNumber == null || prevNumber != number) {
int count = Collections.frequency(list, number);
System.out.println(number + " occurs " + count + (count > 1 ? " times." : " time."));
}
prevNumber = number;
}
}
}
I got it figured out guys, only changed a couple of small things inside the conditions and everything went smoothly! Thanks for the help! Now I just need to find a way to restrict the inputs from going above 100.
import java.util.*;
public class CountOccurrences
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[10];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<=9;i++){
list[i] = scan.nextInt();
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<=10;i++){
if(i<=9 && list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}

Random number to store inside array list and choose from it

I am trying to create a program to generate random number and store into arraylist.
Meanwhile getting the number stored to do multiply.
I have store the generated number but how do I actually get the number that I wanted.
For this example, i trying to get the 3rd number, which step did i missed out?
public class arraylist {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Random rand = new Random();
int numtogen;
int third;
Scanner scan = new Scanner(System.in);
System.out.println("How many number do you want to generate: ");
numtogen = scan.nextInt();
System.out.println("What number do you want to multiply with the third number: ");
third = scan.nextInt();
HashSet<Integer> generated = new HashSet<Integer>();
// Prevent repeat
for (int x = 1; x <= numtogen; ++x) {
while (true) {
// generate a range from 0-100
int ranNum = rand.nextInt(100);
if (generated.contains(ranNum)) {
continue;
} else {
list.add(ranNum);
System.out.println("Number " + x + "=" + " = " + ranNum);
break;
}
}
}
int numinlist;
while (!list.isEmpty()) {
// Integer[] numlist= numbinlist.hasNextInt;
// int answer = numlist[2]*third;
// System.out.println("Answer to first number = "+answer);
}
}
}
You can change the generation of non-repeating numbers to:
Set<Integer> generated = new LinkedHashSet<Integer>();
// Prevent repeat
while (generated.size() < numtogen) {
generated.add(rand.nextInt(100));
}
List<Integer> list = new ArrayList<Integer>(generated);
I'll edit this answer as soon as I understand your actual problem and know the answer.
If you want to get the 3rd generated number try this:
int number = list.get(2);
change this:
for (int x = 1; x <= numtogen; ++x) {
while (true) {
// generate a range from 0-100
int ranNum = rand.nextInt(100);
if (generated.contains(ranNum)) {
continue;
} else {
list.add(ranNum);
System.out.println("Number " + x + "=" + " = " + ranNum);
break;
}
}
}
to:
for (int x = 1; x <= numtogen; ++x) {
// generate a range from 0-100
int ranNum = rand.nextInt(100);
if (generated.contains(ranNum)) {
continue;
} else {
list.add(ranNum);
System.out.println("Number " + x + "=" + " = " + ranNum);
}
}
Then, all you need to do to access the 3rd number is something like:
int answer = (list.get(2) * third);

Categories