Is this program recursive? If not, how do I make it recursive? - java

For my programming class, I was told to make a program that uses recursion. I was confused and went to see my friend who was already in the class and he showed me this program. I thought recursion had to use things like r1(x-1), etc. Is it actually recursive? If it's not, how do you make it recursive?
import java.util.*;
import java.io.*;
class ReverseFile
{
private static Scanner infile;
public static void main(String[] args) throws IOException
{
infile= new Scanner(new File("hw_1.txt"));
r1();
}
public static void r1()
{
String s;
if (infile.hasNextLine())
{
s = infile.nextLine();
r1();
System.out.println(s);
}
}
}

It is recursive as r1 calls itself. The fact that no arguments are passed to r1 doesn't matter.

Related

How do i make a static reference to a non-static method?

import java.util.Iterator;
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
ArrayList<String> original = new ArrayList<>(Arrays.asList("afd", "asdf", "aavdd", "sajf", "adnf", "afd", "fjfn"));
String find = "afd";
String replaceWith = "asd";
System.out.println(replaceIt(original, find, replaceWith));
}
public ArrayList<String> replaceIt(ArrayList<String> original, String find, String replaceWith){
ArrayList<String> newList = new ArrayList<String>();
for(int y = 0; y<original.size(); i++){
if(!original.get(y).equals(find))
newList.set(y, original.get(y));
newList.set(y, replaceWith);
}
original = newList;
return original;
}
}
How do i call the replaceIt method? I'm confused and I need to make it so it prints the output of that function. I'm so confused somebody please help.
public ArrayList<String> replaceIt() is an instance method, it is only called from Main instances/objects.
public static void main is a static method of class Main, static methods can’t access instance methods and instance variables directly.
Therefor, to call replaceIt() method from static main method, make replaceIt() static.
public static ArrayList<String> replaceIt(/*arguments*/){
//your code goes here
}
Having non-static method in Main is a little odd. It's not like you are going to construct new instances of Main (say, the same way you would construct new instances of a Person class).
These type of generic helpers/utils functions usually go into some sort Utils.java or Helpers.java class, and are declared as static in these files. This way you would be able to invoke: Utils.replaceIt(original, find, replaceWith));
Because replaceIt() is an instance method, you simply need to create an instance of the Main class to call it -
public static void main(String[] args) {
...
Main m = new Main();
System.out.println(m.replaceIt(original, find, replaceWith));
}

class constants and file imports for java

