• 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

    • I have the chance to live where electricity comes only from dams.
    • Which doesn't give them a pass for making the same game with a different skin
    • End of 10: Upgrade to Windows 11 Home or Pro for only $14.97 by Steven Parker Microsoft has been reminding users about the upcoming end of support for Windows 10 that is inbound in less than four months. In the reminder, Microsoft has highlighted ways to deal with the event, covering both scenarios depending on whether your system is eligible for a Windows 11 upgrade or not. If you are in the latter camp, then Microsoft wants you to buy a new Windows 11 PC and that is something the tech giant has repeated time and again, even as recently as this past month in the context of Copilot+ AI PCs. It has also provided some data to back up claims of huge performance and productivity boost, albeit citing a paid study. However, if you are like me and don't plan to buy a CoPilot+ PC, and you have hardware that is eligible for Windows 11 (without bypasses) and if you are locked out of the free upgrade path, you can score a Windows 11 license for very little. Description follows: Upgrade your computing experience with Windows 11 Pro. This cutting-edge operating system boasts a sleek new design and advanced tools to help you work faster and smarter. From creative projects to gaming and beyond, Windows 11 delivers the power and flexibility you need to achieve your goals. With a focus on productivity, the new features are easy to learn and use, enhancing your workflow and efficiency. Whether you're a student, professional, gamer, or creative, Windows 11 Home has everything you need to take your productivity to the next level. New interface. easier on the eyes & easier to use Biometrics login*.Encrypted authentication & advanced antivirus defenses DirectX 12 Ultimate. Play the latest games with graphics that rival reality. DirectX 12 Ultimate comes ready to maximize your hardware* Screen space. Snap layouts, desktops & seamless redocking Widgets. Stay up-to-date with the content you love & the new you care about Microsoft Teams. Stay in touch with friends and family with Microsoft Teams, which can be seamlessly integrated into your taskbar** Wake & lock. Automatically wake up when you approach and lock when you leave Smart App Control. Provides a layer of security by only permitting apps with good reputations to be installed Windows Studio Effects. Designed with Background Blur, Eye Contact, Voice Focus, & Automatic Framing Touchscreen. For a true mouse-less or keyboard-less experience TPM 2.0. Helps prevent unwanted tampering Windows 11 Pro also includes a number of productivity-focused features, such as the ability to snap multiple windows together and create custom layouts, improved voice typing, and a new, more powerful search experience. Personal and professional users will enjoy a modern and secure computing experience, with improved performance and productivity features to help users get more done. Only on Windows 11 Pro If you require enterprise-oriented features for your daily professional tasks, then Windows 11 Pro is a better option. Set up with a local account (only when set up for work or school) Join Active Directory/Azure AD Hyper-V Windows Sandbox Microsoft Remote Desktop BitLocker device encryption Windows Information Protection Mobile device management (MDM) Group Policy Enterprise State Roaming with Azure Assigned Access Dynamic Provisioning Windows Update for Business Kiosk mode Maximum RAM: 2TB Maximum no. of CPUs: 2 Maximum no. of CPU cores: 128 Good to know This license is for Windows 11 only. It is NOT intended to be used for upgrading Microsoft Office (MSO) included in Parallels Pro. However, it will still work with Parallels Pro and allow you to run Windows applications including MSO, but it DOES NOT include an upgrade MSO itself. It is still compatible with Microsoft Office ONLY if you have a separate license for it. Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop Max number of device(s): 1 Version: Windows 11 Pro Updates included Click here to verify Microsoft partnership For example, a Microsoft Windows 11 Pro license normally costs $199, but you can pick it up for just $14.97 for a limited time, that represents a saving of $184. For a full description, specs, and license info, click the link below. Get Windows 11 Home or Pro for just $14.97 See all discounted Neowin Deals on offer. This is a time-limited deal. Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • Looks good!
    • 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.
  • 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
      409
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      177
    4. 4
      ATLien_0
      171
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!