• 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

    • NTLite 2025.06.10459 is out.
    • Wireshark 4.4.7 by Razvan Serea  Wireshark is a network packet analyzer. A network packet analyzer will try to capture network packets and tries to display that packet data as detailed as possible. You could think of a network packet analyzer as a measuring device used to examine what's going on inside a network cable, just like a voltmeter is used by an electrician to examine what's going on inside an electric cable (but at a higher level, of course). In the past, such tools were either very expensive, proprietary, or both. However, with the advent of Wireshark, all that has changed. Wireshark is perhaps one of the best open source packet analyzers available today. Deep inspection of hundreds of protocols, with more being added all the time Live capture and offline analysis Standard three-pane packet browser Multi-platform: Runs on Windows, Linux, OS X, Solaris, FreeBSD, NetBSD, and many others Captured network data can be browsed via a GUI, or via the TTY-mode TShark utility The most powerful display filters in the industry Rich VoIP analysis Read/write many different capture file formats Capture files compressed with gzip can be decompressed on the fly Live data can be read from Ethernet, IEEE 802.11, PPP/HDLC, ATM, Bluetooth, USB, Token Ring, Frame Relay, FDDI, and others (depending on your platfrom) Decryption support for many protocols, including IPsec, ISAKMP, Kerberos, SNMPv3, SSL/TLS, WEP, and WPA/WPA2 Coloring rules can be applied to the packet list for quick, intuitive analysis Output can be exported to XML, PostScript®, CSV, or plain text Wireshark 4.4.7 changelog: The following vulnerabilities have been fixed wnpa-sec-2025-02 Dissection engine crash. Issue 20509. CVE-2025-5601. The following bugs have been fixed Wireshark does not correctly decode LIN "go to sleep" in TECMP and CMP. Issue 20463. Dissector bug, Protocol CIGI. Issue 20496. Green power packets are not dissected when proto_version == ZBEE_VERSION_GREEN_POWER. Issue 20497. Packet diagrams misalign or drop bitfields. Issue 20507. Corruption when setting heuristic dissector table UI name from Lua. Issue 20523. LDAP dissector incorrectly displays filters with singleton "&" Issue 20527. WebSocket per-message compression extentions: fail to decompress server messages (from the 2nd) due to parameter handling. Issue 20531. The LL_PERIODIC_SYNC_WR_IND packet is not properly dissected (packet-btle.c) Issue 20554. Updated Protocol Support AT, BT LE LL, CIGI, genl, LDAP, LIN, Logcat Text, net_dm, netfilter, nvme, SSH, TCPCL, TLS, WebSocket, ZigBee, and ZigBee ZCL Download: Wireshark 4.4.7 | 83.2 MB (Open Source) Download: Portable Wireshark 4.4.7 | ARM64 Installer View: Wireshark Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Snapchat finally has a watchOS app, a decade after the Apple Watch launched by David Uzondu Snap has announced that Snapchat is finally hopping onto Apple Watch, something many users have probably been waiting for. This new app lets you easily preview an incoming message right on your wrist and then fire back a reply without ever needing to grab your iPhone. For those quick responses, you have options: you can tap out a message on the keyboard, use Scribble to draw letters, dictate your reply, or just send a fitting emoji. Snap says it's trying to make Snapchat easier to use on all the different devices people have in their lives. It's already seen people using Snapchat on tablets and the web, so bringing it to wearables like the Apple Watch feels like the next natural move. That marks a big change from back in 2015 when the Apple Watch first launched. At the time, Snap took a more cautious "wait and see" approach, wanting to see if people actually used smartwatches before building an app. New app launches are not always perfect. It is still early days for the watchOS app, as some users on Reddit have reported the app being stuck on the loading screen. Hopefully, Snap will address these initial teething problems quickly. This expansion to Apple Watch comes after the company abandoned its widely criticized three-tab app redesign following a notable drop in its North American daily active users and significant negative feedback. That redesign, introduced back in September 2024, was meant to simplify things but ended up frustrating many, leading Snap to reverse course after about seven months and work on a refined five-tab layout. Meanwhile, Android smartwatch users with Wear OS are still in a different boat, as there is no official, dedicated Snapchat app for that platform yet. They can typically only receive notifications, and attempts to sideload the full Android app often result in a clunky experience.
    • I've asked Sayan to limit these articles to science tech news.
    • LeafView 3.6.4 by Razvan Serea LeafView is a fast, open-source image viewer built with Electron. It offers a sleek, minimal UI for fast and efficient image browsing. Supporting various formats, LeafView ensures a smooth viewing experience with essential features like zoom, rotation, and slideshow mode. Designed for simplicity and performance, it utilizes hardware acceleration for smooth rendering and supports touch gestures for seamless navigation. LeafView key features: Lightweight & Open-Source – Minimal resource usage with a clean, efficient design Electron-Based – Cross-platform compatibility with modern UI Multiple Image Format Support – Opens JPG, PNG, GIF, BMP, and more Smooth Rendering – Hardware acceleration for fast performance Essential Image Controls – Zoom, rotate, and slideshow mode Touch Gesture Support – Seamless navigation on compatible devices Minimal UI – Focused on simplicity and ease of use LeafView 3.6.4 changelog: Update electron to v36.4.0 Download: LeafView 3.6.4 | Portable | ~100.0 MB (Open Source) View: LeafView Website | Other operating systems | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Year In
      survivor303 earned a badge
      One Year In
    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
    • First Post
      James courage Tabla earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      419
    2. 2
      +FloatingFatMan
      182
    3. 3
      snowy owl
      181
    4. 4
      ATLien_0
      174
    5. 5
      Xenon
      137
  • Tell a friend

    Love Neowin? Tell a friend!