g cannot be resolved to a variable - java

g cannot be resolved to a variable is the error popping up. I've initialised g in the for loop, so why this error ? I'm a beginner, so can anybody explain in as many simple and understandable words as possible.
import java.util.Scanner;
public class Bellman {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of nodes");
int n = sc.nextInt();
System.out.println("Enter the cost matrix");
for (int j = 0; j<n; j++) {
for (int k = 0; k<n; k++) {
int g[j][j] = sc.nextInt();
}
}
}
}
g cannot be resolved to a variable. I've initialised g in the for loop, so why this error ?

this is most likely what you want to achieve:
int g[][] = new int[n][n];
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
g[j][k] = sc.nextInt();
}
}
You have to initialize the array with a specific size, only then you can assign values at a given indexes.

Related

How can I sort using two different packages?

I had an assignment for a class where I had to develop a simple number sort program.
My main is supposed to receive the user input and my sort class is supposed to interrupt and spit out the resulting numbers in ascending and descending order. The problem is that my main is taking the input but it's not putting it in order at all and I'm unsure why.
package main;
import sort.Sort;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int arr[] = new int[5];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<5; i++) {
System.out.print("Enter a number: ");
myScanner.nextLine();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
}
package sort;
public class Sort {
public void ascendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void descendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
}
I know I'm missing something in my Main, because I'm fairly certain I don't need to put anything else into the sort class.
You're code is perfect. You just missed one assignment in your main method.
Instead of myScanner.nextLine(); you should have written arr[i] = myScanner.nextLine();
myScanner.nextLine(); is getting the next line you enter in the console but it isn't saving it anywhere. arr[i] = myScanner.nextLine(); will save the value of the console in the arr array.
Everything else should work after that.
First you are getting user input using myScanner.nextLine() but not storing it. myScanner.nextLine() won't save anything which user enters .
Thus you need to store it in an array and then use it later. So your main method after the changes should be like this.
public static void main(String[] args) {
int arr[] = new int[3];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<3; i++) {
System.out.print("Enter a number: ");
arr[i] = myScanner.nextInt();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
And your sorting functions are also wrong. There you do some mis-calculations and return / log nothing. Thus you will not see anything in the console if you are not logging or returning anything.
public void descendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
public void ascendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
I hope this functions will work for your use case of ascending and descending sort.

why am I getting this error : data structures (arrays)?

I basically need to find the number of sub arrays that have a negative sum.
import java.io.*;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
static int add(int a[]) {
int sum = 0;
for (int i = 0; i < a.length; ++i) {
sum = sum + a[i];
}
return sum;
}
public static void main(String[] args) {
/*
* Enter your code here.
* Read input from STDIN.
* Print output to STDOUT.
* Your class should be named Solution.
*/
int count = 0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int k = 0; k < n; ++k) {
arr[k] = sc.nextInt();
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n - i; ++j) {
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
if (add(slice) < 0) {
++count;
}
}
}
System.out.println(count);
}
}
Compile Message
Solution.java:32: error: variable j is already defined in method main(String[])
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
^
1 error
Exit Status
255
Its because of the scope of the variable j here. When you refer a variable in map, JVM tries to initiliaze this. In your case, JVM is trying to initialize j with the contents of the map but it is already available at that point from your second for loop. Just use any other variable such as 'k' to get it done.
import java.io.*;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
static int add(int a[])
{
int sum= 0;
for(int i = 0; i < a.length; ++i)
{
sum = sum + a[i];
}
return sum;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int count = 0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int k = 0; k < n; ++k)
{
arr[k] = sc.nextInt();
}
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n - i; ++j)
{
int slice[] = IntStream.range(j, j + i + 1).map(k -> arr[k]).toArray();
if(add(slice) < 0)
{
++count;
}
}
}
System.out.println(count);
}
}
This line declares a variable j which is already declared as the loop counter in that scope:
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
You will have to give it a differen name to get rid of this compilation error:
for (int i = 0; i < n; ++i) {
// this is where j is defined for the loop scope
for (int j = 0; j < n - i; ++j) {
// replace the j inside the .map(...)
int slice[] = IntStream.range(j, j + i + 1).map(s -> arr[s]).toArray();
if (add(slice) < 0) {
++count;
}
}
}

java my array runs with for loops, but nothing displays?