I'm pretty much trying to use a class constant to declare as a file but get an error.
import java.awt.*;
import java.util.*;
import java.io.*;
public class BabyNames {
public static final Scanner NAME=new Scanner(new File("names.txt")); //specifically this part
public static final int YEAR=1900; //generates the error
public static final int LS=11;
public static final int WIDTH=50;
public static void main(String[] args) throws FileNotFoundException{
intro();
personName();
graph();
}
// Error contained:
// BabyNames.java:6: error: unreported exception FileNotFoundException; must be caught or
// declared to be thrown
// public static final Scanner NAME=new Scanner(new File("names.txt"));
^
//1 error
this is not all of the program but dont think the rest is required.
sorry if my method of asking was funky, first time. thanks much.
Technically you can use a static initializer block to set your staic final Scanner variable. Inside the initializer block you can use try/catch:
public static final Scanner NAME;
static {
// Be sure scanner is initialized even in the case of an exception
Scanner scanner = null;
try {
new Scanner(new File("names.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
NAME = scanner;
}
BUT: It is bad style to hold an instance of a class like Scanner as a static constant. A Scanner is a one way object. You are about to consume the file content and that's it. It doesn't make sense to hold such an object as a constant and much less if it is public.
A static variable will be intialized as soon as the class is loaded and lives as long as your program. In most cases this is not what you want.
A better approach would be to make it an instance variable and initilize it in the constructor. And make it private to the class. You can hold the file name as a constant and create the constructor to accept any file name. The methods intro(), personName() and graph() can be made instance methods, too.
public class BabyNames {
public static final String NAMES_FILE_NAME = "names.txt";
public static final int YEAR=1900;
public static final int LS=11;
public static final int WIDTH=50;
private final Scanner name;
public BabyNames(String fileName) throws FileNotFoundException {
name = new Scanner(new File(fileName));
}
public static void main(String[] args) throws FileNotFoundException {
BabyNames babyNames = new BabyNames(NAMES_FILE_NAME);
babyNames.intro();
babyNames.personName();
babyNames.graph();
}
public void graph() {
// ...
}
public void personName() {
// ...
}
public void intro() {
// ...
}
// ...
}
As a consequence the Scanner variable is only known to the BabyNames class and lives as long as the particular BabyNames instance. This is more modular, better to maintain and easier to test. E.g. you can write a unit test and initialize your class with a test file.
You need a try catch around that code.
That's what "must be caught or declared to be thrown" means.
Read this : doc oracle
There are two types of Exception :
1) checked Exception: those should be handle at compile time (by using try,catch,throws)
2) unchecked Exception: No compiler error for these exception but at run time exception may occurs.
Your case is first one FileNotFoundException is checked exception so either you have to write that line inside try catch block or you have to use keyword throws. to pass exception handling to calling method.

Java 1.6: Public variable won't work

I'm very new to java (about 1 week), and i'm stuck on a bit of code. I've looked everywhere, but nothing works. I'm trying to send a string from a MainProgram class to a FileWriter class.
MainProgram:
import java.util.*;
public class MainProgram {
public static void main(String[] args){
static answer;
Scanner Input = new Scanner(System.in);
System.out.println("Enter something so I can write it to a file");
String answer = Input.nextLine();
System.out.print("You said ");
System.out.print(answer);
}
}
FileWriter:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class FileWriter{
public static void SaveList() throws FileNotFoundException{
PrintWriter writer = new PrintWriter("OMGIMAFILELOLZ.txt");
writer.println(answer);
writer.close();
}
}
No matter what I do, I can't pass the answer string onto the FIleWriter class. Please help!
BTW Please don't make the answer too complex. I just came from QBASIC, and i'm only 12, so keep it simple please!
In this line static answer; you have not mentioned the
data type of answer.
main is already a static block,so you can not declare static
variables inside main method
declare answer in the class level like this public static String
answer;
class level syntax
public class MainProgram {
public static String answer;//class level declaration
public static void main(String args[])
{
//some codes
}
static answer;
First of all data type is missing for that.
And you cannot declare fields in methods.
That should be
static String answer;
public static void main(String[] args) {
// answer = Input.nextLine();
Then in FileWriter class,
writer.println(MainProgram.answer);

Can't Get Program to Compile

Pretty new to Java programming, but I'm having trouble getting this to run. I want to read in a word using the StringBuffer class, then reverse it. I am fairly unfamiliar with importing Java libraries, so I'm not sure if I did that correctly. Either way, this is what I have. I tried to compile it (I'm working in the Terminal), but got a few compiler errors. Any help would be appreciated.
import java.util;
import java.io;
public class HW1A {
public static void main (String[] args) {
printBackwards();
}
public static void printBackwards (String[] args) {
StringBuffer backwards = new StringBuffer(args);
System.out.println(backwards.reverse());
}
}
I get the following complier errors:
HW1A.java:1: cannot find symbol
symbol : class util
location: package java
import java.util;
^
HW1A.java:2: cannot find symbol
symbol : class io
location: package java
import java.io;
Thanks.
Since this is a learning exercise have a look at printBackwards, and ask yourself:
What parameters does it need and what are you passing?
Then look at this and what StringBuffer needs - do these match?
Two corrections:
import java.io.*;
To import everything in java.io.
And:
printBackwards(args);
To pass args to your printBackwards method (you declared it correctly, but didn't pass the variable).
The method printBackwards takes a String[] as an argument, but you're not passing anything when you call it.
This compiles :
public class HW1A {
public static void main (String[] args) {
printBackwards(args);
}
public static void printBackwards (String[] args) {
StringBuffer backwards = new StringBuffer(args[0]);
System.out.println(backwards.reverse());
}
}
But you have to decide if the argument to pass to create the StringBuffer is the first element of the args array.
No compilation error... but not sure this is what you want to do...
public class HW1A {
public static void main (String[] args) {
printBackwards(args);
}
public static void printBackwards (String[] args) {
StringBuffer backwards = new StringBuffer();
for (int i = 0; i < args.length; i++) {
backwards.append(args[i]);
}
System.out.println(backwards.reverse());
}
}
Parameters: Hello world!
Output: !dlrowolleH

Can we overload the main() method in Java?

The following code simply prints the word "hi" when run.
import java.util.*;
import java.io.*;
class poly
{
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
public static void main(String args[]) throws Exception
{
System.out.println("hi");
}
}
Is there a way to overload the main() method?
Your program only starts at one location, so that makes no sense. Furthermore, polymorphism is a totally different concept; that's called overloading, not polymorphism.
What you are trying to do is overloading the main method, not making it polymorphic. And no, you can't do it (or to be precise: overload you can, just the JVM won't call the overloaded versions). The JVM is looking for a main method with a specific signature, namely taking a String[] parameter.
Maybe if you tell us more about the actual problem you are trying to solve, we can offer alternative solutions.
The code is correct, you've overloaded the main method. But, as Peter mentioned, the main thread of an application will always start at the method with the signature
public static void main(String[] args)
and nothing else. For starting an application, JVM will ignore all other main methods. To execute the content, you'll have to call it in your code, like so:
public static void main(String args[]) {
main("me");
}
(Should print "this is me" to the console)
In brief you can overload a main function like:
class A
{
public static void main(String s) {
System.out.println(s);
}
public static void main(int s) {
System.out.println(s);
}
public static void main(String args[])
{
System.out.println("inside main entry");
main("me");
}
}
Output:
inside main entry
me
We can have any number of main method and that can be overloaded but the main thread of an application will always start at the method with the signature:
public static void main(String[] args)
and nothing else.
In Java args contains the supplied command-line arguments as an array of String objects.
You can overload a main method in Java; however, getting the classloader to start from the overloaded main method is going to be quite a trick.
The class you pass the the java executable is inspected, it's static methods are read, and control is passed off to only the one that looks like
public static void main(String[] args) { ... }
Since this is a static method, and Java does not have the concept of inheriting static methods, you have no way to overload this method. Since Java does not have the concept of inheritance of static methods, sub-classing the static bits of a class is a nonsensical idea.
Maybe you want something like this?
import java.util.*;
import java.io.*;
class poly {
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
public static void main(String args[])throws Exception
{
if (args.length == 1) {
poly.main(args[0]);
}
else {
System.out.println("hi");
}
}
}
The java runtime environment only looks for the exact match to public static void main(String[]), which is defined as the entry-point for standalone java applications.
To simulate the behaviour you want you have to call the other main yourself:
/**
* Your method called main, ignored by the java runtime since
* it does not match the signature. Called by the valid main(String[])
**/
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
/**
* Starting point of your program, called by the java runtime.
*/
public static void main(String args[])throws Exception
{
if(args.length >= 1){
main(args[0]);
}else{
System.out.println("hi");
}
}
As others point out having several methods with the same name but different parameters is called over*loading* and not polymorphism (over*writing*).
I'm not quite sure what you are asking but I don`t see any reason why you cannot overload the main method.
The "main method I think you are referring to is
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
To overload this method I would create a method such as
public static void main(){}
This must be in the same class as the other main method to make it overloaded.
The static keyword means common to the class.....(there is no need to use an object to access the method from the main(String[] args) method.
In my ind creating an overloaded method in a class is the same as creating a different method.
Different arguments, parameter list ====> different signature ======> different method.
I hope this helps.

Categories

Resources