• 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

    • OontZ Angle 3 Coca-Cola Edition Bluetooth Speaker: Worth it at 25% off? by Paul Hill If you are looking for a portable Bluetooth speaker for yourself or for Father’s Day, check out this OontZ Coca-Cola branded Angle 3 Bluetooth speaker. Right now, you can pick it up for just $30, thanks to a recent 25% discount from the previous $40 price tag. Aside from the Coca-Cola branding, this speaker has a range of nifty features including a 100-foot range, a 14-hour battery, IPX5 water resistance, it promises no distortion of sound, and its shape ensures it won’t fall over. What it does (and doesn’t) The Oontz Bluetooth Speaker Angle 3 Coca-Cola Edition is super portable, making it an ideal choice for when you’re traveling. The speaker is just 5.3 inches long and weighs just 10 ounces. The width and height of the speaker are both under three inches and its triangular shape ensures it won’t fall over so you can put it down quickly whenever you’re out and about. According to OontZ, the speaker has 10 watts output that is “surprisingly loud” with “zero distortion” even when you turn it up to the max. These OontZ speakers are crafted by Cambridge Soundworks, a firm that has received critical acclaim since its inception in 1988. The firm is praised for delivering solid sound quality and construction - it makes some of the industry’s best speakers and offers excellent value for the price. As a travel speaker, it’ll probably end up on the beach or next to swimming pools where it can get wet. You don’t need to worry about splashing it though because it comes with IPX5 water resistance meaning it’s splash-proof, suitable for the shower, beaches, or the pool. While it will offer protection against splashes, it shouldn’t be submerged under water. On a single charge, the speaker will last for 14 hours on a single charge and connects to your device using Bluetooth 5.0. It has a good range of 100 feet so it shouldn’t become choppy just because you went into the next room with your phone. Should you buy? This OontZ Coca-Cola Bluetooth speaker is ideal for anyone who wants a great listening experience at home or on the go. It’s also a good choice for anyone looking for good sound on a budget as it’s now $30, which won’t break the bank. The main strengths of the speaker are its excellent value at the discounted price, reliable connectivity, and the good battery life considering its size. The fact that it’s from a reputable brand, Cambridge Soundworks, is also key. The iconic Coca-Cola branding may not be for everybody but it will definitely stand out with that vibrant red color. The IPX5 is also good to protect against splashes but it’s not fully waterproof, so if you need that, this speaker might not be for you. Oontz Bluetooth Speaker Angle 3 Coca-Cola Edition: $29.99 (Amazon US) - MSRP $39.99 / 25% off This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • GPUs selling higher than their MSRP is the new norm it seems. This shouldn't surprise anyone. Dumb duopoly, if Intel could just stop shooting itself in the foot and release some more cards and undercut the other two that'd be great.
    • I saw that recently, and the thing that would be useful also would be to have the PC model in that spec card as well. I know that it's on the main portal page of System, but repeating it in this "Device specs" module, especially if it's meant for the main specs of the computer, would certainly be useful.
    • Do you want a little in the ground or a lot in the air?
    • Bethesda readying two updates for Oblivion Remastered targeting bugs and performance by Pulasthi Ariyasinghe The surprise release of The Elder Scrolls IV: Oblivion Remastered was a massive success for Bethesda and Microsoft, with the title going on to gain over four million players in just three days at launch while also breaking franchise records for concurrent players. While reactions to the game have been positive from both critics and players, plenty of complaints have since been pouring in about the state of the remaster. Now, Bethesda is aiming to push out updates to resolve these concerns. Today, the company revealed that two updates are currently planned for the RPG, both with different scopes. The first of these is already available in beta form to Steam players. It seems Bethesda is using the same beta update format it uses for Starfield for this Elder Scrolls entry as well. "Thanks for all your excitement and feedback since the launch of The Elder Scrolls IV: Oblivion Remastered," said the development team today. "We are actively working on two separate updates to be launched in the coming weeks, both of which will come to our Steam Beta first, before being released to all other platforms." According to the studio, the first update is focused on "quests, major bugs and blockers, and quality of life fixes. " Following the June 5 launch on the Steam beta platform, all other PC players, as well as those on Xbox Series X|S, PlayStation 5, and Game Pass subscribers, will receive the update on June 11. The beta changelog for Update 1.1 can be seen here, with bug fixes coming for the UI, gameplay, quests, and more. Multiple crashes have been resolved here, with many being related to loading saves and exploring specific locations. Instances of infinite loading, alt-tab freezing, resetting settings, and more are being targeted with fixes, too. To opt into the Elder Scrolls IV: Oblivion Remastered beta update, Steam players can head into the game's properties, select Betas, and choose the [beta] branch to receive the new build. While Bethesda hasn't revealed any release dates for the second update, it did say that improving performance will be its main focus. This is a major point of criticism for the title at the moment, so the update can't come soon enough.
  • 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
      408
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      178
    4. 4
      ATLien_0
      172
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!