Search code examples
javac++argv

Convert C++ to Java - Small Project


I need help converting this block of code into java. I've never used C++ before so this is a task. This is the C++ code:

#include<iostream>
#include<stdlib.h>
#define PAGE_SIZE 4096
using namespace std;

int main(int argc, char **argv){
if(argc<2){
cout<<"Enter the address: ";
return -1;
}
unsigned int address = atoi(argv[1]);
unsigned int page_number = address / PAGE_SIZE;
unsigned int offset = address%PAGE_SIZE;
cout<<"the address "<<address<<"contains: Page number = "<<page_number<<"And off set = "<<offset<<endl;
system("pause");
}

This is what I have so far in java:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int pageSize = 4096;
    int x = 0;
    int address = atoi(argv[1]);
    int pageNumber = address / pageSize;
    int offset = address % pageSize;
    if (x < 2) {
        System.out.println("Enter the address: ");
        x = in.nextInt();
    }
    System.out.println("The address " + address + " contains: Page number = " + pageNumber + " And off set = " + offset);
}

I'm not sure what "argv[1]" meant in C++, so I don't know how to convert it to java. I'm doing this for homework and the question I am trying to answer is:

Assume that a system has a 32-bit virtual address with a 4-KB page size. Write a program that is passed a virtual address (in decimal) on the command line and have it output the page number and offset for the given address.

As an example, your program would run as follows: yourprogram 19986

Your program would output:

The address 19986 contains: Page number = 4 Offset = 3602

Writing this program will require using the appropriate data type to store 32 bits. Use unsigned data type types as well.

Any help on this would be very much so appreciated.


Solution

  • In your java program the Scanner in variable will read the input, therefore you should add the input to address. The calculation has to be made after the input as the variable will assign with values when the user inputs the result.

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int pageSize = 4096;
        int address = 0;
        if (address < 2) {
            System.out.println("Enter the address: ");
            address = in.nextInt();
        }
        int pageNumber = address / pageSize;
        int offset = address % pageSize;
        System.out.println("The address " + address + " contains: Page number = " + pageNumber + " And off set = " + offset);
    }
    

    In C++ argv means that the input will be the first command line argument and it will be an integer.

    In your C++ program:

    unsigned int address = atoi(argv[1]);
    

    address will be the input from the command line, in the example given address = 19986