Variable not accessable - java

Im doing a bit of java home work and I seem to be having a small problem. The problem im having is the variable that Im trying to reference is showing that it is not initialized. However, I declared the variable earlier in the method and then had it initialized in a loop. When i try to access the variable when i make the charCount call a few lines later in the same method, the compiler complains that the variable still needs to be initialized. Can someone explain why this isnt working as i think it should.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class test {
public int charCountHelper(File handle, Character x) throws IOException {
int count = 0;
String data;
int index;
Character[] contents;
Scanner inputFile = new Scanner(handle);
while(inputFile.hasNext()){
data=inputFile.nextLine();
index = data.length()-1;
for(int i = 0; i< data.length(); i++){
contents = new Character[data.length()] ;
contents[i] = data.charAt(i);
}
count += charCount(contents,x,index);
}
inputFile.close();
return count;
}
public int charCount(Character[] content, Character x, int index) {
if(index < 0){
return 0; // this value represents the character count if the program reaches the beginning of the array and has not found a match.
}
if (content[index].equals(x)) {
return 1 + charCount(content, x, index - 1);
}
return charCount(content, x, index - 1); // this is the value that gets returned to the original calling method.
}
}

In your code, contents will not be initialized if data.length() is equal to 0. Initializing contents in the loop is in any case not correct, because if you do it that way, it will only contain one character assigned during the latest initialization of the loop. Simply move the line initializing contents above the loop.

Related

trying to print arrays in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I had a code I needed to submit and every time I try to run it, I get the same errors over and over again.
Here's the question
Write the following Java methods:
(a). readValues to input ten integer values into an array of integers
TAB from a text file “Values.txt”. This array TAB is passed to the
method as parameter. Assume that the number of students in the file is
equal to the length of the array.
(b). oddValues that takes the array TAB as parameter and returns the
number of odd values found in TAB.
(c). replaceOdd that takes the array TAB as a parameter. It should
replace every odd value in TAB by the sum of all odd values.
Hint: your method must first compute the sum of all odd values.
(d). printValues that takes the array TAB as a parameter and prints
its content on the screen.
(e). main that declares the array TAB and calls the above four
methods.
N.B.: In your program, use the methods and variable names as mentioned
above.
And this is the code:
import java.util.*;
import java.io.*;
public class Finalexam
{
public static void main (String [] args ) throws FileNotFoundException
{
int sum=0;
int [] TAB=new int [10];
ReadValues(TAB);
oddValues(TAB);
replaceOdd(TAB);
printValues(TAB);
System.out.println("The sum is" + sum);
}
public static void ReadValues (int [] TAB)
{
{ int i;
for(i=0; i<10; i++){
Scanner s = new Scanner ("Values.txt") ;
TAB[i]=s.nextInt();
}
}
s.close();
}
public static double oddValues(int[] TAB)
{
int i;
double odd=0;
int fn=0;
for(i=1; i<odd; i++){
while(odd % 2 !=0)
{
odd = fn;
}
break;
}
return fn;
}
public static int replaceOdd(int[] TAB)
{
int re=0;
for(int i=0; i<TAB.length; i++){
re = re/TAB.length;
}
return re;
}
public static void printValues(int[] TAB)
{
int i;
for(i=0; i<10; i++){
System.out.println(TAB[i]+"\t");
}
System.out.println();
}
}
In which part I'm doing wrong? I cant even run it.
Firstly there is a compilation error in your code.
In your method
public static void ReadValues (int [] TAB)
{
{ int i;
for(i=0; i<10; i++){
Scanner s = new Scanner ("Values.txt") ;
TAB[i]=s.nextInt();
}
}
s.close();
}
You have too many extra brackets, well thats not the problem though, the problem is the scanner object s is declared inside the for loop where as you are closing it later outside the loop, since the scope of the variable is not outside the loop, hence the error.
The correct way should be
public static void readValues (int [] tab){
int i;
Scanner s = new Scanner ("Values.txt") ;
for(i=0; i<10; i++){
tab[i]=s.nextInt();
}
s.close();
}
Also there are many thing that will work in your code but is a bad practice or is not following conventions.
Variable names (e.g tab) should always be in camel case. It should only be a capital if it is a constant, which is not in your case.
The method names starts with small letter.
Also you are calling the two methods replaceOdd(TAB) and oddValues(TAB) But the return value is not being used anywhere.
FileNotFoundException will never be thrown
If you closely look at this method below
public static double oddValues(int[] TAB) {
int i;
double odd = 0;
int fn = 0;
for (i = 1; i < odd; i++) {
while (odd % 2 != 0) {
odd = fn;
}
break;
}
return fn;
}
The loop will never execute as odd is 0 so i<odd will always be false. Also the logic for odd is wrong.
public static int replaceOdd(int[] TAB){
int re=0;
for(int i=0; i<TAB.length; i++){
re = re/TAB.length;
}
return re;
}
This method will always return zero, the logic is wrong.
There are many more logical errors. I would suggest you to look into them as well

