Accessing scope of a variable once declared outside class - java

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.

Related

Experiment.java:18: error: illegal start of expression

import static java.lang.System.*;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class Experiment
{
private int periodCount = 0;
private String para = "";
public static void main( String args[] ) throws IOException
{
Scanner file = new Scanner(new File("example.dat"));
public int getNumberString()
{
String vowels = " ";
int count = 0;
String para = file("example.dat");
for(int index = 0; index < para.length(); index++)
{
if(vowels.indexOf(para.charAt(index)) >= 0)
{
count++;
}
return count;
}
}
//file.nextLine();
public int periodCounter()
{
int size = getNumberString();
for(int i = 0; i < size; i++)
{
if(para.charAt(i + 1) == '.')
periodCount++;
}
return periodCount;
}
public String Decider()
{
if(periodCount() <= 30)
return "Average";
if (periodCount() >= 30)
return "high";
}
System.out.println("This paragragh is a reading level" + Decider());
}
Hi! to be clear I was just messing around with this but now I want to see if it will work. The goal is to take count of the number of spaces in a paragraph on a dat file document and use that as a stopping point for a method to find the number of periods in a paragraph and determine the reading level from there.
I'm pretty new to java so this is just me throwing things around that I think will work
The issue is that it says both
my getNumberString and periodCounter functions are Experiment.java:18: error: illegal start of expression and that my print command is Experiment.java:45: error: <identifier> expected and Experiment.java:45: error: illegal start of type
additionally, if you find any thing you might want to comment on feel free to!!
Look where your { and } match up. You've defined getNumberString() inside the body of your main() method. You're probably missing a closing } after your Scanner declaration line (and some other code that calls your other methods.
"Experiment.java:18: error: illegal start of expression" is telling you that you can't start a method declaration at this location, this is not valid syntax.

Searching for a String in an Array and returning the position

Hi I'm a complete newbie on programming and I try to search for a certain String in an array. When it's found the method should return the index but if the String is not found it should return -1.
public int poitionOfWord(String testWord) {
for (int i = 0; i < wordArray.length; i++) {
if (wordArray[i].equals(testWord)) {
return i;
}
}
return -1;
}
would this method return always -1 or would it actually terminate when finding a word and would return i.
Your method is correct and it will return the index in case it finds a match else if it doesn't find the match, it will come out of loop and return -1.
Just to make code crisp and concise, you can use something like this,
public static String[] wordArray = new String[]{"a", "b"};
public static int poitionOfWord(String testWord) {
return Arrays.asList(wordArray).indexOf(testWord);
}
Then test it with some code,
public static void main(String args[]) {
System.out.println(poitionOfWord("a"));
System.out.println(poitionOfWord("z"));
}
This prints,
1
-1
In general, when your function reaches a return statement, it will terminate and return the given value.

Main seems to skip over one of my methods

Apologies for posting a bit of a foolish question, but I cant seem to understand why my method startEndCoords does not seem to run properly through my main method here:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class MazeSolver {
// The name of the file describing the maze
static String mazefile;
// set global variables
static int arrayHeight;
static int arrayWidth;
static int startRow;
static int startColumn;
static int endRow;
static int endColumn;
static int cellsize;
static int borderwidth;
static int sleeptime;
static char [][] maze;
public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args)) {
maze = readMazeFile(args[0]);
startEndCoords(maze);
if (solveMaze(startRow, startColumn))
System.out.println("Solved!");
else
System.out.println("Maze has no solution.");
}
}
// get starting & ending points
static boolean startEndCoords(char[][] mazeAsArray){
for (int r = 0; r < MazeSolver.arrayHeight; r++) {
for (int c = 0; c < MazeSolver.arrayWidth; c++) {
if (mazeAsArray[r][c] == 'S') {
MazeSolver.startRow = r;
System.out.println(startRow);
MazeSolver.startColumn = c;
System.out.println(startColumn);
}
if (mazeAsArray[r][c] == 'E') {
MazeSolver.endRow = r;
System.out.println(endRow);
MazeSolver.endColumn = c;
System.out.println(endColumn);
return true;
}
}
}
return false;
}
The print statements within the method will not execute, not sure what im missing.
Thanks for your help.
full code
It appears that your readMazeFile method is intended to set some of the global variables you declare, but it actually doesn't. It instead declares its own local variables that happen to have the same names, and sets those. This leaves MazeSolver.arrayHeight at its default value of 0, so of course the for loop instantly bails before even running once.
Remove the int from the lines in readMazeFile that set arrayHeight and arrayWidth. This will make it use and set the existing static variables instead of creating new local ones.

Variable not accessable

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.

Occurrences of a number in a string

I need to find the number of times that the number 1 occurs in a string such as "11100011"
so that I can then use the count to do some parity bit work. I was wondering if anyone could tell me what method or how to set up a loop to do such a thing.
public class message
{
private String parity1;
private int count;
public message(String Parity1)
{
parity1 = Parity1;
int count = 0;
}
public static int countOnes(String parity1, char 1)
{
count = 0;
for(int i = 0; i < parity1.length(); i++) {
if(parity1.charAt(i)==1){
count++;
}
}
return count;
}
//...
You have a problem with your comparison:
if(parity1.charAt(i)=='1'){//note the quotes; needed to interpret '1' as a char
count++;
}
Note this function signature is wrong:
public static int countOnes(String parity1, char 1)
and should be:
public static int countOnes(String parity1)
The second parameter isn't needed there. If you want to maybe pass in this parameter use:
public static int countOnes(String haystack, char needle)
And then your comparison becomes:
if(haystack.charAt(i)==needle){
Note, too, that count as declared in this method is wrong. You're trying to reference an object's member field from a static function. Static functions aren't associated with an object but with a class. Given that you don't need any member fields, you might as well just declare count within your countOnes function:
public static int countOnes(String parity1) {
int count = 0;
//...
}

Categories