• 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

    • Go ###### yourself Apple. What an embarassing piece of ###### company.
    • From code to combat: Meta CTO calls for Silicon Valley involvement in military contracts by Hamid Ganji This week, Meta announced a partnership with the defense technology startup Anduril to build next-gen VR/AR extended reality headsets for the US military. Microsoft was given the contract in 2018, and the headsets were supposed to be built based on Microsoft HoloLens. Earlier this year, Microsoft gave up the entire project to Anduril but kept its role as the cloud services provider. Meta's Chief Technology Officer (CTO) is now calling for more Silicon Valley involvement in military contracts. Speaking at the Bloomberg Tech summit in San Francisco (via: Business Insider), Andrew Bosworth said the recent partnership between Meta, Anduril, and the US military could be a "return to grace" for Silicon Valley. "The Valley was founded on a three-way investment between the military, academics, and private industry. That was the founding of it," Bosworth said. Meta's CTO added that building VR/AR headsets for the US military doesn't turn the company into a defense contractor. He also said it was "way too early" to determine whether military contracts would become a business segment for Meta. "So far, it's like a zero. Let's start with one and go from there. I think there's no reason it couldn't be meaningful in the impact that it has," he added. The US military's desire for AI-powered tools and weapons has turned Big Tech into military contractors, whether willingly or unwillingly. Companies like Microsoft, Google, and Meta have a long history of providing services to the military and law enforcement agencies. The relationship between tech firms and the defense segment has always been controversial. In the most recent case, a group of Microsoft employees protested against the company's partnership with the Israeli military, which led to the layoff of the protesting staff.
    • Or run msinfo32! With Windows 11, Microsoft believes it has reinvented the wheel?
    • The long-awaited Nothing Phone (3) is finally coming next month, launch date confirmed by Aditya Tiwari London-based consumer electronics brand Nothing is due to launch its latest flagship in 2025. The company dropped a new teaser for the Phone (3), revealing when the flagship device will be out on the market. Nothing Phone (3) will be unveiled during a live event on July 1 at 1:00 PM ET / 10:00 AM PT / 6:00 PM BST / 11:30 PM IST. It has already created a live event titled "Come to Play" on its official YouTube channel, for which you can add a reminder by clicking on the "Notify Me" button. Nothing CEO Carl Pei has previously dropped several details about the unreleased smartphone. He took part in a social media AMA earlier this year and said Nothing Phone (3) will arrive in the third quarter of 2025. Pei confirmed that Nothing Phone (3) will make its way to the US this time after a dry spell since 2023. However, he didn't specify whether the device will be sold directly or through the beta channel, which currently includes Phone (3a), Phone (3a) Pro, and CMF Phone 2 Pro. The US has been a rocky terrain for Nothing. Its first smartphone was made available through the beta channel, and the Nothing Phone (2) is the only smartphone from the company that has been widely available in the US. The Glyph interface featured on the back of Nothing smartphones has remained a differentiating factor from the start. However, the smartphone maker recently posted a 9-second video in which the Glyph lights on the back of a Nothing smartphone abruptly turn off. "We killed the Glyph Interface," the company said. It makes sense when you check out the Phone (3) teaser and see dot matrix-style lights being flashed in a pattern. Nothing released another teaser about a week ago, featuring the number 3 lit up as dot matrix LEDs. If you're looking for some trivia, Nothing product manager Raymond Zhu estimated in a Q&A video that the company would need to sell about 250,000 Phone (3) units to turn a profit. Answering another question, he added that their biggest weakness is "no one knows us", and the company is struggling to reach the masses without high marketing budgets. Let's wait to see what Nothing has in store for Phone (3) next month other than the new physical button. Speaking of the future of smartphones, the Nothing CEO believes that our entire software experience will eventually be condensed down to just one app.
    • As far as I can remember, no one has done a 4v4 before. 2v2? yes. 3v3? yes.
  • Recent Achievements

    • 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
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      403
    2. 2
      +FloatingFatMan
      179
    3. 3
      snowy owl
      174
    4. 4
      ATLien_0
      170
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!