im a bit confused on this and i dont know how to solve this question that i have been asked, id be grateful if you could assist me on this question, maybe try to tell me what needs to be done, and how. the question is:
Write a method called countChars which takes an InputStream as a parameter, reads the stream and returns the number of characters it contains as an int. Any IOExceptions which might occur in the method should be passed back to the method's caller.
Note that the method header should show that it is possible that an exception might occur.
i attempted this question with the following code:
public class countChars
{
public int countChars(int InputStream)
{
return InputStream;
}
}
and i get an error message saying :
Main.java:26: cannot find symbol
symbol : method countChars(java.io.InputStream)
location: class Main
s1 = "" + countChars(f1);
^
1 error
public class CounterUtility
{
public static Integer countChars(InputStream in)
{
Integer counter = 0;
/* your code here */
return counter;
}
}
s1 = CounterUtility.countChars(f1).toString();
You have a couple things mixed up. For one your function is going to take in an InputStream and return an int. You have your function set up to take in an int called InputStream and return an int.
InputStream has a function, read(), which loads the next character of the stream (or -1 if there are no remaining characters). You'll need to define an integer counter and then call read() as many times as it takes to get that response of -1. Once you see a -1 you know that you're at the end of the stream and you can return the counter (which will have a value equal to the number of characters).
//take in an InputStream object and return an int
public int countChars(InputStream input){
int counter = 0; //start counting at zero
while (input.read() != -1){
//as long as there are more characters, keep incrementing the counter
counter++; //add one to the counter
}
return counter; //return the result
}
I never attempted to compile the above code and I haven't written in Java since college, so there may be syntactical errors.
Your countChars method is inside of a class called countChars.
When you call the method, you need an instance of the class.
You need to make the method static, then change the call to countChars.countChars(f1).
The error is probably due to the fact that the countChars method was not successfully compiled. If you review the rest of the output of the compiler you'll probably see it complaining on the return statement. Replace the stub return, with return 0 and it should go through.
Besides, you should not use InputStream as variable name. Use is or something similar.
Furthermore, if the method should take an InputStream as argument, the signature should be
public int countChars(InputStream is) { ...
Seems like you may be compiling the wrong file. The code example you included does not contain the code from the error message. I therfore conclude that the compiler is not acting on the source file that you believe it is (assuming you have accurately copy/pasted the code you are using).
First things first: In Java, class names should always be capitalized.
Second, the code you are running is in the Main class. Your countChars method is in the countChars class. You need to create a countChars object to call it on, or make countChars a static method, which would be called via countChars.countChars(intHere).
Third, int InputStream would be an integer value with the name InputStream, not an InputStream object.
A few points. Generally it is considered good practice to Capitalize all Java Classes. You aren't forced to do so, but when you don't it makes readability much more difficult for the rest of the world.
So public class countChars becomes public class CountChars.
Second, you are attempting to call a method on an object, but you don't specify which object you want to use. Generally you can't use a method all by itself in object oriented programming, you must specify the class and then the method to call on the class. This is done one of two ways:
By creating an Object (instance of the class) and the calling the method on that Object, like so:
CountChars counter = new CountChars();
s1 = "" + counter.countChars(i);
By declaring the method to be static, which means it will be a method on the "Class" Object, CountChars. To call a static method, the class name is used, like so:
s1 = "" + CountChars.countChars(i);
Related
I am using code academy and I always get stuck when it comes to parameters. I watched their video but I didn't get it.Please help.
To begin with, it is parameter and not perimeter.
Let us take an example. We are defining a function which accepts a name as input and as an output, it returns a greeting message.
class GreetUser {
/*
A Simple function which accepts a username as input and returns me back with a Hello message
*/
public static String greet(String username) { // function declaration
return "Hello, " + username;
}
public static void main(String[] args) {
String greetingMessage = greet("Daniel"); // involing the function
System.out.println(greetingMessage);
}
}
The line: public static String greet(String username) is called function definition. What you pass in the brackets is/are called - parameters. It is basically some variables/data placeholders you define. In plain English it means - this a function does something and returns something, and what I defined in the brackets are the inputs of this function. The greet method here says, I am expecting an input of the type String. This is the parameter
There is another method in the program called main Once you understand point one, you can answer for yourself what is the type of parameter main function takes in .
There can be times when functions do no need an input, so you do not pass any parameter list to the function. Example:
public static void iDoNothing(){
}
You can see inside main() we are invoking or calling the greet function and passing some value to it since it expects one parameter. What you pass, it is technically called argument
So when you declare a function, in the brackets you give what input it expects and is called parameter
When you call the function, you pass values to the function and it is called argument
Please read more on this:
Java Tutorial
Difference between Parameter and Argument
Also, you should read the Guidelines of the forum about How to Ask a Good Question
Are you talking about parameters? Parameters are basically values or objects passed to the methods and manipulate in the methods. Sometimes methods return the values. Methods are always used when the same code is to be used again and again for different values - like if we have to calculate greater of two values -
public static int greaterThan(int a, int b) {
if(a > b)
return a;
else
return b;
}
a and b are only the name of the parameters, like we declare the variables and assign the values to the variables. And you can reuse the method more than one time -
greaterThan(3,5);
greaterThan(8,5);
And the results will be different -
5
8
I hope this explanation will help you to understand about the parameters.
Thanks
I've searched for similar posts on this matter and honestly there is a lot, but please understand that I don't. I would appreciate it if someone could explain a little better, simpler.
I am trying to write my first program. The first part of the program is to reverse the number that is entered by the user, and I don't have a problem with this. The problem is when I try to get the that reversed number into another class
Here is the code:
package secretIDpack;
import java.util.Scanner;
public class renNum {
int reverse = 0;
int storeNumber;
public int revMethod(){
Scanner in = new Scanner(System.in);
storeNumber = in.nextInt();
while(storeNumber != 0) {
reverse = reverse * 10;
reverse = reverse + storeNumber%10;
storeNumber = storeNumber/10;
} return reverse;
System.out.println(reverse);
}
}
The System.out.println part is just so I can confirm that the above code is working properly, which it is as long as I keep the return part out of the code. As soon as I put the return part in, I get the message that there is unreachable code at the System.out.println
Now you probably already see what is being done here, but I will make sure you understand. I need the value of the reversed number in another class where it will be worked on further like adding some value multiplying etc. So let's say the number entered is 1234 and when revMethod does its part it will be 4321, I need this number in this class
package secretIDpack;
public class NewSecretID {
public static void main(String[] args){
renNum revObject = new renNum();
revObject.revMethod();
System.out.println(reverse);
}
}
Now in this class I get an error that "reverse" cannot be resolved to a variable, why isn't this class pulling the "reverse" value from the previous class?
As for your first question, you have a return statement followed by a print statement. In this case, the problem is that when the return keyword is found, the execution flow will exit that method. Thus, anything which follows will never executed.
To fix this, you would simply need to invert the order of your return and print statement such that the printing will take place before returning.
As per your second question, the reverse string does not exist within your main method. It exists in some other method which you are calling, but it is never declared in your NewSecretID class, which is why you are getting that error.
Variables declared within methods are not available outside the declaring method. Same applies for class lever variables, since they are not available outside that class. Just to be clear, you can access them, just not in the way you are doing it.
To solve your second issue, just do int reverse = revObject.revMethod(). This would place whatever it is that revMethod gives back into an integer variable called reverse. For the sake of completeness you can rename reverse to anything you like. int foo = revObject.revMethod() would also work.
First part of your question:
The return statement will exit the method! That means that code after the return statement will not be executed and is therefore "unreachable". Just switch those two lines:
System.out.println(reverse);
return reverse;
Second part of your question:
The revMethod has a return value of int. To use the return value of the method you'll have to assign it to a variable in the calling method. e.g.:
int returnValue = revObject.revMethod();
System.out.println(returnValue);
I'm working on an assignment right now, and am confused by this. The code given is simple:
public class Variables{
public static void main(String[ ] args){
StringBuffer b = "ghi";
f(b);
System.out.println(b):
}
public static void f(StringBuffer p){
p.concat("jkl");
}
}
The question simply asks what the output of the print statement will be. My first thought was simply "ghi", but this was incorrect. If the method f is taking b as a parameter and setting it to p, then how does .concat() modify b? I've read through the StringBuffer documentation and dont understand why this wouldn't end up with b equaling "ghi" while p is "ghijkl".
Basically, how is the .concat() method called on p also modifying b?
First, you need to create a StringBuffer correctly.
StringBuffer foo = new StringBuffer("some string");
You passed an object to a function. Java passes objects as references (the references themselves of course are passed by value). See: Is Java "pass-by-reference" or "pass-by-value"?
Since you have a reference to a StringBuffer and not a copy of it, you are actually modifying the same object as you would as if you were in main.
This is the difference between parsing by reference and parsing by value.
When you create a method taking a primitive, for example, it undergoes what is called parsing by value. The JVM pretty much creates a copy of the value and that is what you get in the method.
int j = 0;
foo(k);
System.out.println(j); //Will still be 0.
public static void foo(int i) {
//i is not j (what you called the method with), it is a copy of it that is only valid within this method
i++;
}
Now when you call the method with an object such as a StringBuffer you are parsing by reference. This means that you are not parsing the value of the StringBuffer(not parsing a StringBuffer` with "ghi" as its contents), but you are rather parsing a pointer to it. Using this pointer you can still operate on the original object within other methods and bodies of code.
I have question about one method of InputStream class, because it doesn't seem to me it could ever work.
Let we have something like this:
InputStream is;
byte[] b = new byte[64];
is.read(b);
// and now the byte array b contains data comming through InputStream???
I would understand if usage of the .read() method would look something like this:
b = is.read();
Because the read method would be returning byte array.
But how can the real method write something to its argument and make it visible outside of itself?
It's like I would have this:
String myString = "myText";
public void myMethod(String s) {
s = "abc123";
}
myMethod(myString);
// and now is the content of myString equal to "abc123" instead of "myText" ???
// ANSWER: no!
Thanks for your replies.
Everything except primitives types are objects in java(including array). The objects are passed by copy of reference from one method to another. So if the called method makes changes to the object passed to it, method is eventually making changes to the same object which was passed to it. Hence, changes are reflected to the calling method as well.
You need to learn about objects and how are they passed between method calls to understand this in detail. Please refer this link for better understanding.
Because the read method would be returning byte array.
Eh? Where did you read that? InputStream's .read() method returns an integer.
how can the real method write something to its argument and make it visible outside of itself?
Because you pass in a reference to an array where the .read(byte[]) will write. And the return value of this method is the number of bytes actually written to the byte array passed as an argument.
This code works:
public void writeOneToFirstElement(final int[] array)
{
array[0] = 1;
}
final int[] foo = { 0 };
writeOneToFirstElement(foo);
System.out.println(foo[0]); // prints 1
THe Array is just a reference to the object and cause the adress where the data resides doesnt change on modifications it can work that way
Explained here:
http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html
Edit: Typo
byte array as well as String are reference types..When you pass them as argument there reference are copied and they all refer to the same object..
For example, a remote is like a reference to a TV.When you pass the remote to another person,he's still able to access the TV
The objects are passed by copy of reference from one method to another. So if the called method makes changes to the object passed to it, method is eventually making changes to the same object which was passed to it. Hence, changes are reflected to the calling method as well. For example replace the String in the parameter with String[] and check the output.
public static void main(String[] args)
{
String[] myString = {"myText"};
myMethod(myString);
System.out.println(myString[0]);
}
public void myMethod(String[] s) {
s[0] = "abc123";
}
I have a recursive algorithm which steps through a string, character by character, and parses it to create a tree-like structure. I want to be able to keep track of the character index the parser is currently at (for error messages as much as anything else) but am not keen on implementing something like a tuple to handle multiple returned types.
I tried using an Integer type, declared outside the method and passed into the recursive method, but because it's final, recursive call increments are "forgotten" when I return. (Because the increment of the Integer value makes the passed-by-value object reference point at a new object)
Is there a way to get something similar to work which won't pollute my code?
Since you've already discovered the pseudo-mutable integer "hack," how about this option:
Does it make sense for you to make a separate Parser class? If you do this, you can store the current state in a member variable. You probably need to think about how you're going to handle any thread safety issues, and it might be overkill for this particular application, but it might work for you.
It's kind of a hack, but sometimes I use an AtomicInteger, which is mutable, to do things like this. I've also seen cases where an int[] of size 1 is passed in.
The current solution I am using is:
int[] counter = {0};
and then pass it to the recursive algorithm:
public List<Thing> doIt (String aString, int[] counter) { ... }
and when I want to increment it:
counter[0]++;
Not super elegant, but it works...
Integers are immutable, which means that when you pass it as an argument it creates a copy rather than a reference to the same item. (explanation).
To get the behavior you're looking for, you can write your own class which is like Integer only mutable. Then, just pass it to the recursive function, it is incremented within the recursion, and when you access it again after the recursion is over it will still maintain its new values.
Edit: Note that using an int[] array is a variation on this method... In Java, arrays are also passed by reference rather than copied like primitives or immutable classes.
You could just use a static int class variable that gets incremented each time your doIt method is called.
You could also do:
private int recurse (int i) {
if (someConditionkeepOnGoing) {
i = recurse(i+1);
}
return i;
}
To be honest I would recode the function to make it a linear algorithm that uses a loop. This way you have no chance of running out of heap space if you are stepping through an extremely large string. Also, you would not need to have a the extra parameter just to keep track of the count.
This also would probably have the result of making the algorithm faster because it does not need to make a function call for every character.
Unless of course there is a specific reason it needs to be recursive.
One possibility I can think of is to store the count in a member variable of the class. This of course assumes that the public doIt method is only called by a single thread.
Another option is to refactor the public method to call a private helper method. The private method takes the list as a parameter and returns the count. For example:
public List<Thing> doIt(String aString) {
List<Thing> list = new ArrayList<Thing>();
int count = doItHelper(aString, list, 0);
// ...
return list;
}
private int doItHelper(String aString, List<Thing> list, int count) {
// ...
// do something that updates count
count = doItHelper(aString, list, count);
// ...
return count;
}
This assumes that you can do the error handling in the public doIt method, since the count variable isn't actually passed back to the caller. If you need to do that, you could of course throw an exception:
public List<Thing> doIt(String aString) throws SomeCustomException {
List<Thing> list = new ArrayList<Thing>();
int count = doItHelper(aString, list, 0);
// ...
if (someErrorOccurred) {
throw new SomeCustomException("Error occurred at chracter index " + count, count);
}
return list;
}
It's difficult to know whether that will help without knowing more about how your algorithm actually works.