cannot be resolved to a variable java 101 - java

Newbie code for printing a matrix:
import java.util.*;
import java.io.File;
public class Strings {
public static void main(String[] args){
Strings String1 = new Strings();
int alen =0 ,blen =0;
String a,b;
int [][] matrix = new int[alen+1][blen+1];
System.out.println("Enter String a: ");
Scanner usrip = new Scanner(System.in);
a = usrip.next();
System.out.println("Enter String b: ");
b = usrip.next();
System.out.println("Execute print method: ");
String1.printMatrix();
}//end of main
public void printMatrix(){
for(int i=0;i<alen+1;i++)
{
for(int j=0;i<blen+1;j++)
{
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix
}// End class
Since alen , blen are declared in the class not in a mehtod I thought they were global varaibales. But looks like Its not what I think it is.
The error I get is alen cannot be resolved into a variable same for blen and matrix as well.
Same error when I try to access them like String1.alen as well.

the variables "alen" and "blen" you declared in main() are method-local, that means they are not accessible from printMatrix() method. Make them fields instead by writing:
private int alen;
private int blen;
just below the line public class Strings {
or pass them as arguments to printMatrix() method, as Christian suggested.

You cannot access alen, blen and matrix since they are not declared within the printMatrix() scope (you may want to read about scope in Java), here is one simple solution:
Pass the variables as arguments:
public void printMatrix(int alen, int blen, int[][] matrix){
...
}
and call in the main method:
String1.printMatrix(alen, blen, matrix);
Of course, that this is not necessary, you could just do:
public void printMatrix(int[][] matrix){
for(int i=0;i<matrix.length;i++)
{
for(int j=0;i<matrix[i].length;j++)
{
System.out.print(matrix[i][j]);
}
}
}

It is a bit ugly, but for a beginner, you can do the following:
public class Strings {
public int [][] matrix;
public static void main(String[] args){
Strings String1 = new Strings();
int alen =0 ,blen =0;
String a,b;
String1 = new int[alen+1][blen+1];
...
public void printMatrix(){
for(int i=0;i<matrix.length;i++)
{
for(int j=0;i<matrix[0].length;j++)
{
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix
}// End class

this is one way among many:
public void printMatrix(int[][] matrix){
for(int i=0;i<matrix.length;i++) {
for(int j=0;i<matrix[i].length;j++) {
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix`enter code here
call it like:
String1.printMatrix(matrix);

Related

Why is array giving a wrong value when using two classes?

I have this code here.
public class ArrayChallenge {
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Number of integers: ");
int num = kb.nextInt();
int [] returnedArray = readIntegers(num);
System.out.println("Ascending Order: " + printAsc(returnedArray));
}
public static int [] readIntegers(int count){
int [] values = new int[count];
for(int i=0; i<count; i++){
System.out.print("Enter number: ");
values[i] = kb.nextInt();
}
return values;
}
public static int [] printAsc(int [] theArray){
Arrays.sort(theArray);
return theArray;
}
The code above works perfectly fine. I have only one class but several static methods and during calling the method printAsc(returnedArray), the program will return a set of arrays in a format just like using .toString
I took this code to a next level using two classes and making the static methods to instance methods. However when i print the arrays. It prints these values [I#643b1d11
Here is my code below:
Main Class
public class Main {
public static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the number of elements: ");
int num = kb.nextInt();
int numArrays [] = new int[num];
Minimum minimum = new Minimum();
int [] returnedArrays = minimum.readIntegers(numArrays);
int returnedMin = minimum.findMin(returnedArrays);
System.out.println("Minimum Value: " + returnedMin);
System.out.println("Ascending Arrays: " + minimum.arrayAsc(returnedArrays));
}
}
Minimum Class
public class Minimum {
public int [] readIntegers(int [] numArrays){
System.out.println("Enter " + numArrays.length + " integers:");
for(int i=0; i< numArrays.length; i++){
numArrays[i]=Main.kb.nextInt();
}
return numArrays;
}
public int findMin(int [] numArrays){
int max = Integer.MAX_VALUE;
for(int i=0;i<numArrays.length;i++){
if(max>numArrays[i]){
max = numArrays[i];
}
}
return max;
}
public int [] arrayAsc(int [] numArrays){
Arrays.sort(numArrays);
return numArrays;
}
}
How did the result of my arrays became like that? Can someone explain the process to me? Much appreciate.
Also, i used the debug method because im using Intellij, It didnt really show anything.
The way you are using printAsc, you need to change its definition to return a String.
public static String printAsc(int [] theArray){
Arrays.sort(theArray);
return Arrays.toString(theArray);
}
If you do not want to change the definition of printAsc, you need to call it as follows:
System.out.println("Ascending Order: " + Arrays.toString(printAsc(returnedArray)));
You can't just print an Array and expect it to read out all the values. When printing, Java casts the value into a String. By default, when dealing with Objects, Java will simply print the name of the Object's class and its Hash value. This is what you see. You can read more about it here.
If you want to parse the Array into a String that hold all the members of the Array, you might want to take a look at the Arrays.toString method (and how to use it).

Converting String Array into Integer Array by accessing each indexes using loop

I have my example code below. I'm trying to convert the gradeString into gradeInt and I can't seem to do it properly. When I print the value of gradeInt at the end using toString.
It says a blank array which is like this one: [ ]
Thanks for the help!
import java.util.*;
class testing{
public static Scanner console = new Scanner(System.in);
public static int studSize;
public static String [] gradeArr = new String[studSize];
public static int [] gradeInt = new int[gradeArr.length];
public static void initialize(){
System.out.print("Please enter student size: ");
String studString = console.nextLine();
studSize = Integer.parseInt(studString);
enterData();
}
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
convert();
}
public static void convert(){
for(int i=0; i<gradeInt.length; i++){
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
print();
}
public static void print(){
System.out.print(Arrays.toString(gradeArr));
System.out.print(Arrays.toString(gradeInt));
}
public static void main(String [] args){
initialize();
//Main and Class Closing Braces
}
}
Add this line just before your call to convert for the "quick fix":
gradeInt = new int[gradeArr.length];
Try this. The problem is that you are assigning sizes of arrays etc before any data is entered. Actually the usuage of studSize is not needed at all - see comments in code
public static Scanner console = new Scanner(System.in);
public static int studSize;
public static String [] gradeArr;
public static int [] gradeInt;
public static void initialize(){
// not needed -
System.out.print("Please enter student size: ");
String studString = console.nextLine();
// not needed
studSize = Integer.parseInt(studString);
enterData();
}
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
convert();
}
public static void convert(){
// set here as the size is know
gradeInt = new int[gradeArr.length];
for(int i=0; i<gradeArr.length; i++){
// should be carefull of NumberFormatException
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
print();
}
public static void print(){
System.out.print(Arrays.toString(gradeInt));
}
public static void main(String [] args){
initialize();
//Main and Class Closing Braces
}
I ran your code and it works
Output:
[95, 85, 75]
Process finished with exit code 0
I suspect there may be an error in other parts of your code if you're getting a empty array.
What's the context you're running the code in? If you paste the rest of the code it might help finding the real source of the error.
SOLUTION:
Like Andy mentioned. The root error is contained here:
public static int [] gradeInt = new int[gradeArr.length];
You're defining this variable at runtime and assigning it the same length as gradeArr which is 0 at the time.
This results in a logic error that happens in the convert() method.
for(int i=0; i<gradeInt.length; i++){
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
You are telling the code to loop if i was smaller than gradeInt which has a length of 0. Basically it never loops. It just skips the loop entirely.
The quickest way to fix this is to modify the code like this:
Don't assign a length to the gradeInt variable at runtime. Modify the line to this:
public static int [] gradeInt;
And then modify your enterData() method to this:
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
gradeInt = new int[gradeArr.length];
convert();
}

How to pass multiple array to constructor in java?

I have a problem passing a multiple array to constructor.
Can we actually do that or not?
public class First {
public String[] a;
public String[] b;
public First(String[] a, String[] b){
this.a=a;
this.b=b;
}
}
And the next code is where I'm using class First.
Scanner ss = new Scanner(System.in);
int x;
System.out.print("How many lines? ");
x = ss.nextInt();
for(int i=0; i<x; i++){
System.out.print("A: "); a[i]=ss.nextString();
System.out.print("B: "); b[i]=ss.nextString();
}
First ff= new First(a,b);
In NetBeans, there is no error, but I can't use it in another class.
I'd be thankful if you would help me.
There is nothing wrong with passing in multiple arrays to a Java constructor. However, you may want to consider making copies of the arrays that you are passing in (with Arrays.copyOf()). You should also seriously consider making your actual array data private or protected.
The Question is not cleared. You cant use it on another class means. PLease clear your question.. But below code is working fine.. you can check it out.
public class MultipleArr {
String a[];
String b[];
public MultipleArr(String[] a, String[] b)
{
this.a=a;
this.b=b;
}
public static void main(String[] args) {
String [] a={"1","2","3"};
String [] b={"2","2","3"};
MultipleArr arr=new MultipleArr(a,b);
for(int i=0;i<arr.a.length;i++)
{
System.out.println(arr.a[i]);
}
for(int i=0;i<arr.b.length;i++)
{
System.out.println(arr.b[i]);
}
}
}
public class MultipleArr {
String a[];
String b[];
public MultipleArr(String[] a, String[] b)
{
this.a=a;
this.b=b;
}
public static void main(String[] args) {
String [] a;
String [] b;
Scanner ss = new Scanner(System.in);
int x;
System.out.print("How many lines? ");
x = ss.nextInt();
a=new String[x];
System.out.print("A: ");
for(int i=0; i<x; i++)
{
a[i]=ss.next();
}
b=new String[x];
System.out.print("B: ");
for(int i=0; i<x; i++)
{
b[i]=ss.next();
}
MultipleArr arr=new MultipleArr(a,b);
for(int i=0;i<arr.a.length;i++)
{
System.out.println(arr.a[i]);
}
for(int i=0;i<arr.b.length;i++)
{
System.out.println(arr.b[i]);
}
}
}

I'm having trouble writing static methods

I'm not very experienced in making static methods...I wanted some practice and I'm having some problems. I'm trying to make a program where you input a number and it prints out all the squares less than b. For example, if you put in 100, it returns 0, 1, 4, 9, 16, 25, 36, 49, 64, 81.
I'm getting errors, though.
Illegal modifier for parameter getSquares; only final is permitted. This is on the line public static double getSquares(double b)
-The method getSquares(int) is undefined for the type Squares when I try to do Squares.getSquares(100);...I'm guessing this is because of my first problem. Please help me, I know static methods are important but I don't know how to make them.
package Testers;
import java.util.Scanner;
public class Squares
{
public static void main(String[] args)
{
Squares.getSquares(100);
public static double getSquares(double b)
{
double sqrtNum=Math.sqrt(b);
int i=0;
while(i<sqrtNum)
{
sqrtNum=Math.pow(i,2);
System.out.print(sqrtNum+" ");
i++;
}
}
}
}
You can't declare a method inside a method - format your code and it is clearer to see. Example:
package Testers;
import java.util.Scanner;
public class Squares {
public static void main(String[] args) {
Squares.getSquares(100);
}
public static double getSquares(double b) {
double sqrtNum = Math.sqrt(b);
int i = 0;
while(i < sqrtNum) {
sqrtNum = Math.pow(i, 2);
System.out.print(sqrtNum + " ");
i++;
}
}
}
Also, there is no returned value in getSquares() - it looks like you intended to make it void.
Finally, this while loop:
int i = 0;
while(i < sqrtNum) {
// code
i++;
}
can be simplified to this for loop:
for (int i = 0; i < sqrtNum; i++) {
// code
}
Your static method should not be in main() if you want it to be a method of the Squares class. it should be in Squares and not in main, like:
public class Squares
{
public static void main(..) {...}
public static double getSquares(...) {...}
}
You're declaring your method in another method, which doesn't work. Put it outside and it should be good.
package Testers;
import java.util.Scanner;
public class Squares
{
public static void main(String[] args)
{
Squares.getSquares(100);
}
public static double getSquares(double b)
{
double sqrtNum=Math.sqrt(b);
int i=0;
while(i<sqrtNum)
{
sqrtNum=Math.pow(i,2);
System.out.print(sqrtNum+" ");
i++;
}
}
}
In your getSquares method you need a return statement.

Write a class named Calculator with a method int sum(String s)

String s contains a set of integers separated by white space (blanks, tabs, or newlines). Return the sum of the integers.
You can use a Scanner object to solve this problem. Create a new Scanner(s) and store it in a variable, say in. Then, use in.hasNextInt() to control a while loop. Each iteration of the while loop uses in.nextInt() to get the next integer from the String s. Accumulate this integer into a variable and return that variable when the loop exits.
You may use a main method to test your method by creating an instance of the Calculator class and calling sum(…) with several combinations of values using that instance.
For example, sum(“3 4 5 27 3”) is 42.
I have written this so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
}
public int sum(String s){
int i = 0;
Scanner in = new Scanner(s);
while (in.hasNextInt()) {
sum = sum + in.nextInt();
}
return sum;
}
}
To call the method from main and display the results make the sum method static and then call it and print the result:
public static void main(String[] args) {
System.out.println(sum("1 2 3"));
}
import java.util.Scanner;
public class Calculator{
public static void main(String[] args){
System.out.println(sum("1 2 3"));
}
public static int sum(String s){
int i = 0;
int sum = 0;
Scanner in = new Scanner(s);
while (in.hasNextInt()) {
sum = sum + in.nextInt();
}
return sum;
}
}

Categories

Resources