There is the error I am getting
Exception in thread "main" java.lang.NullPointerException
at StudentGrades.getMinimum(StudentGrades.java:54)
at StudentClient.main(StudentClient.java:14)
I did not find any method that i set a null.
I tried using median method but still gets me this same error.
import java.util.Arrays;
import java.util.Random;
public class StudentGrades {
Random randomNumber = new Random();
int numberofStudents;
int grade;
int[] grades;
int sum = 0;
public StudentGrades(int studentNumber) {
numberofStudents = studentNumber;
int[] grades = new int[numberofStudents];
for (int i = 0; i < numberofStudents; i++) {
grades[i] = randomNumber.nextInt(101);
Arrays.sort(grades);
}
}
public int getNumberStudents() {
return numberofStudents;
}
public int[] getStudentGrades() {
int[] temp = new int[grades.length];
for (int i = 0; i < grades.length; i++) {
temp[i] = grades[i];
}
return temp;
}
public void setStudentGrades(int n) {
grade = n;
}
public double getAverage() {
for (int i = 0; i < grades.length; i++) {
sum = +grades[i];
}
double average = (double) sum / numberofStudents;
return average;
}
public int getMaximum() {
int max = grades[0];
for (int i = 0; i < grades.length; i++) {
if (grades[i] > grades[max])
max = grades[i];
}
return max;
}
public int getMinimum() {
int min = grades[0];
for (int i = 0; i < grades.length; i++) {
if (grades[i] < grades[min])
min = grades[i];
}
return min;
}
public String toString() {
String returnString = "grades :";
for (int i = 0; i < grades.length; i++) {
returnString += grades[i];
}
return returnString;
}
public double getMedian() {
double median = 0;
if (grades.length % 2 == 0) {
median = (grades[grades.length / 2] + grades[(grades.length / 2) + 1]) / 2;
} else
median = grades[((grades.length - 1) / 2) + 1];
return median;
}
}
In your constructor you declared a local variable grades which did not initialize your instance variable grades:
int [] grades = new int [numberofStudents];
So the instance variable grades remains null. Try this:
grades = new int [numberofStudents];
which refers to the instance variable instead of declaring a local variable.
Related
My program isn't sorting the numbers at all. It displays them in the order they were initially entered. It must sort them from smallest to largest number. The code below should find the largest number in the array and swap it with the last .the code is below:
import java.util.Scanner;
public class maxSorttt {
public static void main(String[] args) {
double[] ten = new double[10];
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < ten.length; i++)
ten[i] = input.nextDouble();
sort(ten);
}
public static void sort(double[] array) {
for (int i = array.length - 1; i < 0; i--) {
double currentMax = array[i];
int currentMaxIndex = i;
for (int x = i - 1; x < -1; x--) {
if (currentMax < array[x]) {
currentMax = array[x];
currentMaxIndex = x;
}
}
if (currentMaxIndex != i) {
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
}
I believe your problem is here:
for(int i=array.length-1; i<0; i--)
array.length is not less than 0 so the for loop never runs. You probably wanted
for(int i=array.length-1; i>=0; i--)
Be Simple!
public static void selectionSort(double[] arr) {
for (int i = 0; i + 1 < arr.length; i++) {
int minIndex = findMinIndex(arr, i + 1);
if (Double.compare(arr[i], arr[minIndex]) > 0)
swap(arr, i, minIndex);
}
}
private static int findMinIndex(double[] arr, int i) {
int minIndex = i;
for (; i < arr.length; i++)
if (Double.compare(arr[i], arr[minIndex]) < 0)
minIndex = i;
return minIndex;
}
private static void swap(double[] arr, int i, int j) {
double tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
I have a java code to read the length of an integer array, output the range, length of the gap, and any distinct elements inside. Additionally, it will output the numbers again with none repeated.
I would like to shorten the length of my main method.
My code produces the correct output, it is just very lengthy. Additionally, is there a way I can edit this main method to where it won't require a drastic change to my other methods? Thank you so much!
package ArrayPrograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
***public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
in.close();
}
}***
Sure thing. Here you go:
package arrayprograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
static void showResults(int[] array, int num, WIP obj){
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
in.close();
showResults(array, num, obj );
}
}
There's not a whole lot you can do, like most of the comments say, but you can remove and edit some of the braces around that aren't necessary for the bodies. Here is a rough draft of it. The only things you could change besides that is to store all of the WIP.tests in variables in one code block and then print them all out in another code block; which would improve readability.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
WIP obj = new WIP();
System.out.print("Enter the length of the array:");
int num = in.nextInt();
int array[] = new int[num] ;
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println("The largest gap in the array is " + WIP.LargestGap(array,num) + ".");
System.out.println("The range of the array is " + obj.range(array,num) + ".");
int numberofDistinct = obj.numberOfDistinctElement( array, num );
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray = obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
System.out.print(distinctArray[i]+"]");
else
System.out.print( distinctArray[i]+ ",");
in.close();
}
I am trying to find a median of an array in Java.
I am getting the exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method median(double[]) in the type tez3 is not applicable for the arguments (int[])
at tez3.main(tez3.java:33)
My code is below. What is the problem? How can i print the double function ?
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class tez3 {
public static void main(String args[]) throws java.io.IOException {
Scanner s = new Scanner(new File("C:\\tny\\Deneme1.txt"));
int[] numberList = new int[10];
int i = 0;
int count = 0;
int result = 0;
while (s.hasNextInt()) {
numberList[i++] = s.nextInt();
}
for (i = 0; i < numberList.length; i++) {
System.out.println(+(i + 1) + ".Value: " + numberList[i]);
}
for (i = 0; i < numberList.length; i++) {
count++;
}
for (i = 0; i < numberList.length; i++) {
result += numberList[i];
}
System.out.println("Average of the Values is: " + result / count);
System.out.println("Mode of the Values is: " + mode(numberList));
System.out.println("Median of the Values is: " + median(numberList));
}
public static int mode(int numberList[]) {
int maxValue = 0, maxCount = 0;
for (int i = 0; i < numberList.length; ++i) {
int count = 0;
for (int j = 0; j < numberList.length; ++j) {
if (numberList[j] == numberList[i]) {
++count;
}
}
if (count > maxCount) {
maxCount = count;
maxValue = numberList[i];
}
}
return maxValue;
}
public double median(double[] numberList) {
int factor = numberList.length - 1;
double[] first = new double[(double) factor / 2];
double[] last = new double[first.length];
double[] middleNumbers = new double[1];
for (int i = 0; i < first.length; i++) {
first[i] = numbersList[i];
}
for (int i = numberList.length; i > last.length; i--) {
last[i] = numbersList[i];
}
for (int i = 0; i <= numberList.length; i++) {
if (numberList[i] != first[i] || numberList[i] != last[i]) {
middleNumbers[i] = numberList[i];
}
}
if (numberList.length % 2 == 0) {
double total = middleNumbers[0] + middleNumbers[1];
return total / 2;
} else {
return middleNumbers[0];
}
}
}
The problem is exactly what the error message says. Your method median() takes a double[] as parameter.
But when you're trying to call it you give it numberList as a parameter. But numberList is an int[], that is to say it is not a double[].
The easiest fix is to modify median() so that the parameter it takes is int[] rather than double[].
The problem is that you want to cast all elements in you int[] list to a double.
If you don't want to change the parameters of median to int[] then my preferred way to deal with this is to overload the method and convert the arguments
So, it would be something like:
public double median(int[] numberList) {
double[] doubleList = new double[numberList.size()];
for(int i=0; i<doubleList.size(); i++){
doubleList[i] = (double)numberList[i];
}
return median(doubleList);
}
If you did change the parameter of your original 'median' method, then you would just cast the numberList element each time you called it, i.e.
first[i] = (double) numbersList[i];
I think I have most of the code figured out, there is just one part that is giving me grief. When I use printList(list) it prints out 1, 2, 3,... up to 9 when it is supposed to be printing the squares of these numbers. If I print out the createSquaresList(10) it is correctly printed. Any help is appreciated :-).
import java.util.*;
public class Lab8a
{
public static void main(String args[])
{
ArrayList<Double> list = createSquaresList(10);
printList(list);
removeElement(list, 4);
printList(list);
swapElements(list, 2, 6);
printList(list);
double max = getMaxValue(list);
double ave = getAverage(list);
System.out.println("Max Value = " + max);
System.out.println("Average = " + ave);
int idx1 = linearSearch(list, 4);
int idx2 = linearSearch(list, 75);
System.out.println("idx 1 = " + idx1);
System.out.println("idx 2 = " + idx2);
}
public static ArrayList<Double> createSquaresList(int n)
{
ArrayList<Double> squares= new ArrayList<>();
double s = 0.0;
for (double i = 0.0; i <= n-1; i++)
{
s = i*i;
squares.add(s);
}
return squares;
}
public static double getMaxValue(ArrayList<Double> list)
{
double largest = list.get(0);
for (int i = 1; i < list.size(); i++)
{
if (list.get(i) > largest)
{
largest = list.get(i);
}
}
return largest;
}
public static double getAverage(ArrayList<Double> list)
{
double avg = 0.0;
double sum = 0.0;
for (int i =0; i < list.size(); i++)
{
sum += list.get(i);
}
avg = sum / list.size();
return avg;
}
public static void removeElement(ArrayList<Double> list, double index)
{
double temp = 0.0;
int lastPos = list.size() - 1;
double last = list.get(lastPos);
index = temp;
temp = last;
last = index;
list.remove(lastPos);
}
public static void swapElements(ArrayList<Double> list, int a, int b)
{
int temp = 0;
a = temp;
temp = b;
b = a;
}
public static int linearSearch(ArrayList<Double> list, double val)
{
int pos = 0;
boolean found = false;
while (pos < list.size() && !found)
{
if (list.get(pos) == val)
{
found = true;
}
else
{
pos++;
}
}
if (found)
{
return pos;
}
else
{
return -1;
}
}
public static void printList(ArrayList<Double> list)
{
for(int i = 0; i < list.size(); i++)
{
System.out.print(i);
if(i < list.size()-1)
{
System.out.print(", ");
}
}
System.out.println("");
}
}
Change
System.out.print(i);
to
System.out.print(list.get(i));
it is because you are print the int not the contents of the list,
try changing the 3 line of the function printList to:
System.out.print(list.get(i));
Hey guys I'm having problems figuring out how to write my driver class for my Array class.
My questions
1.How do I make the array in my Array class reference the array in my Driver class?
2.How do I pass my class methods from my Array class to my Driver class so I can print them out?
Here's my two bits of code
Main class:
import javax.swing.*;
import java.util.*;
public class Array
{
double sum = 0;
int max = 0;
int min = numbers[0];
double sd = 0;
int mode = 0;
int modeCount = 0;
public double average()
{
for(int i=0; i<numbers.length; i++)
{
sum = sum + numbers[i];
}
double average = sum / numbers.length;
return average;
}
public int max()
{
for(int i=0; i<numbers.length; i++)
{
if(numbers[i] > max)
{
max = numbers[i];
}
}
return max;
}
public int min()
{
for(int i=0; i<numbers.length; i++)
{
if(numbers[i] < min)
{
min = numbers[i];
}
}
return min;
}
public double standardDeviation()
{
for (int i=0; i<numbers.length;i++)
{
sum = sum + numbers[i];
double average = sum / numbers.length;
{
sd += ((numbers[i] - average)*(numbers[i] - average)) / (numbers.length - 1);
}
}
double standardDeviation = Math.sqrt(sd);
return standardDeviation;
}
public int mode()
{
for (int i = 0; i < numbers.length; ++i)
{
int count = 0;
for (int j = 0; j < numbers.length; ++j)
{
if (numbers[j] == numbers[i]) ++count;
}
if (count > modeCount) {
modeCount = count;
mode = numbers[i];
}
}
return mode;
}
}
Driver class:
import javax.swing.*;
import java.util.*;
public class ArrayTest
{
public static void main(String [] args)
{
int[] numbers;
numbers = new int [20];
Random rand = new Random(2621);
int maxRange = 65;
int minRange = 20;
for(int i=0; i<20; i++)
{
numbers[i] = rand.nextInt(maxRange - minRange + 1) + minRange;
}
Arrays.sort(numbers);
}
}
Looks a lot like a homework assignment...
In your Array class, you can keep a reference to the array and then have a method called setArray() that you can use to pass the array from your main class to your Array class.
int[] numbers;
public void setArray(int[] nums) {
numbers = nums;
}
then from your main class you can call
Array.setArray(myIntArray);
int max = Array.max();
In real life (other than for programming practice), you would never want to do this though.