Write Point Array - arrays

I work on a trainigs code to compare the distance of an unspecific number of points from the zero point.
The error appears when i want to write the input point values into the Point array and i don't know how to handle it:
points[i].setLocation(x,y);
Error says: Exception in thread "main" java.lang.NullPointerException
at minDis.minDis.main(minDis.java:59)
I would be thankful for any advices.
import java.awt.Point;
import java.util.Scanner;
public class minDis {
private static final Point Point = null;
static double dis(Point p){
double dis= Math.sqrt(p.x*p.x+p.y*p.y);
return dis;
}
static double minDist(Point[] points, int anz){
double minimum= dis(points[0]);
for(int z=0; z<anz; z++){
if (dis(points[z]) < minimum)
minimum=dis(points[z]);
}
return minimum;
}
static double minDistPoint(Point[] points, int anz){
double minimum= dis(points[0]);
int DistPoint = 0;
for(int z=0; z<anz; z++){
if (dis(points[z]) < minimum)
minimum=dis(points[z]);
DistPoint=z;
}
return DistPoint;
}
public static void main(String[] args) {
Point points[]=null;
Scanner scan= new Scanner(System.in);
System.out.println("How many Points do you want to compare?");
int anz= scan.nextInt();
for(int i=0; i<anz; i++){
System.out.println("Type in Point "+anz);
System.out.println("X: ");
int x= scan.nextInt();
System.out.println("Y: ");
int y= scan.nextInt();
**points[i].setLocation(x,y);**
}
scan.close();
System.out.println("It is Point "+minDistPoint(points, anz)+" with a distance of "+ minDist(points, anz));
}
}

In your code snippet, you are not allocating memory for the Pointer Object array. That's why you are getting NullPointerException. Therefore, you need to allocate memory to the array of Point objects in your code.
But, remember when you create a array of objects like this,
Object[] arr = new Object[10];
Here you are just creating 10 Object References. Now, to do any operations with individual array elements, you need to allocate memory to each object also, For Example,
arr[i] = new Object();
So, use the following snippet as the corrected version for your code.
public static void main(String[] args) {
Point[] points;
Scanner scan= new Scanner(System.in);
System.out.println("How many Points do you want to compare?");
int anz= scan.nextInt();
points = new Point[anz];
for(int i=0; i<anz; i++) {
points[i] = new Point();
System.out.println("Type in Point "+anz);
System.out.println("X: ");
int x= scan.nextInt();
System.out.println("Y: ");
int y= scan.nextInt();
points[i].setLocation(x,y);
}
scan.close();
System.out.println("It is Point "+ minDistPoint(points, anz)+" with a distance of "+ minDist(points, anz));
}

Related

Passing arrays between methods, and accessing them accordingly

I'm supposed to use two methods to hold arrays, then with the two arrays determine win % of the rockets, average margin of score difference for the games lost by Houston Rockets, and the lowest Houston Rockets’ score and the corresponding game number. I primarily need help with the first one, and I can get the other tasks. I just dont know how to pass arrays from methods very well. Any help would be useful, THanks!
import java.util.Scanner;
public class MorenoJonathonRocketsStatistics
{
public static void main(String[] args)
{
System.out.println("enter rockets game scores");
int[] rockets = rocketsScore();
System.out.println("enter opponents scores");
int[] opponents = opponentsScore();
int per = percent();
System.out.println("game win percent"+per+" %");
}
public static int[] rocketsScore()
{
Scanner sc = new Scanner(System.in);
int[] rocketsScore = new int[8];
for(int i=0;i<rocketsScore.length;i++)
{
rocketsScore[i] = sc.nextInt();
}
return rocketsScore;
}
public static int[] opponentsScore()
{
Scanner sc = new Scanner(System.in);
int[] opponentsScore = new int[8];
for(int i=0;i<opponentsScore.length;i++)
{
opponentsScore[i] = sc.nextInt();
}
return opponentsScore;
}
public static int percent(int[] array, int[] array2)
{
int[] rock = rocketsScore.length();
int[] opp = opponentsScore.length();
double percent=0;
int w=0, l=0;
for(int i=0; i<rocketsScore.length;i++)
{
if(rocketsScore[i]>opponentsScore[i])
{
w++;
}
else{
l++;
}
}
percent = w/l;
return percent;
}
}
To pass array in methods, you don't need to put any brackets beside the variable that is holding the array. So, you may want to do it like below:
int per = percent(rockets, opponents);

