I want to write a program that creates a two-dimensional int array initialized with test data.
The program cannot run. I am confused about the code.Please help with the problem.How to correct my code? Thank you.
public class Int2DArray {
private static int x;
private static int y;
public static int getTotal(int[][] numbers) {
int total = 0;
for (int x = 0; x < numbers.length; x++);
for (int y = 0; y < numbers[x].length; y++);
total = total + numbers[x][y];
return total;
}
public static double getAverage(int[][] numbers) {
double average = 0;
average = getTotal(numbers) / (x + y);
return average;
}
public static int getRowTotal(int[][] numbers, int index) {
int total = 0;
for (int y = 0; y < 3; y++) {
total = total + numbers[index][y];
}
return total;
}
public static int getColumnTotal(int[][] numbers, int index) {
int total = 0;
for (int x = 0; x < numbers.length; x++) {
total = total + numbers[x][index];
}
return total;
}
public static int getHighestInRow(int[][] numbers, int x) {
int high = numbers[x][0];
for (int i = 1; i < 3; i++) {
if (numbers[x][i] > high) {
high = numbers[x][i];
}
}
return high;
}
public static int getLowestInRow(int[][] numbers, int x) {
int low = numbers[x][0];
for (int i = 1; i < 3; i++) {
if (numbers[x][i] < low) {
low = numbers[x][i];
}
}
return low;
}
}
public class Int2DArrayTest {
public static void main(String[] args) {
int[][] iarray = {{2, 1, 9}, {7, 3, 4}, {5, 6, 8}};
System.out.println("Total:" + getTotal(iarray));
System.out.println("Average:" + getAverage(iarray));
System.out.println("Total of row 0" + getRowTotal(iarray, 0));
System.out.println("Total of row 1" + getRowTotal(iarray, 1));
System.out.println("Total of row 2" + getRowTotal(iarray, 2));
System.out.println("Total of col 0" + getColumnTotal(iarray, 0));
System.out.println("Total of col 1" + getColumnTotal(iarray, 1));
System.out.println("Total of col 2" + getColumnTotal(iarray, 2));
System.out.println("Highest in row 0" + getHighestInRow(iarray, 0));
System.out.println("Highest in row 1" + getHighestInRow(iarray, 1));
System.out.println("Highest in row 2" + getHighestInRow(iarray, 2));
System.out.println("Lowest in row 0" + getLowestInRow(iarray, 0));
System.out.println("Lowest in row 1" + getLowestInRow(iarray, 1));
System.out.println("Lowest in row 2" + getLowestInRow(iarray, 2));
}
}
I see one big error:
you can resolve it so:
public static int getTotal(int[][] numbers) {
int total = 0;
for (int x = 0; x < numbers.length; x++);
for (int y = 0; y < numbers[x].length; y++);
total = total + numbers[x][y];
return total;
}
replace for
public static int getTotal(int[][] numbers) {
int total = 0;
for (int x = 0; x < numbers.length; x++){
for (int y = 0; y < numbers[x].length; y++){
total = total + numbers[x][y];
}
}
return total;
}
or better so(using foreach):
public static int getTotal(int[][] numbers) {
int total = 0;
for (int [] x : numbers){
for (int y : x){
total = total + y;
}
}
return total;
}
And use formatting hotkey in your IDE.
public static int getRowTotal(int[][] numbers, int index) {
int total = 0;
for (int y = 0; y < 3; y++) {
total = total + numbers[index][y];
}
return total;
}
here you use constant 3 - it is bad style you need to extract it as constant
public static double getAverage(int[][] numbers) {
double average = 0;
average = getTotal(numbers) / (x + y);
return average;
}
x and y are not initialized in your code
why do you divide by x+y. You need divide on count of element.
You have declared the methods inside Int2DArray as static
public static int getTotal(int[][] numbers) { //
So you need to call them as static in order to use them like:
System.out.println("Total:" + Int2DArray.getTotal(iarray));
You are having following line twice, so an obvious syntactical error.
public class Int2DArrayTest {
Moreover, you also have logical error in getAverage function.
average = getTotal(numbers) / (x + y);
It shows divide by zero exception.
Related
I am doing a solution to a coding problem, and I tweaked some existing code to be able to figure out how many semi-primes exist up till and including a certain number.
However, I am stuck at the part where I want to count the number of unique semi-primes between two numbers e.g. 10 and 4, which would be 4,6,9 and 10, i.e. 4. My answer is simply saying 10 has 4 semi-primes, 4 has 1 semi-primes, so the sub-primes between them are 4-1 =3. This is where I am going wrong.
Code is here:
public class SemiPrimeRange {
public static int[] solution(int N, int[] P, int[] Q) {
int arrSize = P.length;
int[] arr = new int[arrSize];
for (int i = 0; i < arr.length; i++) {
int n = NoSemiPrimes(Q[i]);
int m = NoSemiPrimes(P[i]);
arr[i] = n-m;
}
for (int i : arr) {
System.out.println(i);
}
return arr;
}
public static int NoSemiPrimes(int large) {
int n = 0;
boolean[] primeTop = new boolean[large + 1];
boolean[] semiprimeTop = new boolean[large + 1];
for (int i = 2; i <= large; i++) {
primeTop[i] = true;
}
for (int i = 2; i * i <= large; i++) {
if (primeTop[i]) {
for (int j = i; i * j <= large; j++) {
primeTop[i * j] = false;
}
}
}
int primes = 0;
for (int i = 2; i <= large; i++) {
if (primeTop[i])
primes++;
}
for (int i = 0; i < large; i++) {
semiprimeTop[i] = false;
}
for (int i = 0; i <= large; i++) {
for (int j = i; j <= large; j++) {
if (primeTop[j]&&primeTop[i]) {
if(i*j<=large){
semiprimeTop[j*i] = true;
}
}
}
}
for (int i = 0; i < semiprimeTop.length; i++) {
System.out.println(semiprimeTop[i]);
}
int semiprimes = 0;
for (int i = 2; i <= large; i++) {
if (semiprimeTop[i])
semiprimes++;
}
System.out.println("The number of semiprimes <= " + large + " is " + semiprimes);
return semiprimes;
}
public static void main(String[] args) {
int[] P = { 1, 4, 16 };
int[] Q = { 26, 10, 20 };
int N = 26;
solution(N, P, Q);
}
If you want number of semi-primes between y and x (y > x), count(y) - count(x) (count(a) is number of semi-primes between a and 1) is not a correct formula because it will omit x if it is semi-prime. Correct formula is count(y) - count(x - 1).
Also note that your code is ineffective because it will count between 1 and the lesser number twice.
The method signature should be
public static int NoSemiPrimes(int small, int large)
and change the loop
int semiprimes = 0;
for (int i = 2; i <= large; i++) {
if (semiprimeTop[i])
semiprimes++;
}
to
int semiprimes = 0;
for (int i = small; i <= large; i++) {
if (semiprimeTop[i])
semiprimes++;
}
to count the number of semi-primes in desired range directly instead of using int NoSemiPrimes(int large) twice.
I was tasked with creating a 2D array (10-by-10), filling it with random numbers (from 10 to 99), and other tasks. I am, however, having difficulty sorting each row of this array in ascending order without using the array sort() method.
My sorting method does not sort. Instead, it prints out values diagonally, from the top leftmost corner to the bottom right corner. What should I do to sort the numbers?
Here is my code:
public class Program3
{
public static void main(String args[])
{
int[][] arrayOne = new int[10][10];
int[][] arrayTwo = new int[10][10];
arrayTwo = fillArray(arrayOne);
System.out.println("");
looper(arrayTwo);
System.out.println("");
sorter(arrayTwo);
}
public static int randomRange(int min, int max)
{
// Where (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
return (int)(Math.random()* ((max - min) + 1) + min);
}
public static int[][] fillArray(int x[][])
{
for (int row = 0; row < x.length; row++)
{
for (int column = 0; column < x[row].length; column++)
{
x[row][column] = randomRange(10,99);
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
return x;
}
public static void looper(int y[][])
{
for (int row = 0; row < y.length; row++)
{
for (int column = 0; column < y[row].length; column++)
{
if (y[row][column]%2 == 0)
{
y[row][column] = 2 * y[row][column];
if (y[row][column]%10 == 0)
{
y[row][column] = y[row][column]/10;
}
}
else if (y[row][column] == 59)
{
y[row][column] = 99;
}
System.out.print(y[row][column] + "\t");
}
System.out.println();
}
//return y;
}
public static void sorter(int[][] z)
{
int temp = 0;
int tempTwo = 0;
int lowest;
int bravo = 0;
int bravoBefore = -1;
for (int alpha = 0; alpha < z.length; alpha++)
{
//System.out.println(alpha + "a");
lowest = z[alpha][bravoBefore + 1];
bravoBefore++;
for (bravo = alpha + 1; bravo < z[alpha].length; bravo++)
{
//System.out.println(alpha + "b");
temp = bravo;
if((z[alpha][bravo]) < lowest)
{
temp = bravo;
lowest = z[alpha][bravo];
//System.out.println(lowest + " " + temp);
//System.out.println(alpha + "c" + temp);
tempTwo = z[alpha][bravo];
z[alpha][bravo] = z[alpha][temp];
z[alpha][temp] = tempTwo;
//System.out.println(alpha + "d" + temp);
}
}
System.out.print(z[alpha][bravoBefore] + "\t");
}
/*
for (int alpha = 0; alpha < z.length; alpha++)
{
for (int bravo = 0; bravo < z.length - 1; bravo++)
{
if(Integer.valueOf(z[alpha][bravo]) < Integer.valueOf(z[alpha - 1][bravo]))
{
int[][] temp = z[alpha - 1][bravo];
z[alpha-1][bravo] = z[alpha][bravo];
z[alpha][bravo] = temp;
}
}
}
*/
}
}
for(int k = 0; k < arr.length; k++)
{
for(int p = 0; p < arr[k].length; p++)
{
least = arr[k][p];
for(int i = k; i < arr.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < arr[i].length; z++)
{
if(arr[i][z] <= small)
{
least = array[i][z];
row = i;
col = z;
}
}
}
arr[row][col] = arr[k][p];
arr[k][p] = least;
System.out.print(arr[k][p] + " ");
}
System.out.println();
}
Hope this code helps . Happy coding
let x is our unsorted array;
int t1=0;
int i1=0;
int j1=0;
int n=0;
boolean f1=false;
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
t1=x[i][j];
for(int m=i;m<x.length;m++){
if(m==i)n=j+1;
else n=0;
for(;n<x[m].length;n++){
if(x[m][n]<=t1){
t1=x[m][n];
i1=m;
j1=n;
f1=true;
}
}
}
if(f1){
x[i1][j1]=x[i][j];
x[i][j]=t1;
f1=false;
}
}
}
//now x is sorted; "-";
/*METODA MAIN*/
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
int m, n;
int sloupec;
float prumerSloupce;
System.out.println("zadej pocet radku pole: ");
m = sc.nextInt();
System.out.println("zadej pocet sloupcu pole: ");
n = sc.nextInt();
int[][] a;
/*NAPLNENI POLE NAHODNYMI CISLY*/
a = naplnPole(m, n);
/*TISKNUTI POLE*/
tiskPole(a);
System.out.println("Zadej cislo sloupce, jehoz prumer chces znat ");
sloupec = sc.nextInt();
prumerSloupce = aritmetickyPrumerSloupce(a, sloupec);
/*METODA NAPLNENI POLE*/
public static int[][] naplnPole(int m, int n) {
int[][] x = new int[m][n];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
x[i][j] = (int) Math.round(Math.random() * 9);
}
}
return x;
} /*METODA TISKNUTI POLE*/
public static void tiskPole(int[][] x) {
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
System.out.print(x[i][j] + " ");
}
System.out.println();
}
}
/*METODA ZJISTENI ARITMETICKEHO PRUMERU SLOUPCE*/
public static float aritmetickyPrumerSloupce(int[][] a, int sloupec) {
int sum = 0;
for (int i = 0; i < a.length; i++)
sum += array[i][sloupec];`this is the error line`
return sum / (float) a.length;
}
Everything works except the method, i'm trying to get average of a column from a matrix that consist of random numbers. number of rows and columns is defined by typing from scanner.
You aren't defining your array a anywhere that I can see;
int[][] a = { { 1, 2 }, { 3, 4 } };
System.out.println(Arrays.deepToString(a));
// ...
prumerSloupce = aritmetickyPrumerSloupce(a, column);
and your function should be using a.length like
public static float aritmetickyPrumerSloupce(int[][] a, int column) {
int sum = 0;
for (int i = 0; i < a.length; i++)
sum += a[i][column];
return sum / (float) a.length;
}
Ive already wrote code that will take the temp for each month and then show and calculate the total, average, most and least rainfall for the year and output that. How do I replace the most and least rainfall with actually months names?
code so far:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Rainfall
{
public static void main(String[] args)
{
String [] months={"Janurary","Febuary","March","April","May","June","July","August","September","October","November","December"};
final int MONTHS = 12;
double[] rain = new double[MONTHS];
initRain(rain);
double total = totalRain(rain);
double average = averageRain(rain, total);
int most = mostRain(rain);
int least = leastRain(rain);
// Decimal Format
DecimalFormat digit = new DecimalFormat("#.0");
// Output
System.out.println("The total rainfall of the year is " + digit.format(total));
System.out.println("The average rainfall of the year is " + digit.format(average));
System.out.println("The month with the highest amount of rain is " + (most + 1));
System.out.println("The month with the lowest amount of rain is " + (least + 1));
}
public static void initRain(double[] array)
{
Scanner keyboard = new Scanner(System.in);
for (int x = 0; x < array.length; x++)
{
System.out.print("Enter Rainfall for month " + (x + 1) + ": ");
array[x] = keyboard.nextDouble();
}
}
public static double totalRain(double[] array)
{
double total = 0;
for (int x = 0; x < 12; x++)
total += array[x];
return total;
}
public static double averageRain(double[] array, double total)
{
return total / array.length;
}
public static int mostRain(double[] array)
{
double maximum = array[1];
int value = 0;
for (int i=0; i < 12; i++) {
if (array[i] >= maximum) {
maximum = array[i];
value = i;
}
}
return months[index];
}
public static int leastRain(double[] array)
{
double minimum = array[0];
int value = 0;
for (int i=0; i < 12; i++)
{
if (array[i] <= minimum) {
minimum = array[i];
value = i;
}
}
return value;
}
}
Well, you've got an index, and you've got an array of the names of the months, so... ?
String most = months[mostRain(rain)];
I guess that this code is not even compiling
see
public static int mostRain(double[] array)
{
double maximum = array[1];
int value = 0;
for (int i=0; i < 12; i++) {
if (array[i] >= maximum) {
maximum = array[i];
value = i;
}
}
return months[index];
}
as it is expecting to be returned an int but you are returning a String (also index does not exist), so what you want is
public static int mostRain(double[] array)
{
double maximum = 0.00; // change this too
int value = 0;
for (int i=0; i < 12; i++) {
if (array[i] >= maximum) {
maximum = array[i];
value = i;
}
}
return value; // change this
}
then you can use it above like
System.out.println("The month with the highest amount of rain is " + months [mostRain (rain)]);
Of course, make the similar change for leastRain too.
I'm stuck... My code was working earlier, but now it just hangs. On top of that I can't seem to get my getHighest and getSmallest methods to return the correct values. I don't know if I'm just not catching something. Any help would be great!
import java.util.Scanner;
import java.text.DecimalFormat;
public class Rainfall
{
public static void main(String[] args)
{
final int MONTHS = 12;
double[] rain = new double[MONTHS];
initRain(rain);
double total = totalRain(rain);
double average = averageRain(rain, total);
double most = mostRain(rain);
double least = leastRain(rain);
DecimalFormat digit = new DecimalFormat("#.0");
System.out.println("The total rainfall of the year is " + digit.format(total));
System.out.println("The average rainfall of the year is " + digit.format(average));
System.out.println("The month with the highest amount of rain is " + most);
System.out.println("The month with the lowest amount of rain is " + least);
}
public static void initRain(double[] array)
{
Scanner keyboard = new Scanner(System.in);
for (int x = 0; x < array.length; x++)
{
System.out.print("Enter Rainfall for month " + (x + 1) + ": ");
array[x] = keyboard.nextDouble();
}
}
public static double totalRain(double[] array)
{
double total = 0;
for (int x = 0; x < 12; x++)
total += array[x];
return total;
}
public static double averageRain(double[] array, double total)
{
return total / array.length;
}
public static double mostRain(double[] array)
{;
double maximum = array[1];
int value = 0;
for (int i=0; i < 12; i = i++)
{
if (array[i] >= maximum)
maximum = array[i];
value = i;
}
return value;
}
public static double leastRain(double[] array)
{
double minimum = array[0];
int value;
for (int i=0; i < 12; i++)
{
if (array[i] <= minimum)
minimum = array[i];
value = i;
}
return value;
}
}
Your program hangs because of this line:
for (int i=0; i < 12; i = i++)
The problem is that i++ returns the value of i before the variable is incremented, so the increment step of your loop is the same as writing i=i. Thus, the variable i never reaches the escape condition of the loop.
it should be:
for (int i=0; i < 12; i++)
Cleaned up your code a little bit, can be improved a lot. There were many simple errors.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Rainfall
{
public static void main(String[] args)
{
final int MONTHS = 12;
double[] rain = new double[MONTHS];
initRain(rain);
double total = totalRain(rain);
double average = averageRain(rain, total);
int most = mostRain(rain);
int least = leastRain(rain);
DecimalFormat digit = new DecimalFormat("#.0");
System.out.println("The total rainfall of the year is " + digit.format(total));
System.out.println("The average rainfall of the year is " + digit.format(average));
System.out.println("The month with the highest amount of rain is " + (most + 1));
System.out.println("The month with the lowest amount of rain is " + (least + 1));
}
public static void initRain(double[] array)
{
Scanner keyboard = new Scanner(System.in);
for (int x = 0; x < array.length; x++)
{
System.out.print("Enter Rainfall for month " + (x + 1) + ": ");
array[x] = keyboard.nextDouble();
}
}
public static double totalRain(double[] array)
{
double total = 0;
for (int x = 0; x < 12; x++)
total += array[x];
return total;
}
public static double averageRain(double[] array, double total)
{
return total / array.length;
}
public static int mostRain(double[] array)
{
double maximum = array[1];
int value = 0;
for (int i=0; i < 12; i++) {
if (array[i] >= maximum) {
maximum = array[i];
value = i;
}
}
return value;
}
public static int leastRain(double[] array)
{
double minimum = array[0];
int value = 0;
for (int i=0; i < 12; i++)
{
if (array[i] <= minimum) {
minimum = array[i];
value = i;
}
}
return value;
}
}