Accessing scope of a variable once declared outside class

Hi I have this code to get shortest word in a string:-
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = null;
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=1;i<words.length;i++){
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
int p = shortestLocation;
return p;
}
}
It returns error that variable shortestLocation cannot be converted to int:-
java:6: error: incompatible types: <null> cannot be converted to int
int shortestLocation = null;
My question is how do you access the scope of a variable,like in this case I know what is wrong. The variable shortest location is defined outside the scope of if statement,hence it considers only the value with which it was initialized.
How do i make it so that the initial value is changed to the if-statement value. It is a scope problem,please help i am beginner.
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = null;
this ^^ line needs to be initialized to an integer... not 'null' 0 is fine
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=1;i<words.length;i++){
your problem starts here ^^ you never iterate through all of the words as you stop at i<words.length the problem with that is you begin at i=1. for loops work like this for (begin here; until this is not met; do this each time) when i=words.length the condition is no longer met.
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
int p= shortestLocation;
No need to initialize p here... just return shortest location.
return p;
}
}
that leaves the final code like this
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = 0;
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=0;i<words.length;i++){
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
return shortestLocation;
}
}
Keep in mind, to get a 'good' result it HEAVILY weighs on the words list
As pointed out in the comments initializing your original 'int p' could help with debugging.

Java is not recognizing an object created as an array [duplicate]

This question already has answers here:
Accessing arrays with methods
(4 answers)
Closed 8 years ago.
I am creating a simple mechanical computer emulator, with virtual counters and punch cards, but I keep getting errors in java.
It creates counters as an array of objects like this:
private static void createcounters(int counternums, int digits,
int[] countervals){
for (int i=0; i<counternums; i++){
try {
if (digits < 1){
System.out.println("Invalid number of digits, reverting to 1 digit");
digits = 1;
}
Counter[] counter = null;
counter[i] = new Counter(digits, countervals[i]);
} catch (Exception ex) {
}
}
}
The object is referenced at a different point in a program to read values and put those in a integer array:
public int[] getcounters(){
int[] countervals = null;
for (int i=0; i<counternums; i++){
countervals[i] = counter[i].ReturnVal;
}
return countervals;
}
Java gives this error on compiliation:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: variable counter
location: class mechanicalcomputeremulator.Computer
at mechanicalcomputeremulator.Computer.getcounters(Computer.java:49)
at mechanicalcomputeremulator.MechanicalComputerEmulator.main(MechanicalComputerEmulator.java:20)
Java Result: 1
If I reference the counter in the method that the objects are created, the error doesn't appear.
You've got at least four problems:
You're declaring the counter variable as a local variable inside your method. I suspect you meant to declare a field somewhere - or return a reference from the method, and assign it to an instance variable there.
You're initializing the variable to null and then immediately trying to dereference it. How do you expect that to work?
You're declaring a different variable for each iteration of the loop. I strongly suspect you mean to declare one variable and populate the same array in all iterations.
You're catching Exception and just ignoring it. Never do that. (Ideally don't do either part of it.)
So sample better code:
private static void createCounters(int counterNums,
int digits,
int[] counterVals) {
// Moved out of the loop, as it's pointless there.
if (digits < 1) {
// TODO: Throw an exception instead?
System.out.println("Invalid number of digits, reverting to 1 digit");
digits = 1;
}
counter = new Counter[counterNums];
for (int i=0; i < counterNums; i++) {
counter[i] = new Counter(digits, counterVals[i]);
}
}
Or:
private static Counter[] createCounters(int counterNums,
int digits,
int[] countervals) {
if (digits < 1) {
// TODO: Throw an exception instead?
System.out.println("Invalid number of digits, reverting to 1 digit");
digits = 1;
}
Counter[] counter = new int[counterNums];
for (int i=0; i < counterNums; i++) {
counter[i] = new Counter(digits, counterBals[i]);
}
return counter;
}
Note that if counterNums is the same as the length of counterVals, you can remove that parameter and just use counterVals.length.
Counter[] counter in createCounters is a method-scoped variable. It will not be available in a different method. If you want to make it available to all methods in your class then it needs to be a field.
However, you need to be aware you are using static on the createcounters method, so you can't access an instance field unless you remove the static keyword on the method.
You also can't do Counter[] counter = null; and then assign values to it, you need to do Counter[] counter = new Counter[size];. I suspect you also want an expandable array, so should use an ArrayList instead.
public class MyClass {
private Counter[] counter = new Counter[10]; // arbitrary fixed size array
private /*static*/ void createcounters(int counternums, int digits,
int[] countervals){
...
counter[i] = new Counter(digits, countervals[i]);
}
public int[] getcounters(){
int[] countervals = null;
for (int i=0; i<counternums; i++){
countervals[i] = counter[i].ReturnVal;
}
return countervals;
}
}

