Writing a non-static method as a static method - java

I'm trying to write this method as a static method but I don't fully understand how static methods work past them not creating objects to work with.
This is the method I'm trying to convert
public void process(String str)
{
for (int i=0; i<str.length(); i++){
char letter = str.charAt(i);
int index = Character.toLowerCase(letter-'a');
if (index>=0 && index<26){
counts[index]++;
}
}
}
This method just takes a string and records the number of times each letter showed up in the String
Im trying to write this as a static method and I have this method stub
public static LetterCounter buildCounter(String str)
{
}

Since this is a learning exercise, I wouldn't write any code, but describe what needs to be done:
Create a new instance of LetterCounter
Call an instance method process on it, passing str that you got in your buildCounter
Return the instance of LetterCounter that you created in step 1.
You are done!

Your current code would require that counts[] be declared as static also, meaning there is only one counts[], and every time you call MyClass.process("blah") it would increase the class variable counts[index]
I am guessing but I think what you are trying to do is create a static "utility' function to return an array of counts for the various charactors in the passed in string? So something similar to this (untested) code.
then you would call something like MyUtilClass.process("xxyz");
In this case "static" means that the process does is not associated with an object, it is more like a "function" or "subroutine"
public static int[] process(String str) {
int[] counts = new int[25];
for (int i=0; i<str.length(); i++){
char letter = str.charAt(i);
int index = Character.toLowerCase(letter-'a');
if (index>=0 && index<26){
counts[index]++;
}
}
return counts;
}

Related

How to call a static method from main class?

I got this code:
public static ArrayList<Integer> MakeSequence(int N){
ArrayList<Integer> x = new ArrayList<Integer>();
if (N<1) {
return x; // need a null display value?
}
else {
for (int j=N;j>=1;j--) {
for (int i=1;i<=j;i++) {
x.add(Integer.valueOf(j));
}
}
return x;
}
}
I am trying to call it from the main method just like this:
System.out.println(MakeSequence (int N));
but I get an error...
Any recommendations? Much appreciated, thanks!
System.out.println(MakeSequence (int N));
should be
int N = 5; // or whatever value you wish
System.out.println(MakeSequence (N));
Just pass a variable of the correct type. You don't say that it is an int again;
You define the method as follow MakeSequence (int N), this means that method expects one parameter, of type int, and it'll be called N when use inside the method.
So when you call the method, you need to pass an int like :
MakeSequence(5);
// or
int value = 5;
MakeSequence(value);
Then put all of this in a print or use the result in a variable
System.out.println(MakeSequence(5));
//or
List<Integer> res = MakeSequence(5);
System.out.println(res);
All of this code, to call the method, should be in antoher method, like the main one
Change x.add(Integer.valueOf(j)); to x.add(j); as j is already an int
to follow Java naming conventions : packages, attributes, variables, parameters, method have to start in lowerCase, while class, interface should start in UpperCase
The first issue is I think that N should be some int value not defining the variable in the method call. Like
int N = 20;
ClassName.MakeSequence(N);
The other issue you will face. As System.out.println() only prints string values and you are passing the ArrayList object to it, so use it like this System.out.println(ClassName.MakeSequence(N).toString())

Setting all values of a 2d array (java)

