For Loop is not running properly - java

Situation with the code is I think that the for loop in the private method is not getting int[] userArray. I have spent hours trying to figure out why the for loop is not working, I even tried using while loop.
public class Arrays {
static Scanner scan = new Scanner(System.in);
private static int sizeOfArrayWanted;
private static double average = 0;
/**
* private static int smallestNumber=1;
*
* private static int count = 0; private static int total=0; private static
* int average=total/count; private static int largestNumber=0; private static
* int standardDeviation=0; private static int meanOfSD=0; private static int
* x1=0; private static int[] userArray= new int [0];
**/
private static int total1 = 0;
private static int standardDeviation = 0;
private static int finalAverage = 0;
public static void main(String[] args) {
// int randomNumber = (int)((Math.random() * 9) + 1);
System.out.println("Hello how big would you like the array?");
int sizeOfArrayWanted = scan.nextInt();
int smallestNumber = 1;
int largestNumber = 0;
int total = 0;
int standardDeviation = 0;
int count = 0;
double average = 0;
int[] userArray = new int[sizeOfArrayWanted];
for (int x = 0; x < sizeOfArrayWanted; x++) {
userArray[x] = (int) ((Math.random() * 9) + 0);
total = total + userArray[x];
count++;
if (userArray[x] < smallestNumber) {
smallestNumber = userArray[x];
}
if (userArray[x] > largestNumber) {
largestNumber = userArray[x];
}
System.out.print(userArray[x] + ", ");
average = total / count;
}
System.out.println("");
System.out.println("largest Number= " + largestNumber);
System.out.println("smallest Number= " + smallestNumber);
System.out.println("average =" + (total / count));
Arrays.computeStandardDeviation(userArray, sizeOfArrayWanted);
}
private static int computeStandardDeviation(int[] userArray, int sizeofArrayWanted) {
int x1 = 0;
while (x1 < sizeofArrayWanted) {
x1++;
userArray[x1] = (int) (userArray[x1] - average);
userArray[x1] = (int) Math.pow(userArray[x1], 2);
total1 = total1 + userArray[x1];
finalAverage = total1 / x1;
standardDeviation = (int) Math.sqrt(finalAverage);
}
return standardDeviation;
}
}
When I try to compile the program, I get the following errors:
Exception in thread "main" largest Number= 6
smallest Number= 1
average =4
java.lang.ArrayIndexOutOfBoundsException: 5
at Arrays.computeStandardDeviation(Arrays.java:80)
at Arrays.main(Arrays.java:67)