java.lang.ArrayIndexOutOfBoundsException: 4 Error

I'm new to coding and I've been writing this code and trying to make it work but every time I run it it crashes. I've looked things up and will writing this code I've followed java's website on how to properly write down code as well as this site.
Anyways, it would be greatly appreciated if someone can explain to me why this is not working because it seems to me like the logic is there but I don't get why it crashes.
My code:
import java.util.Scanner;
import java.lang.String;
import java.util.*;
public class Question1
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
System.out.println("Enter either letters or numbers and I'll magically tell you if they are consecutive :D");
String inputedString= keyboard.nextLine();
boolean consecutiveOrNot=isConsecutive(inputedString);
System.out.println("Drum rolls...... Is it consecutive: "+ consecutiveOrNot); //Problem with this line?
}
public static boolean isConsecutive(String inputedString)
{
//Storing string's units into an array and converting to UpperCase if necessary
//and storing string's numerical value into the variable 'arrayCharToInt'
char[] charIntoArray= new char[inputedString.length()];
int[] arrayCharToInt= new int[inputedString.length()];
for (int i=0;i<inputedString.length();i++ )
{
charIntoArray[i]=inputedString.charAt(i);
if (Character.isLetter(charIntoArray[i]) && Character.isLowerCase(charIntoArray[i]))
{
charIntoArray[i]= Character.toUpperCase(charIntoArray[i]);
}
arrayCharToInt[i]=(int) charIntoArray[i];
}
// The next if statements and the methods that they call are used to verify
//that the content of the initial string is either letters or numbers, but not both together
boolean[] continuous= new boolean[arrayCharToInt.length];
boolean[] testContNumbersDecreasing= new boolean[arrayCharToInt.length];
boolean[] testContNumbersIncreasing= new boolean[arrayCharToInt.length];
boolean[] testContLettersDecreasing= new boolean[arrayCharToInt.length];
boolean[] testContLettersIncreasing= new boolean[arrayCharToInt.length];
Arrays.fill(continuous, true);
if (lowestValue(arrayCharToInt)>=65 && highestValue(arrayCharToInt)<= 90)
{
for (int x=0;x<arrayCharToInt.length ;x++ )
{
testContLettersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -25));
testContLettersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -25));
}
return (Arrays.equals(continuous,testContLettersIncreasing) || Arrays.equals(continuous,testContLettersDecreasing));
}
else if ((lowestValue(arrayCharToInt) >= 48) && (highestValue(arrayCharToInt)<= 57))
{
for (int x=0;x<arrayCharToInt.length ;x++ )
{
testContNumbersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -9));
testContNumbersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -9));
}
return (Arrays.equals(continuous,testContNumbersIncreasing) || Arrays.equals(continuous,testContNumbersDecreasing));
}
else
{
return false;
}
}
public static int lowestValue(int[] array)
{
int lowest=array[0];
for (int counter=0; counter< array.length; counter++)
{
if( lowest>array[counter])
lowest= array[counter];
}
return lowest;
}
public static int highestValue(int[] array)
{
int highest=array[0];
for (int counter=0; counter< array.length; counter++)
{
if( highest<array[counter])
highest= array[counter];
}
return highest;
}
}
The main method seems to be fine because it put everything in the isConsecutive method as a comment except for 'return true;' and indeed the program ran and printed true. So I know the problem lies somewhere in the second method.
If there's anything that I did not do right please tell me and that would be greatly appreciated. After all I'm still learning.
Thanks
All of your calls to arrayCharToInt[x+1] are going to go out of bounds on the last iteration of the loop they're in (for example, if arrayCharToInt.length equals 5, the highest that x is going to go is 4. But then x+1 equals 5, which is out of bounds for an array with five cells). You'll need to put in some sort of if( x == arrayCharToInt.length - 1) check.
in the method isConsecutive inside the for loop: for (int x=0;x<arrayCharToInt.length ;x++ ) , you have used arrayCharToInt[x+1]
if the arrayCharToInt lenth is 4 , then you have arrayCharToInt [0] to arrayCharToInt [3].
now consider this statement:arrayCharToInt[x+1]
when x is 3 this statement will evalueate to arrayCharToInt[4] resulting in array index out of bounds exception
This error throw when something went wrong in the Array calling function.
You got the length and make it print.
for eg:
int a[] = {1,2,3,4}
Length of this array is,
int length = a.length
So length = 4 but highest index is 3, not 4. That means index of the array started with 0. So you have to print:
arr[length-1];
In your program,
x == arrayCharToInt.length - 1

