• 0

Java Assignment Challange Question


Question

Hi everyone, I have this "Challange Question" with my Java assignment, can anyone please tell me how to do it?

Note: This is should be a simple Command Line program, made up of only one class and compiled using javac.exe, run by java.exe from J2SDK

  Assignment Question said:
Write a program that prints out its own source code to the standard output. The printed version must be an exact duplicate of the original source code (in other words, if you saved the output into a file with the correct name, you could compile and run it exactly the same as original - and it would in turn produce the exact same output as the original).

It seems pretty hard to me :pinch:

Can anyone with some Java programming experience tell me how please!

Thanks in advanced!!

Link to comment
https://www.neowin.net/forum/topic/65653-java-assignment-challange-question/
Share on other sites

20 answers to this question

Recommended Posts

  • 0

Do you have to do it with access to the original .java source file, or without it?

If you have the .java file, just open it, and output the content to the screen...

[Edit]Forget the text bellow, it doesn't give you the most important, the methods code...[/Edit]

  Quote
Start with the java.lang.Class class (http://java.sun.com/j2se/1.4/docs/api/java...lang/Class.html).

Get the needed one by doing this.getClass() (http://java.sun.com/j2se/1.4/docs/api/java...html#getClass()).

Then use the java.lang.reflect API (http://java.sun.com/j2se/1.4/docs/api/java...ge-summary.html).

Edited by Germano
  • 0

To read a file, use a BufferedReader (http://java.sun.com/j2se/1.4/docs/api/java...eredReader.html)

BufferedReader buffer = new BufferedReader(new InputStreamReader(new FileInputStream(the_file)));

the_file should be the class name (maybe get it with the above this.getClass()) plus ".java".

This is an important link: http://java.sun.com/j2se/1.4/docs/api/index.html

  • 0

Oh, it have the following hints:

  hint said:
The Unicode value for the double quotes is 34 (decimal). You can print out the

double quote character using (char)34 or '\u0022'. Your program will need to use

variables, and you are likely to find the information about double quotes very useful.

You will also have to use the String class, and in particular the substring method. This

program can be written using only a few statements.

By the way... this is Computer Science 101, and it's Assignmnet 1...

  • 0

Wow, sure seems like a lot for the first assignment in a low level course....but I suppose you've been talking over the concepts for weeks?

Yeah, and it really does only need a few statements. A read statement for the source file. An output statement (either screen or output file). And then closing those files. And any other output you want.

Example of Output:
PrintWriter fw = new PrintWriter(new FileWriter("C:\\testing.txt"));
fw.println("Hello world");
fw.close()

Example of Input:
BufferedReader input = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = input.readLine();
while (input.ready()) {
    System.out.println(line);
 ? ?line = input.readLine();
}
input.close()

Edited by kjordan2001
  • 0

Hi, thanks for the help,

I tried the following

import java.io.*;

public class printsource{

	public static void main(String[] args){

  BufferedReader input = new BufferedReader(new FileReader("printsource.java"));

  String line = input.readLine();

  while (input.ready()) {

     System.out.println(line);
     line = input.readLine();

  }

  input.close();


	}

}

but I get errors like "unreported exception java.io.IOException; must be caught or declared to be thrown" when compiling, canyou tell me what's wrong please?

  • 0

Well, there's a couple ways to handle that....

Put:

public void myMethod() throws IOException {

or

try {

line = input.readLine();

}

catch (IOException e) {

System.out.println("Invalid");

}

For something like this where you have multiple lines where you're getting input, I like throws IOException, but sometimes when an error comes up, you're expected to do something about it. That's where the try catch stuff comes in.

But if you're calling a method that throws an IOException, where you call it needs a try catch.

Ex from Sun's Java Tutorial:

import java.io.*;

public class Copy {
 ? ?public static void main(String[] args) throws IOException {
	File inputFile = new File("farrago.txt");
	File outputFile = new File("outagain.txt");

 ? ? ? ?FileReader in = new FileReader(inputFile);
 ? ? ? ?FileWriter out = new FileWriter(outputFile);
 ? ? ? ?int c;

 ? ? ? ?while ((c = in.read()) != -1)
 ? ? ? ? ? out.write(c);

 ? ? ? ?in.close();
 ? ? ? ?out.close();
 ? ?}
}

That incorporates both input and output. You need IOException handling of some sort with both input and output. The throws IOException handles any errors you might get. And since this is main, Java will handle the errors by printing out a long message since Java calls main.

More on IO http://java.sun.com/docs/books/tutorial/es...l/io/index.html

Edited by kjordan2001
  • 0

import java.io.*;

public class ReadSource {
    public static void main(String[] arguments) {
        try {
            FileReader file = new
                FileReader("ReadSource.java");
            BufferedReader buff = new
                BufferedReader(file);
            boolean eof = false;
            while (!eof) {
                String line = buff.readLine();
                if (line == null)
                   eof = true;
                else
                    System.out.println(line);
            }
            buff.close();
        } catch (IOException e) {
            System.out.println("Error + e.toString());
        }
    }
}

here you go. it works for sure . at least it did for me. this is the code but whether u wanna learn and udnerstand it is up to u :)

  • 0

import java.io.*;

public class ReadSource {
 ? public static void main(String[] arguments) {
 ? ? ? try {
 ? ? ? ? ? BufferedReader buff = new BufferedReader(new FileReader("ReadSource.java"));
 ? ? ? ? ? for(String line = buff.readLine(); line != null; line = buff.readLine())
 ? ? ? ? ? ? ? System.out.println(line);
 ? ? ? ? ? buff.close();
 ? ? ? } catch (IOException e) {
 ? ? ? ? ? System.out.println("Error + e.toString());
 ? ? :p }
 ? }
}

:p Less lines.

  • 0
  kjordan2001 said:
  Germano said:
Well, don't help him too much, he must learn...

Exception handling is something he must understand by himself what it is, and for what it is for.

Just my opinion...

Just showing him stuff he could easily find on the java tutorial.

Yes, you're right. I didn't notice the java tutorial link.

My experience indicates that absentee of documentation reading is the most common newbie problem. So I tend to always give links.

Also, programmers must learn to search by themselves solutions and examples in the internet. Google is one of the most powerful tools of a developer.

  • 0
  Germano said:
  kjordan2001 said:
  Germano said:
Well, don't help him too much, he must learn...

Exception handling is something he must understand by himself what it is, and for what it is for.

Just my opinion...

Just showing him stuff he could easily find on the java tutorial.

Yes, you're right. I didn't notice the java tutorial link.

My experience indicates that absentee of documentation reading is the most common newbie problem. So I tend to always give links.

Also, programmers must learn to search by themselves solutions and examples in the internet. Google is one of the most powerful tools of a developer.

Yeah, and Sun's tutorial and the API are a Java programmer's best friends, get to know them well if you're using java.

  • 0
  Quote
Write a program that prints out its own source code to the standard output. The printed version must be an exact duplicate of the original source code (in other words, if you saved the output into a file with the correct name, you could compile and run it exactly the same as original - and it would in turn produce the exact same output as the original).

The Unicode value for the double quotes is 34 (decimal). You can print out the double quote character using (char)34 or '\u0022'. Your program will need to use variables, and you are likely to find the information about double quotes very useful. You will also have to use the String class, and in particular the substring method. This program can be written using only a few statements.

I think the source .java file isn't available. Notice "if you saved the output into a file with the correct name"... Doing that wouldn't be possible, with the .java on the path.

Being this the first assignment, I suppose the output is to be "hard coded"...

A String variable would contain the class code... Some double quotes would be necessary (why not use \" ?).

The problem would be that we would never stop from rewriting the source code, one inside the other, inside the other, inside the other?

This is called a Self Generating Program (or Self Reproducing Program).

The solution will have to use substrings? Well, looks like this way we accomplish all the assignment requiremen:). :)

Now, should we give him the source code?

Edited by Germano
  • 0
  Germano said:
  Quote
Write a program that prints out its own source code to the standard output. The printed version must be an exact duplicate of the original source code (in other words, if you saved the output into a file with the correct name, you could compile and run it exactly the same as original - and it would in turn produce the exact same output as the original).

The Unicode value for the double quotes is 34 (decimal). You can print out the double quote character using (char)34 or '\u0022'. Your program will need to use variables, and you are likely to find the information about double quotes very useful. You will also have to use the String class, and in particular the substring method. This program can be written using only a few statements.

I think the source .java file isn't available. Notice "if you saved the output into a file with the correct name"... Doing that wouldn't be possible, with the .java on the path.

Being this the first assignment, I suppose the output is to be "hard coded"...

A String variable would contain the class code... Some double quotes would be necessary (why not use \" ?).

The problem would be that we would never stop from rewriting the source code, one inside the other, inside the other, inside the other?

This is called a Self Generating Program (or Self Reproducing Program).

The solution will have to use substrings?Well, looks like this way we accomplish all the assignment requirements. :)

Now, should we give him the source code?

yeah, I think printing out the source file is not what they really wanted... been trying to figure out how to do it other ways...

  • 0

Hey, I got it!

public class Ass01Optional{

	public static void main(String args[]){

	String a="public class Ass01Optional{public static void main(String args[]){String a=;System.out.println(a.substring(0,56)+((char)34)+a+((char)34)+a.substring(56));}}";

	System.out.println(a.substring(0,75)+((char)34)+a+((char)34)+a.substring(75));

	}
}

well, just gotta get the numbers right :cool:

Edited by alanp
  • 0

Hmm, now I'm just confused on what your assignment was....I figured it was read in your .java file and do something with it, but seems like you're just hard coding the stuff into a string. Well, at least that's easier if that's what the program is supposed to do.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Adobe releases all-new Photoshop app for Android devices by Pradeep Viswanathan Early this year, Adobe released an all-new Photoshop app for iOS devices. Designed from the ground up for smartphones, the app allows users to easily add, remove, adjust, and combine content, as well as access free Adobe Stock assets to create new visuals. Today, Adobe announced a similar, brand-new Photoshop app for Android devices, currently in beta. It’s important to note that this Android version is not intended to replace the desktop version of Photoshop. Instead, it offers access to select powerful Photoshop features—including layering, masking, and the new Generative Fill—within an easy-to-use mobile interface. During the beta phase, the following features are available to all users: Following the beta phase, users will need a new Photoshop Mobile & Web plan to access the premium features. The premium features list includes the ability to remove objects by brushing over them with the Remove Tool, the ability to use Clone Stamp to hide unwanted objects by cloning areas of an image, the ability to fill portions of an image with content sampled from other parts of the image with Content-Aware Fill, the ability to export using additional file formats (PSD, TIF, JPG, PNG), and more. You can download the Adobe Photoshop app from the Google Play Store if your device is running Android 11 or later and has at least 6GB of RAM (8GB or more is recommended for optimal performance).
    • And what about all the toxic waste that "clean" nuclear energy produces?
    • Plasma is beautiful, but my workload is unlikely to ever run on linux ... Cubase 14 with 5 or 6 dozen instances of Kontakt 8. Sigh.
    • Hey everyone! Just curious what your favorite browser is and why? Personally, I prefer using Chrome because it is simple and smooth to use. Would love to hear what everyone else is using and if there's something better I should try!
    • I'm Sam, 20, currently studying IT and passionate about all things tech and music. I found Neowin while browsing for community forums, and I’m excited to be here, connect with others, and maybe even learn something new along the way. Looking forward to chatting with you all!
  • Recent Achievements

    • Conversation Starter
      DarkShrunken earned a badge
      Conversation Starter
    • One Month Later
      jrromero17 earned a badge
      One Month Later
    • Week One Done
      jrromero17 earned a badge
      Week One Done
    • Conversation Starter
      johnwin1 earned a badge
      Conversation Starter
    • One Month Later
      Marwin earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      246
    2. 2
      snowy owl
      156
    3. 3
      ATLien_0
      142
    4. 4
      +FloatingFatMan
      138
    5. 5
      Xenon
      127
  • Tell a friend

    Love Neowin? Tell a friend!