You increment x1 after the check. Making it 1 too large for array at last iteration. Move x1++ into average calculation.
while(x1<sizeofArrayWanted)
{
// x1++;
finalAverage = total1 / ++x1;

The issue is from the computeStandardDeviation method. The index starts at 0, so increasing it immediately will cause it not to look at the first spot in the array and therefore also check the last index + 1 location. It should be like this
private static int computeStandardDeviation(int [] userArray, int sizeofArrayWanted)
{
int x1=0;
while(x1<sizeofArrayWanted)
{
userArray[x1]=(int) (userArray[x1]-average);
userArray[x1]=(int) Math.pow(userArray[x1], 2);
total1=total1+userArray[x1];
finalAverage=total1/x1;
standardDeviation= (int) Math.sqrt(finalAverage);
x1++; // move this here
}
return standardDeviation;
}

Array index out of bounds exception is because you are incrementing x1 before doing operations, rather you should do all operations and increment x1 at the end. Otherwise, at the last iteration of the loop, you will be accessing an element outside the scope of the array.
private static int computeStandardDeviation(int[] userArray, int sizeofArrayWanted) {
int x1 = 0;
while (x1 < sizeofArrayWanted) {
userArray[x1] = (int) (userArray[x1] - average);
userArray[x1] = (int) Math.pow(userArray[x1], 2);
total1 = total1 + userArray[x1];
finalAverage = total1 / x1;
standardDeviation = (int) Math.sqrt(finalAverage);
x1++; //Increment should be done after all operations
}
return standardDeviation;
}
Also you dont need to pass the size parameter explicitly here, since you can just get the size from the array passed to the method.

Related

Cannot invoke "City.getX()" because "city[i]" is null

Hey Im working on a homework and i got stuck, i need to return the name of the two citys with the least amount of distance between them, the citys must be in order that the second one is after the first one (first i, second i+1);
Thanks.
public class Maincity {
public static void main(String[] args) {
City [] cityArr = new City[10];
String[] nameArr = new String[] {"Hadera","Beer Sheva","Haifa", "Ashdod", "Eilat", "Jerusalem", "Ashkelon", "Tel Aviv", "Hertzila", "Netanya"};
for (int i=0;i<cityArr.length;i++) {
int rRandom = (int)(Math.random() * 100000) + 10000;
int xRandom = (int)(Math.random() * 10000) + 1000;
int yRandom = (int)(Math.random() * 10000) + 1000;
City ir = new City(nameArr[i], rRandom, xRandom, yRandom);
System.out.println(ir);
}
System.out.println(Distance(cityArr));
}
public static int Distance(City[] city) {
int min = 100000000;
for (int i = 0; i < city.length; i++) {
int newX = city[i].getX() - city[i + 1].getX();
int newY = city[i].getY() - city[i + 1].getY();
newX = (int) Math.pow(newX, 2);
newY = (int) Math.pow(newY, 2);
int nDistance = (int) (Math.sqrt(newX) + Math.sqrt(newY));
if (nDistance < min) {
min = nDistance;
}
}
return min;
}
}
There were 2 problems:
You didn't put the city into array.
The index calculation (i+1) throwed ArrayIndexOutOfBoundsException
public static void main(String[] args) {
String[] nameArr=new String[] {"Hadera","Beer Sheva","Haifa", "Ashdod", "Eilat", "Jerusalem", "Ashkelon", "Tel Aviv", "Hertzila", "Netanya"};
City [] cityArr= new City[nameArr.length];
for(int i=0;i<cityArr.length;i++) {
int rRandom = (int)(Math.random()*100000)+10000;
int xRandom = (int)(Math.random()*10000)+1000;
int yRandom = (int)(Math.random()*10000)+1000;
City ir = new City(nameArr[i],rRandom, xRandom, yRandom);
cityArr[i] = ir;
System.out.println(ir);
}
System.out.println(Distance(cityArr));
}
public static int Distance(City[] city) {
int min =100000000;
for(int i=0;i<city.length;i++) {
int nextCityIndex = (i+1) % city.length;
int newX =city[i].getX() - city[nextCityIndex].getX();
int newY =city[i].getY() - city[nextCityIndex].getY();
newX = (int) Math.pow(newX, 2);
newY = (int) Math.pow(newY, 2);
int nDistance = (int) (Math.sqrt(newX)+Math.sqrt(newY));
if(nDistance<min) {
min=nDistance;
}
}
return min;
}

Create bar graph using Java

I am working on an assignment to create a bar graph using Java using random numbers, but I do not know how to code it properly, it keeps on giving errors when I move on to the next step.
public class BinSort {
final int N_BINS = 0; //number of bins
final int N_SAMPLES = 0; //total random integers
final float BIN_WIDTH = 0; //width of the bin
int [] nums; //generate and store random numbers
int [] binCount; //array
int max = 0; //largest random number = (max-1)
public void main(String[] args) {
int nBins, nSamples; //initializers
BIN_WIDTH = (float) (max/N_BINS); //calculate BIN_WIDTH
nums = new int[] {}; //initialize nums array
for (int i = 0; i < max; i++) {
int array = nums[i];
}
}
public void generateBins() {
int bin;
int [] binCount = new int [N_BINS]; //set binCount array with N_BINS elements
for (int i = 0; i < N_SAMPLES; i++) {
int array = binCount[i];
bin = (int) Math.floor(nums[i]/BIN_WIDTH);
}
}
public void printBins() {
float freq;
for(int i = 0; i < binCount.length; i++) {
freq = (binCount[i]/N_SAMPLES);
System.out.print(N_SAMPLES + " random integers in " + binCount + " sorted into " + N_BINS + " bins:");
float binMin = i * BIN_WIDTH;
float binMax = binMin + BIN_WIDTH;
System.out.println(binCount[i] + freq + binMin + binMax);
}
}
}
This code is incomplete, but I do not know what to do next. So, I am stuck.
Can someone please help me?
Edit: The program does not compile after running in eclipse. It says the execution is terminated in the console.
Only static variables can be used in the static method . Below code is compiling fine:
public class BinSort {
static final int N_BINS = 0; //number of bins
static final int N_SAMPLES = 0; //total random integers
static float BIN_WIDTH = 0; //width of the bin
static int [] nums; //generate and store random numbers
int [] binCount; //array
static int max = 0; //largest random number = (max-1)
public static void main(String[] args) {
int nBins, nSamples; //initializers
BIN_WIDTH = (float) (max/N_BINS); //calculate BIN_WIDTH
nums = new int[] {}; //initialize nums array
for (int i = 0; i < max; i++) {
int array = nums[i];
}
}
public void generateBins() {
int bin;
int [] binCount = new int [N_BINS]; //set binCount array with N_BINS elements
for (int i = 0; i < N_SAMPLES; i++) {
int array = binCount[i];
bin = (int) Math.floor(nums[i]/BIN_WIDTH);
}
}
public void printBins() {
float freq;
for(int i = 0; i < binCount.length; i++) {
freq = (binCount[i]/N_SAMPLES);
System.out.print(N_SAMPLES + " random integers in " + binCount + " sorted into " + N_BINS + " bins:");
float binMin = i * BIN_WIDTH;
float binMax = binMin + BIN_WIDTH;
System.out.println(binCount[i] + freq + binMin + binMax);
}
}
}

Why does the below code returns wrong answer?

Here I'm comparing ArmstrongNo & out were both have same values(371), but is printing the wrong statement.
public class ArmstrongNumber {
static int ArmstrongNo = 371;
static int sum = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
ArmstrongNumber am = new ArmstrongNumber();
int out = am.Armstrong();
System.out.println(out);
if (ArmstrongNo == out)
System.out.println("It is an Armstrong number");
else
System.out.println("Not an Armstrong number");
}
public int Armstrong() {
int length = String.valueOf(ArmstrongNo).length();// To find the length of integer
for (int x = 0; x < length; x++) {
int i = ArmstrongNo % 10;
int cube = i * i * i;
sum += cube;
ArmstrongNo = ArmstrongNo / 10;
}
return sum;
}
}
OUTPUT:
371
Not an Armstrong number
you are overwriting your ArmstrongNo here ArmstrongNo = ArmstrongNo / 10;
sum is then 371 but ArmstrongNo is 0
EDIT
this fixes your code (at least functionally)
public int Armstrong() {
int ArmstrongNoCopy = ArmstrongNo;
int length = String.valueOf(ArmstrongNoCopy)
.length();// To find the length of integer
for (int x = 0; x < length; x++) {
int i = ArmstrongNoCopy % 10;
int cube = i * i * i;
sum += cube;
ArmstrongNoCopy = ArmstrongNoCopy / 10;
}
return sum;
}
Your method public int Armstrong() modifies static variable ArmstrongNo. To avoid this, do declare this static variable as final and add local variable to the method public int Armstrong():
final static int ArmstrongNo = 371;
public int Armstrong() {
int ArmstrongNo = ArmstrongNumber.ArmstrongNo;
//...
}