I don't understand why this runs but does not print anything. (I am new to coding altogether, so any advice is great.)
import java.util.Scanner;
import java.util.Random;
public class ArrayDoubleValues{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
// Length input
System.out.println("Length: ");
int length = scan.nextInt();
int[] list = new int[length];
for (int i = 0; i == list.length; i++){
list[i] =(int)(Math.random()+ 1) * 100;
System.out.print(list.length);
}
for(int i = 0; i == list.length; i++){
System.out.println(list[i]);
}
}
}
You have a wrong condition here --
for (int i = 0; i == list.length; i++){
Your program never enters these loops because i is not equal to list.length when you reach them. Instead, it should be
for (int i = 0; i < list.length; i++) { ... }

finding cofactor and determinant of a 3x3 matrix (java)

I computed the product, sum, and transpose(of product), but I have no clue where to start on the cofactor and determinent of the product matrix.
Ive seen a couple examples but none that resemble my particular code so if anyone could show me how i could incorporate these two methods into my program I'd high appreciate it.
please dont ask me what i've tried because as I stated I am clueless at the moment
//here is the code I wrote for the product:
package programEx;
import java.io.*;
import java.util.*;
import java.io.File.*;
import java.util.Scanner;
public class progEx {
public static void main(String[] args) {
//Establishing Input Stream
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in A: ");
int rowsInA = s.nextInt();
System.out.print("Enter number of columns in A / rows in B: ");
int columnsInA = s.nextInt();
System.out.print("Enter number of columns in B: ");
int columnsInB = s.nextInt();
int[][] a = new int[rowsInA][columnsInA];
int[][] b = new int[columnsInA][columnsInB];
//Taking user input for 1st matrix
System.out.println("Enter matrix A");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][j] = s.nextInt();
}
}
//Taking user input for 2nd matrix
System.out.println("Enter matrix B");
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[0].length; j++) {
b[i][j] = s.nextInt();
}
}
//calling the multiplication method and passing it to both matrices
int[][] c = multiply(a, b);
System.out.println("Product of A and B is");
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[0].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
//Separate method for the multiplication of 1st and 2nd matrices
public static int[][] multiply(int[][] a, int[][] b) {
int rowsInA = a.length;
int columnsInA = a[0].length;
int columnsInB = b[0].length;
int[][] c = new int[rowsInA][columnsInB];
for (int i = 0; i < rowsInA; i++) {
for (int j = 0; j < columnsInB; j++) {
for (int k = 0; k < columnsInA; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return c;
}
}
Well,a 3*3 matrix has 3 columns and 3 rows to begin with.
Each starts with an index 0.
Determinant can be calculated as:
int d=determinant();
int determinant()
{
int x=a[0][0]*((a[1][1]*a[2][2])-(a[2][1]*a[1][2]));
int y=-a[0][1]*((a[0][1]*a[2][2])-(a[2][0]*a[1][2]));
int z=a[0][2]*((a[1][0]*a[2][1])-(a[1][1]*a[2][0]));
int r=x+y+z;
return r;
}
This is only for finding the determinant of a 3*3 matrix.

If statements in 2D arrays

When I am trying to run this code it shows java.lang.ArrayIndexOutOfBoundsException Error. Please help me to fix this code.
import java.util.*;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Random r = new Random();
final int N, S;
System.out.print("Input No of Students : ");
N = input.nextInt();
System.out.print("No of Subject : ");
S = input.nextInt();
int[][] st = new int[N][S];
int[] stNo = new int[N];
int[] stMax = new int[N];
for (int i = 0; i < N; i++) {
stNo[i] = r.nextInt(10000);
for (int j = 0; j < S; j++) {
st[i][j] = r.nextInt(101);
}
}
// Find max Value of marks of a Student
for (int i = 0; i < N; i++) {
for (int j = 0; j < S; j++) {
if (st[i][j] > st[i][j + 1]) {
stMax[i] = st[i][j + 1];
}
}
}
// Display marks
// Dispaly Column names
System.out.print("stNo\t");
for (int i = 1; i < S + 1; i++) {
System.out.print("Sub " + i + "\t");
}
System.out.print("Max");
// Print Values
for (int i = 0; i < N; i++) {
System.out.print(stNo[i] + "\t");
for (int j = 0; j < S; j++) {
System.out.print(st[i][j] + "\t");
}
System.out.print(stMax[i]);
System.out.println();
}
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (here shows the input for "S")
at pack1.Example.main(Example.java:31)
As I am a new to coding I can not fix this. Please help me to fix this.
Thanks
An ArrayIndexOutOfBoundsException error means you exceed the boundaries of the array. In your case, st has S colomns and you tried to reach the S+1-th element (index S).
st[i][j + 1] => when j == S-1 (the end of the loop), you do an out of bounds.
Now, as your comment say, you're looking for the max value. Then the code should be:
stMax[i] = 0;
for (int j = 0; j < S; j++) {
if (st[i][j] > stMax[i]) {
stMax[i] = st[i][j];
}
}
What your code is doing is comparing the current value to the next one. And every time the next value is greater than the current one, you update stMax[i]. This does not make sense.
This line is causing the exception:
stMax[i] = st[i][j + 1];
You are iterating j to the end of the array, and always looking for the next element. So when j reaches the end of the array it is still looking for one more index, hence the outOfBoundsException.

Categories