arrays of random numbers

hello everyone I got this codes but I need to make some constraint on my arrays: public static void main (String[] args)
{Random myRand = new Random ();
// Pick array size T from 1 to 100.
int T = 1 + myRand.nextInt(5);
System.out.println("T="+(T));
int C = 1 + myRand.nextInt(100);
System.out.println("C="+(C));
// Declare array of size T.
int [] production_cost=new int [T];
int []stock1= new int [T];
int[]stock2= new int [T];
int[]fix_cost1= new int [T];
int[]fix_cost2= new int [T];
int[] Demands=new int[T];
// Fill the array with random numbers.
{for (int i=0; i< T; i++){
production_cost[i] = myRand.nextInt(Integer.max(0,20));
stock1[i] = myRand.nextInt(Integer.max(0, 20));
stock2[i]= myRand.nextInt(Integer.max(0,20));
fix_cost1[i]=myRand.nextInt(Integer.max(10, 20) );
fix_cost2[i]=myRand.nextInt(Integer.max(20,30));
Demands[i] = myRand.nextInt(Integer.max(1,C));}
System.out.println("p2::"+Arrays.toString(production_cost));
System.out.println("h1::"+Arrays.toString(stock1));
System.out.println("h2::"+Arrays.toString(stock2));
System.out.println("K1::"+Arrays.toString(fix_cost1));
System.out.println("K2::"+Arrays.toString(fix_cost2));
System.out.println("d::"+Arrays.toString(Demands));
You can see this link : Fill an array with random numbers
You need to add logic to assign random values to double[] array using
randomFill method.
Change
public static double[] list(){
anArray = new double[10];
return anArray; }
To
public static double[] list() {
anArray = new double[10];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray; }
Then you can call methods, including list() and print() in main method to generate random double values and print the
double[] array in console.
public static void main(String args[]) {
list(); print(); }
One result is as follows:
-2.89783865E8
1.605018025E9
-1.55668528E9
-1.589135498E9
-6.33159518E8
-1.038278095E9
-4.2632203E8
1.310182951E9
1.350639892E9
6.7543543E7

Adding the elements of a BigDecimal Array in java

I am new to Java and I came up to this error in my program where I can't add the elements in an array of BigDecimal elements. I successfully made it with Integer and Double types but when I change the type to BigDecimal, it won't work at all.
import java.math.*;
import java.util.*;
public class AddBigRealNumbers {
public static void main(String[] args) {
try{
Scanner von = new Scanner(System.in);
System.out.println("Enter the number of figures to be added:");
int numfig;
numfig = von.nextInt();
BigDecimal []nums = new BigDecimal[numfig];
System.out.println("Enter the elements:");
for(int i=0; i<numfig;i++){
nums[i]=von.nextBigDecimal();
}
System.out.println("The elements are: ");
for(int i=0; i<numfig;i++){
System.out.println(nums[i]);
}
BigDecimal sum=BigDecimal.ZERO;
for (BigDecimal i : nums)
sum += i;
System.out.println("The sume of these numbers is:"+sum);
}
catch(Exception e){
System.out.println("Your exception is:" +e);
}
}
}
You can't add BigDecimal with +, you have to use its add() function. It is also immutable, so using the same BigDecimal sum for the whole addition won't work.
BigDecimal isn't just another class for numbers like Integer and Double are.
Because BigDecimal is immutable as LisaMM pointed out, you will need to increment your sum like so:
for (BigDecimal i : nums) {
sum = sum.add(i);
}
...
sum.add(i); <-- this wont't work
Instead we need to reassign a new BigDecimal to sum using its current value incremented by i.
BigDecimal sum = null;
for (int i = 0; i < lengthOfArray; i++) {
if (sum == null) {
sum = data[i];
} else {
sum = sum.add(data[i]);
}
}

How can I put an array into a method?

I have to find the LCM of two integers using the prime factors method and function calls.
I'm up to making a function to find the prime factorization of the first number, but I'm getting errors at int x = first_number; and with System.out.print(primeFactorization).
This is my code so far:
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int first_number;
int second_number;
System.out.print("Enter an integer: ");
first_number = reader.nextInt();
System.out.print("Enter another integer: ");
second_number = reader.nextInt();
}
public static int primeFactorization(int[] pfArray) {
int counter = 0;
pfArray = new int[10]; //created array in memory
int x = first_number;
for(int i=2;i<=x;i++){
while(x%i==0){
x=x/i;
pfArray[counter] = i;
++counter;
}
}
for(int i=0;i<counter;i++){
System.out.println(pfArray[i]);
}
}
System.out.println(primeFactorization);
}
I am just starting to learn Java, so please answer in very basic terms!
Thanks so much!
The variable first_number is declared in the first method and so cannot be used within the second method unless you pass it in as a parameter.
The only thing called primeFactorisation is the method. System.out.println requires an object (a variable) as its input. So you can't do it like that.