Array Index Out of Bounds Exception in 1 of 3 Methods [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
This should be a fairly simple homework assignment, but I've been pounding my face on it for a while now ... When executed, it should just populate an array and find the mean and standard deviation. I'm getting an out of bounds exception, but only in the arrayDeviation method. Any direction would be appreciated.
import java.util.Scanner;
import java.util.Random;
public class StandardDeviation
{
//declare global variables
final static int ELEMENTS = 100;
public static void main(String [] args)
{
//declare variables
final int RANGE = 500;
int[] numList = new int[ELEMENTS];
Random rand = new Random();
//populate array
for(int count = 0; count < ELEMENTS; count++)
{
numList[count] = rand.nextInt(RANGE) + 1;
}
//call printArray
printArray(numList);
//call arrayAverage
double mean = arrayAverage(numList);
System.out.println("\nMean: " + mean);
//call arrayDeviation
double standardDeviation = arrayDeviation(numList, mean);
System.out.print("Standard deviation: " + standardDeviation);
} //end main
//output 10 elements per line
public static void printArray(int[] list)
{
final int ELEMENTS_PER_LINE = 10;
for(int count = 0; count < ELEMENTS; count++)
{
System.out.printf("%-4d", list[count]);
if ((count + 1) % ELEMENTS_PER_LINE == 0)
{
System.out.println();
}
}
}
//returns average as double
public static double arrayAverage(int[] list)
{
int sum = 0, count;
double average;
for(count = 0; count < ELEMENTS; count++)
{
sum = sum + list[count];
}
average =(double) sum / count;
return average;
}
//calculate and return standard deviation
public static double arrayDeviation(int[] list, double mean)
{
double sum = 0.0, standardDeviation;
int count;
for(count = 0; count < ELEMENTS; count++);
{
sum = sum + Math.pow((list[count] - mean), 2);
}
standardDeviation = Math.sqrt(sum / 2);
return standardDeviation;
}
} //end class
Staring at this code for like 10 minutes I couldn't see why it's giving that Exception.Pasting it in Netbeans and it instatly highlights an empty for-loop
public static double arrayDeviation(int[] list, double mean)
{
double sum = 0.0, standardDeviation;
int count;
for(count = 0; count < ELEMENTS; count++); //This semicolon is your
//problem
{
sum = sum + Math.pow((list[count] - mean), 2);
}

Finding the median and max value of an array in java

I used this code to calculate the max value and the median element in an array of integers, but when I call the methods in my client class, both of these two methods produce an output of zero. The name of the array is "grades" and it is made of randomly generated integers
import java.util.*;
public class StudentGrades {
private int [] grades;
//Constructor
public StudentGrades ( int students)
{
Random number = new Random();
grades = new int[students];
for (int i = 0 ; i < students ; i++)
{
grades[i] = number.nextInt(99) + 1;
}
}
double median;
public void median()
{
Arrays.sort(grades) ;
double median ;
if (grades.length % 2 == 0)
{
int indexA = (grades.length - 1 ) /2;
int indexB = (grades.length)/2;
median = ((double) (grades[indexA] + grades[indexB]))/2;
}
else
{
int medIndex = (grades.length-1) / 2;
median = grades[ medIndex ];
}
}
public double getMedian()
{
return median;
}
int max;
public int getHighest()
{
for(int i = 0 ; i < grades.length - 1 ; i++)
{
int max = 0;
if(grades[i] > max)
{
max = grades[i];
}
}
return max;
}
In my driver, I simply had to prove that the method worked correctly, so it's:
System.out.println(" The highest grade is" + grades.getHighest());
System.out.println("The median grade is" + grades.getMedian());
Few mistakes.
1.) Might be calling getMedian(), whereas the logic is inside median() method.
2.) Inside method, getHighest(),
a.) No need to loop the array, since array is already sorted. So i have commented the code.
Just get the value at last index of array.
public class Test {
static int max;
static double median;
static int[] grades = { 2, 3, 4, 5, 62, 34 };
public static void main(String args[]) {
Arrays.sort(grades);
median();
getHighest();
System.out.println(median);
System.out.println(max);
}
public static void median() {
if (grades.length % 2 == 0) {
int indexA = (grades.length - 1) / 2;
int indexB = (grades.length) / 2;
median = ((double) (grades[indexA] + grades[indexB])) / 2;
} else {
int medIndex = (grades.length - 1) / 2;
median = grades[medIndex];
}
}
public double getMedian() {
return median;
}
public static int getHighest() {
/* for (int i = 0 ; i < grades.length ; i++) {
if (grades[i] > max) {
max = grades[i];
}
}*/
max = grades[grades.length - 1];
return max;
}
Output
4.5
62

Categories

Resources