I am trying to fill a 7x6 blank 2d Array in java with a value of -1.
I initialized the array in a non-main class by typing:
int[][] anArray = new int[7][6];
Then I created a method setArray() which looks like the following:
public int[][] setArray()
{
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 6 ; j++)
{
anArray[i][j] = -1;
}
}
return anArray;
}
but when I run this method through the main class, it returns the board as:
[[I#71988d36
Does anyone know why this is happening? I'm fairly sure the above code is correct.
edit: Forgot a pair of curly braces.
Every class extending Object in Java (that is, all of them) inherits this method:
public String toString()
Which is called when you invoke to decide what to actually print
System.out.println()
The problem is, unless you override it, it will return something not very helpful which will get printed (except in a few cases such as String, int ....).
In this particular case, rather than overriding it, and as the comments above explain, it's easier to call a wrapper function that takes the array as a parameter and delivers a nice String as a result.

Adding numbers to arrays with methods in another class?

I am learning java and trying to figure out how to implement these methods into my main class from a second class. The program takes user input to add numbers into an array and then I need to print the following using the pre-specified methods below. The parameters in the below method is what confuses me.
public static double findMin(double[] numbers, int count) //count is the count of numbers stored in the array
public static double computePositiveSum(double[] numbers, int count)
public static int countNegative(double[] numbers, int count)
Basically, I am confused as to how I link all the variables and array between the two classes so they can recognize the parameters and return the correct value to output min, sum and number of negatives. Do I want the array in the main method?
Basically, what I did now to fix it was that I created the variables in the main method and then pass the variables in the main method through the parameters of the object I created that links to the secondary class. Does that seem ok?
If you already have the array , so what you need is call your methods and pass this value to it
lets say you have this array :
double[] num = {1.2,2.3};
and your count is the length of num array , so the count is:
int count = num.length;
then call your method and pass the parameters to it like this:
findMin(num , count );
computePositiveSum(num , count );
countNegative(num , count );
Note : you need to read in Object-Oriented Programming Concepts
Sorry guys for such a question. I just needed a refresher since it has been awhile. I resolved the issue by creating the array and count variable in the main method and then passed those through the parameters so the methods in the secondary class could read them. Thanks for the quick responses and help .
You don't need a count variable, you can use myarray.length
So your code should be something like this:
public static void main(string [] args)
{
double[] myarray = {5.3, 69.365, 125, 2.36};
double result = MyClass.findMin(myarray);
}
public class MyClass
{
public static double findMin(double[] numbers)
{
// your impl
}
public static double computePositiveSum(double[] numbers)
{
// your impl
}
public static int countNegative(double[] numbers)
{
// your impl
}
}
You can create an object reference of the main class in your derived class. Then call these methods using the object of your main class.
class Main
{
------
}
class derived
{
Main m = new Main();double[] A=new double[1];
Scanner s = new Scanner(System.in);
int i=0,wc=1;
int arrayGrowth=1;
while(s.hasNext())
{
if (A.length == wc) {
// expand list
A = Arrays.copyOf(A, A.length + arrayGrowth);
wc+=arrayGrowth;
}
A[i]=s.nextDouble();
i++;
}
int len=A.length-1;
m.findMin(A,len);
m.computePositiveSum(A,len);
m.countNegative(A,len);
}

unable to get this class working in java on client code - no compilation errors but runtime

I have pasted my code here. below the code I give descriptin of what I am trying to do
import java.util.*;
import java.io.*;
//given a string, gives letters counts etc
public class LetterDatabase{
private String word;
private int[] charCounts;
public static final int TOTAL_LETTERS=26;
//constructor
public LetterDatabase(String word) {
this.word=word;
int[] charCounts= new int[TOTAL_LETTERS];
//this function fillup charCounts with no of occurances
//more below
fillupcharArray();
}
/*Returns a count of letters.
public int get(char letter) {
return charCounts[Character.getNumericValue(letter)-10];
}
/*Sets the count for the given letter to the given value.
public void set(char letter,int value) {
int index=Character.getNumericValue(letter-'a');
charCounts[index]=value;
}
/* converts string to Array of chars containing only alphabets
private char[] convertToArray() {
String str = word.replaceAll("[^a-zA-Z]+", "");
char[] charArr=new char[str.length()];
for (int i = 0; i < str.length(); i++) {
charArr[i] = str.charAt(i);
}
return charArr;
}
private void fillupcharArray(){
char[] charArr=convertToArray();
for(int i=0;i<charArr.length;i++) {
for(int j=0;j<26;j++) {
if (Character.toLowerCase(charArr[i])==Character.toLowerCase((char)('a'+j))) {
charCounts[j]+=1;
}
}
}
}
}
my client code that I used to test is below
import java.util.*;
import java.io.*;
public class Testdatabase{
public static void main(String args[]) {
String str="my name is Dummy!!!:..,";
LetterDatabase first= new LetterInventory(str);
System.out.println(first.get('a'));
System.out.println(first.set('a'));
System.out.println(first.get('a'));
}
}
Explanation: I define a LetterDatabase class which computes the count of letters--only alphabets (type char) in given string. I have a get method, that returns the occurance of particular letter and a set method, that sets the value of letter to a set value.
in my constructor, I am calling a function that fills the array(charCounts), so that I can easily lookup for occurrence of a given char. Firstly my constructor does not work. my class code compiles and my client code above compiles. when I run the clientcode, commenting out the getter and setter calls, i get the following error.
Exception in thread "main" java.lang.NullPointerException
at LetterDatabase.fillupcharArray(LetterInventory.java:55)
at LetterDatabase.<init>(LetterInventory.java:17)
at Testdatabase.main(hw1test.java:7)
I am unable to figure what is going wrong. the fillupcharArray seems to work fine when I test it individually. I am not pasting that here.
secondly, the way I define get and set method in my class is not very good. it would be nice if I dont have to use Character.getNumericValue
I am open to hear on any other improvements. Thanks for your time
You are shadowing the array charCounts in the constructor of LetterDatabase. Replace
int[] charCounts = new int[TOTAL_LETTERS];
with
charCounts = new int[TOTAL_LETTERS];
Inside a class method, when a local variable has the same name as an instance variable, the local variable shadows the instance variable inside the method block. In this case the local variable charCounts is shadowing the instance variable charCounts.
From wikipedia
In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope
In your constructor, you've defined a local variable charCounts:
int[] charCounts= new int[TOTAL_LETTERS];
This shadows the instance variable charCounts, to which I think you meant to assign it.
Assign it to the instance variable charCounts like this:
charCounts = new int[TOTAL_LETTERS];
This means that, in your code, the instance variable charCounts remains null until you access and a NullPointerException results.

I want to return a the length of the string using 2 methods. Newbie in Java

I have errors when I run program(1). But when I used program(2), writing 0 after a, it run and produced the correct output. Writing 0, is just my guess and somehow it worked. Why is that?
Program (1):
public static void main(String[] args) {
System.out.println(a);
}
private static int a(int len) {
String s = "What";
len = s.length();
return (len);
}
}
Program (2):
public static void main(String[] args) {
System.out.println(a(0));
}
private static int a(int len) {
String s = "What";
len = s.length();
return (len);
}
}
You wrote the function in such a way that it requires a parameter. To call a function that requires a parameter, you have to supply one. That's why the second program worked--you gave the function a a parameter of 0.
To make the first program work, then, you have two options. The first is what you did--supply the required parameter for the function. The second is to modify the function declaration so it does not require a parameter, changing
private static int a(int len) {
to
private static int a() {
public static void main(String[] args) {
System.out.println(a);
}
private static int a(int len) {
String s = "What";
len = s.length();
return (len);
}
The problem here is that a is a function which receives a single integer parameter. This code is therefore a compilation error:
System.out.println(a);
You cannot print a function. What you can do is call a function and print that function's return value. Which is precisely what your second chunk of code does.
However, since your function a ignores its input parameter, you could re-write the code like this:
public static void main(String[] args) {
System.out.println(a());
}
private static int a() {
String s = "What";
int len = s.length();
return len;
}
Note that you still need to call the function using parentheses, a(). But because there is no longer a parameter required, you can leave the parameter list empty.
(Note: this really has nothing to do with the string length part. It's just simple method calling.)
Well look at this code:
public static void main(String[] args) {
System.out.println(a);
}
That's trying to use a as if it's a variable - it's not, it's a method. So you want to invoke that method, and use the return value, which is what you do in your second version.
Admittedly it's pretty odd to pass in an argument and then not use it, and likewise you've got unnecessary parentheses around your return value - return isn't a method call.
So your code can be simplified to:
public static void main(String[] args) {
System.out.println(a());
}
private static int a() {
return "What".length();
}
Or if you really want the local variable:
public static void main(String[] args) {
System.out.println(a());
}
private static int a() {
String s = "What";
return s.length();
}
You seem to be confusing method parameters with normal variable declarations. You've written a as a method that takes a single int parameter, so you need to pass it a value; but you don't actually use that value in the body of the function.
You probably really want to use a local variable, and not pass a parameter at all, e.g.:
public static void main(String[] args) {
System.out.println(a());
}
private static int a() {
String s = "What";
int len = s.length();
return (len);
Note that you still need to write a() in the call, not just a, to make clear that it is a method call.
The first code can't compile as you are trying to output a variable a that has not been declared (this syntax is not a method call). In the second one you are actually calling the static method a that exists, so it runs.
a is a function not a variable. You cannot call a function without the paranthesis...
you would have to type in a() to call the function.
Now, what happens in the first case is, since there are missing paranthesis it tries to resolve it as a variable and errors out.
The second case is where you call the function in the correct fashion
You need to read up on how to make method calls. This is one of the most basic things you will be doing in java.
When you want to call method a, you need to pass the correct number of arguments(in this case a single int) or the method call will not be recognized and be an error. What IDE are you using to develop your java code? If you are using something like Eclipse you shouldnt even be able to run the code with this error present.
Your function a is defined as a function that takes a single argument, which is named len. When you call it as a(0), you provide that argument and everything works just fine. When you call it as a, you do not provide that argument and compilation fails. The code never runs.
The question is: why have you defined a to take an argument? It isn't used: its value is immediately overwritten with the result of s.length().
It seems like you are attempting to declare a local variable for use by mentioning it in the function signature. That does is not necessary, and does not work, in Java.

Categories