Returning Arrays from Methods

So I have to display the marks that are below average, and all the marks that are above average.
I don't know where to go with this next but here's what I have so far:
public static void main (String[]args) {
int[]marks={50,60,30,90,70,40,80,44};
int average=average(marks);
int[]resultBelowAverage=getBelowAverage(marks,average);
printIntArray(resultBelowAverage);
int[]resultAverageandAbove=getAverageandAbove(marks,average);
printIntArray(resultAverageandAbove);
}
This next method is used to calculate the average. I got the right answer for this one which is 58.
public static int average(int[] marks) {
int i=0;
int total=0;
for(i=0;i<marks.length;i++){
total=total+marks[i];
}
int average=total/i;
return average;
}
This next method gets how many values in the array are below average.
public static int countBelowAverage (int[] numbers,int av){
int size=0;
for(int i=0;i<numbers.length;i++) {
if (numbers[i]<av) {
size=size+1;
}
}
return size;
}
This next method gets how many values in the array are above average.
public static int countAboveAverage (int[] numbers,int av) {
int size=0;
for(int i=0;i>=numbers.length;i++) {
if (numbers[i]>=av) {
size=size+1;
}
}
return size;
}
This next method gets which values in the array are below average. I think this is where I went wrong.
public static int[] getBelowAverage(int[]numbers,int av) {
int size=countBelowAverage(numbers,av);
int[]belowAverage=new int[size];
return belowAverage;
}
This next method gets which values in the array are above average.
public static int[] getAverageandAbove(int[] numbers,int av) {
int size=countAboveAverage(numbers,av);
int[]AboveAverage=new int[size];
return AboveAverage;
}
This last method prints the arrays that are classified into below average and above average.
public static void printIntArray(int[]x) {
for(int i=0;i<x.length;i++){
System.out.println (x[i]);
}
}
In your method getAverageandAbove you make an array, but you do not put anything in it.
you should loop through your numbers array again, and fill your AboveAverage array with the values that are greater than the average.
Try something like this to get the below average array
public static int[] getBelowAverage(int[]numbers,int av){
int size=countBelowAverage(numbers,av);
int[]belowAverage=new int[size];
int j = 0;
for (int i = 0; i < numbers.length; i++){
if (numbers[i] < av){
belowAverage[j] = numbers[i];
j++;
}
}
return belowAverage;
}
Do similar for the above average method
In your methods you just creating arrays of proper size, an empty arrays and returning them. You should put some marks that are below / above average to these arrays before returning
Like here:
int[]belowAverage=new int[size];
//you have an empty array just after creation with nothing inside
//enter here marks from the marks array that are below average
return belowAverage;
Exactly the same situation here:
int[]AboveAverage=new int[size];
//you have an empty array just after creation with nothing inside
//enter here marks from the marks array that are above average
return AboveAverage;
You may use an algorithm from peeskillet's solution to do it.

Resources