copy array in to another array using a for loop

following are the steps of the program I'm trying to make
catch String using Scanner
pass that String to a method in another class
separate characters of that String in to an array using .toCharArray()
copy contents of that array to another array using a for loop
but this array giving me a null pointer exception. what am i doing wrong? (ignore the class naming i know it's stupid but i have to do it this way because my teacher wants it that way)
main class:
import java.util.Scanner;
public class _01 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your name : ");
String name = input.nextLine();
int size = name.length();
_02 process = new _02(size);
process.push(name);
}
}
other class with the array:
public class _02 {
int maxsize;
int top;
char arrayStack[];
public _02(int size) {
maxsize = size;
top = -1;
}
public void push(String letters) {
char temp[]= letters.toCharArray();
for (int c=0;c<temp.length;c++) {
temp[c] = arrayStack[++top];
}
}
}
Your assignment is reversed - you want to assign from temp (right side of assignment) to arrayStack (left side of assignment). Also, you need to initialize arrayStack, e.g. arrayStack = new char[temp.length] - right now it's null.
char arrayStack[]; // this is not initialized.
arrayStack[] = new char[temp.length] // inside the push() method.
Arrays need to be initialized in Java; simply declaring an array yields a field initialized to null. Once you change the class to properly initialize arrayStack, you don't need the maxsize field, since it will be the same as arrayStack.length. You also have your assignment reversed in the push method. Finally, since you have a maximum array size, you might want to avoid throwing an ArrayIndexOutOfBoundsException and instead throw a more semantically meaningful exception, or else simply drop the extra characters or grow the stack (in which case the constructor arg is an initial size). For that, you will need some range checking. Finally, the logic is cleaner if you initialize top to 0 instead of -1 and use top++ instead of ++top (or, better, use the built-in API for copying pieces of an array).
public class _02 {
int top;
char arrayStack[];
public _02(int size) {
arrayStack = new char[size];
top = 0;
}
public void push(String letters) {
char temp[]= letters.toCharArray();
int len = temp.length;
// do some range checking
if (top + len >= arrayStack.length) {
// silently ignore the extra characters
len = arrayStack.length - top;
// an alternative would be to throw a "stack full" exception
// yet another alternative would be to grow the stack
}
// for (int c=0; c<len; c++) {
// arrayStack[top++] = temp[c];
// }
// don't use a loop--use the API!
System.arraycopy(temp, 0, arrayStack, top, len);
top += len;
}
}

Categories