CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Nov 2022
    Posts
    1

    Convert C++ Code to Java

    Hello. I just wandering on how to convert C++ code to Java since I have an assignment in converting this C++ Code to Java. Please help me thanks. I also need to study the difference in the implementation of the code in C++ and Java hehe. #javabegginer

    #include <iostream>
    #include <iomanip>
    #include <string>
    using namespace std;

    struct StudentGrade
    {
    int quiz1;
    int quiz2;
    int midterm;
    int final;
    int total;
    string firstName;
    string lastName;
    double percent, avg;
    char letterGrade;
    };

    void getData(StudentGrade& g);
    void setLetterGrade(StudentGrade& g);
    void format(int n);

    #define W(i) setw(17)
    #define Y(i) setw(10)

    int main()
    {
    char run_again;

    do
    {
    StudentGrade g;
    getData(g);

    const double Q_PERCENT = 12.5;
    const double M_PERCENT = 25.0;
    const double F_PERCENT = 50.0;
    const int Q_SCORE = 10;
    const int E_SCORE = 100;

    double q1 = double(g.quiz1) / Q_SCORE * Q_PERCENT;
    double q2 = double(g.quiz2) / Q_SCORE * Q_PERCENT;
    double m = double(g.midterm) / E_SCORE * M_PERCENT;
    double f = double(g.midterm) / E_SCORE * F_PERCENT;

    g.total = g.quiz1 + g.quiz2 + g.midterm + g.final;
    g.percent = q1 + q2 + m + f;

    int tScore = Q_SCORE * 2 + E_SCORE * 2;
    double tPercent = Q_PERCENT * 2 + M_PERCENT + F_PERCENT;

    setLetterGrade(g);

    format(1);
    cout << endl << endl;
    cout << "Here are the results for " << g.firstName << " " << g.lastName << "." << endl;
    cout << Y(i) << "TEST" << Y(i) << "TEST" << Y(i) << "MAX" << W(i) << "GRADE SCORE"
    << W(i) << "MAXIMUM SCORE" << endl;
    cout << Y(i) << "PERIOD" << Y(i) << "SCORE" << Y(i) << "SCORE" << W(i) << "DISTRIBUTION"
    << W(i) << "DISTRIBUTION" << endl << endl;
    cout << Y(i) << "Quiz 1" << Y(i) << g.quiz1 << Y(i) << Q_SCORE << W(i) << q1 << "%"
    << W(i) << Q_PERCENT << "%" << endl;
    cout << Y(i) << "Quiz 2" << Y(i) << g.quiz2 << Y(i) << Q_SCORE << W(i) << q2 << "%"
    << W(i) << Q_PERCENT << "%" << endl;
    cout << Y(i) << "Midterm" << Y(i) << g.midterm << Y(i) << E_SCORE << W(i) << m << "%"
    << W(i) << M_PERCENT << "%" << endl;
    cout << Y(i) << "Final" << Y(i) << g.final << Y(i) << E_SCORE << W(i) << f << "%"
    << W(i) << F_PERCENT << "%" << endl;
    cout << Y(i) << "_________________________________________________ ______________________\n";
    cout << Y(i) << "TOTAL" << Y(i) << g.total << Y(i) << tScore << W(i) << g.percent << "%"
    << W(i) << tPercent << "%" << endl;

    cout << Y(i) << "Average" << Y(i) << (double(g.total) / tScore * tPercent) << "%" << endl;
    cout << Y(i) << "Grade: " << Y(i) << g.letterGrade << endl;

    cout << endl << endl;
    cout << "Would you like to try again for another student? (y/n) : ";
    cout << "(enter Y or N)";
    cout << endl;
    cin >> run_again;
    } while ((run_again == 'y') || (run_again == 'Y'));
    system("pause");
    return 0;

    }

    void getData(StudentGrade& g)
    {
    cout << "Enter the student's first name: ";
    cin >> g.firstName;
    cout << "Enter the student's last name: ";
    cin >> g.lastName;
    cout << "Enter Quiz 1 score (maximum is 10): ";
    cin >> g.quiz1;
    cout << "Enter Quiz 2 score (maximum is 10): ";
    cin >> g.quiz2;
    cout << "Enter Midterm score (maximum is 100): ";
    cin >> g.midterm;
    cout << "Enter Final score (maximum is 100): ";
    cin >> g.final;

    g.quiz1 = g.quiz1 > 10 ? 10 : g.quiz1;
    g.quiz1 = g.quiz1 < 0 ? 0 : g.quiz1;
    g.quiz2 = g.quiz2 > 10 ? 10 : g.quiz2;
    g.quiz2 = g.quiz2 < 0 ? 0 : g.quiz2;
    g.midterm = g.midterm > 100 ? 100 : g.midterm;
    g.midterm = g.midterm < 0 ? 0 : g.midterm;
    g.final = g.final > 100 ? 100 : g.final;
    g.final = g.final < 0 ? 0 : g.final;

    return;
    }

    void setLetterGrade(StudentGrade& g)
    {
    if (g.percent >= 90.0)
    g.letterGrade = 'A';
    else if (g.percent >= 80.0)
    g.letterGrade = 'B';
    else if (g.percent >= 70.0)
    g.letterGrade = 'C';
    else if (g.percent >= 60.0)
    g.letterGrade = 'D';
    else
    g.letterGrade = 'F';
    }

    void format(int n)
    {
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(n);
    }

  2. #2
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,860

    Re: Convert C++ Code to Java

    What part of the C++ code don't you understand?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    Feb 2017
    Posts
    674

    Re: Convert C++ Code to Java

    Quote Originally Posted by ForgottenLaw View Post
    I have an assignment in converting this C++ Code to Java.
    Your assignment seems to come from here as someone's solution to an exercise in Absolute C++ by Savitch.

    http://www.sr2jr.com/textbook-soluti...es-and-classes

    Maybe it was your Java instructor who posted it there?

    Anyway, why not use a free C++ to Java converter? There are quite a few on the internet.

    I also need to study the difference in the implementation of the code in C++ and Java
    The C++ program adheres to the procedural programming paradigm. That means a straight conversion to Java will use the static keyword extensively. However, overusing static is considered bad Java. So, except for the syntax, the C++ and Java versions will be identical. But they will be perceived differently by each programming community - okay in C++, not okay in Java.
    Last edited by wolle; November 25th, 2022 at 01:41 AM.

  4. #4
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,860

    Re: Convert C++ Code to Java

    As you have the original exercise requirements, I'd suggest you forget the C++ code and code your own version direct in Java. You'll learn more.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  5. #5
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,860

    Re: Convert C++ Code to Java

    It's not even that good C++ code... Perhaps 'better' C++:

    Code:
    #include <iostream>
    #include <iomanip>
    #include <string>
    
    struct StudentGrade {
    	unsigned quiz1 {};
    	unsigned quiz2 {};
    	unsigned midterm {};
    	unsigned final{};
    	unsigned total {};
    	std::string firstName;
    	std::string lastName;
    	double percent {}, avg {};
    	char letterGrade {};
    	double q1 {};
    	double q2 {};
    	double m {};
    	double f {};
    };
    
    StudentGrade getData();
    void setLetterGrade(StudentGrade&);
    void format(int);
    void output(const StudentGrade&);
    
    constexpr double Q_PERCENT { 12.5 };
    constexpr double M_PERCENT { 25.0 };
    constexpr double F_PERCENT { 50.0 };
    constexpr double Q_SCORE { 10 };
    constexpr double E_SCORE { 100 };
    
    constexpr auto tScore { Q_SCORE * 2 + E_SCORE * 2 };
    constexpr auto tPercent { Q_PERCENT * 2 + M_PERCENT + F_PERCENT };
    
    #define W std::setw(17)
    #define Y std::setw(10)
    
    int main() {
    	char run_again {};
    
    	do {
    		output(getData());
    
    		std::cout << "Would you like to try again for another student? ([Y]es/[N]o) : ";
    		std::cin >> run_again;
    	} while ((run_again == 'y') || (run_again == 'Y'));
    }
    
    void output(const StudentGrade& g) {
    	format(1);
    
    	std::cout << "\n\nHere are the results for " << g.firstName << " " << g.lastName << ".\n";
    	std::cout << Y << "TEST" << Y << "TEST" << Y << "MAX" << W << "GRADE SCORE"
    		<< W << "MAXIMUM SCORE" << '\n';
    	std::cout << Y << "PERIOD" << Y << "SCORE" << Y << "SCORE" << W << "DISTRIBUTION"
    		<< W << "DISTRIBUTION" << "\n\n";
    	std::cout << Y << "Quiz 1" << Y << g.quiz1 << Y << Q_SCORE << W << g.q1 << "%"
    		<< W << Q_PERCENT << "%\n";
    	std::cout << Y << "Quiz 2" << Y << g.quiz2 << Y << Q_SCORE << W << g.q2 << "%"
    		<< W << Q_PERCENT << "%\n";
    	std::cout << Y << "Midterm" << Y << g.midterm << Y << E_SCORE << W << g.m << "%"
    		<< W << M_PERCENT << "%\n";
    	std::cout << Y << "Final" << Y << g.final << Y << E_SCORE << W << g.f << "%"
    		<< W << F_PERCENT << "%\n";
    	std::cout << Y << "_________________________________________________ ______________________\n";
    	std::cout << Y << "TOTAL" << Y << g.total << Y << tScore << W << g.percent << "%"
    		<< W << tPercent << "%\n";
    
    	std::cout << Y << "Average" << Y << (double(g.total) / tScore * tPercent) << "%\n";
    	std::cout << Y << "Grade: " << Y << g.letterGrade << "\n\n\n";
    }
    
    StudentGrade getData() {
    	StudentGrade g;
    
    	std::cout << "Enter the student's first name: ";
    	std::cin >> g.firstName;
    
    	std::cout << "Enter the student's last name: ";
    	std::cin >> g.lastName;
    
    	std::cout << "Enter Quiz 1 score (maximum is 10): ";
    	std::cin >> g.quiz1;
    
    	std::cout << "Enter Quiz 2 score (maximum is 10): ";
    	std::cin >> g.quiz2;
    
    	std::cout << "Enter Midterm score (maximum is 100): ";
    	std::cin >> g.midterm;
    
    	std::cout << "Enter Final score (maximum is 100): ";
    	std::cin >> g.final;
    
    	g.quiz1 = g.quiz1 > 10 ? 10 : g.quiz1;
    	g.quiz2 = g.quiz2 > 10 ? 10 : g.quiz2;
    	g.midterm = g.midterm > 100 ? 100 : g.midterm;
    	g.final = g.final > 100 ? 100 : g.final;
    
    	g.q1 = g.quiz1 / Q_SCORE * Q_PERCENT;
    	g.q2 = g.quiz2 / Q_SCORE * Q_PERCENT;
    	g.m = g.midterm / E_SCORE * M_PERCENT;
    	g.f = g.midterm / E_SCORE * F_PERCENT;
    
    	g.total = g.quiz1 + g.quiz2 + g.midterm + g.final;
    	g.percent = g.q1 + g.q2 + g.m + g.f;
    
    	setLetterGrade(g);
    	return g;
    }
    
    void setLetterGrade(StudentGrade& g)
    {
    	if (g.percent >= 90.0)
    		g.letterGrade = 'A';
    	else if (g.percent >= 80.0)
    		g.letterGrade = 'B';
    	else if (g.percent >= 70.0)
    		g.letterGrade = 'C';
    	else if (g.percent >= 60.0)
    		g.letterGrade = 'D';
    	else
    		g.letterGrade = 'F';
    }
    
    void format(int n)
    {
    	std::cout.setf(std::ios::fixed);
    	std::cout.setf(std::ios::showpoint);
    	std::cout.precision(n);
    }
    [Excluding std::format from C++20]
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  6. #6
    Join Date
    Feb 2017
    Posts
    674

    Re: Convert C++ Code to Java

    Quote Originally Posted by 2kaud View Post
    It's not even that good C++ code...
    I agree. The code the OP posted looks like written by a C++ newbie, which it probably is, considering where it originates (as someone's solution to a textbook exercise). No programming language educator with self-respect would "borrow" such code and reuse it in an assignment.

    I tried the first free C++ to Java converter I found on the internet on your code.

    https://c-to-java-converter-free-edi....informer.com/

    Here is the result:

    Code:
    public class GlobalMembers
    {
    
    	public static StudentGrade getData()
    	{
    		StudentGrade g = new StudentGrade();
    
    		System.out.print("Enter the student's first name: ");
    		g.firstName = ConsoleInput.readToWhiteSpace(true);
    
    		System.out.print("Enter the student's last name: ");
    		g.lastName = ConsoleInput.readToWhiteSpace(true);
    
    		System.out.print("Enter Quiz 1 score (maximum is 10): ");
    		g.quiz1 = Integer.parseInt(ConsoleInput.readToWhiteSpace(true));
    
    		System.out.print("Enter Quiz 2 score (maximum is 10): ");
    		g.quiz2 = Integer.parseInt(ConsoleInput.readToWhiteSpace(true));
    
    		System.out.print("Enter Midterm score (maximum is 100): ");
    		g.midterm = Integer.parseInt(ConsoleInput.readToWhiteSpace(true));
    
    		System.out.print("Enter Final score (maximum is 100): ");
    		g.final = Integer.parseInt(ConsoleInput.readToWhiteSpace(true));
    
    		g.quiz1 = g.quiz1 > 10 ? 10 : g.quiz1;
    		g.quiz2 = g.quiz2 > 10 ? 10 : g.quiz2;
    		g.midterm = g.midterm > 100 ? 100 : g.midterm;
    		g.final = g.final > 100 ? 100 : g.final;
    
    		g.q1 = g.quiz1 / Q_SCORE * Q_PERCENT;
    		g.q2 = g.quiz2 / Q_SCORE * Q_PERCENT;
    		g.m = g.midterm / E_SCORE * M_PERCENT;
    		g.f = g.midterm / E_SCORE * F_PERCENT;
    
    		g.total = g.quiz1 + g.quiz2 + g.midterm + g.final;
    		g.percent = g.q1 + g.q2 + g.m + g.f;
    
    		setLetterGrade(g);
    		return g;
    	}
    	public static void setLetterGrade(StudentGrade g)
    	{
    		if (g.percent >= 90.0)
    		{
    			g.letterGrade = (byte)'A';
    		}
    		else if (g.percent >= 80.0)
    		{
    			g.letterGrade = (byte)'B';
    		}
    		else if (g.percent >= 70.0)
    		{
    			g.letterGrade = (byte)'C';
    		}
    		else if (g.percent >= 60.0)
    		{
    			g.letterGrade = (byte)'D';
    		}
    		else
    		{
    			g.letterGrade = (byte)'F';
    		}
    	}
    	public static void format(int n)
    	{
    //C++ TO JAVA CONVERTER TODO TASK: The cout 'showpoint' manipulator is not converted by C++ to Java Converter:
    //ORIGINAL LINE: std::cout.setf(std::ios::showpoint);
    	}
    	public static void output(StudentGrade g)
    	{
    		format(1);
    
    		System.out.print("\n\nHere are the results for ");
    		System.out.print(g.firstName);
    		System.out.print(" ");
    		System.out.print(g.lastName);
    		System.out.print(".\n");
    		System.out.printf("%10d", "TEST");
    		System.out.printf("%10d", "TEST");
    		System.out.printf("%10d", "MAX");
    		System.out.printf("%17d", "GRADE SCORE");
    		System.out.printf("%17d", "MAXIMUM SCORE");
    		System.out.printf("%d", '\n');
    		System.out.printf("%10d", "PERIOD");
    		System.out.printf("%10d", "SCORE");
    		System.out.printf("%10d", "SCORE");
    		System.out.printf("%17d", "DISTRIBUTION");
    		System.out.printf("%17d", "DISTRIBUTION");
    		System.out.printf("%d", "\n\n");
    		System.out.printf("%10d", "Quiz 1");
    		System.out.printf("%10d", g.quiz1);
    		System.out.printf("%10d", Q_SCORE);
    		System.out.printf("%17d", g.q1);
    		System.out.printf("%d", "%");
    		System.out.printf("%17d", Q_PERCENT);
    		System.out.printf("%d", "%\n");
    		System.out.printf("%10d", "Quiz 2");
    		System.out.printf("%10d", g.quiz2);
    		System.out.printf("%10d", Q_SCORE);
    		System.out.printf("%17d", g.q2);
    		System.out.printf("%d", "%");
    		System.out.printf("%17d", Q_PERCENT);
    		System.out.printf("%d", "%\n");
    		System.out.printf("%10d", "Midterm");
    		System.out.printf("%10d", g.midterm);
    		System.out.printf("%10d", E_SCORE);
    		System.out.printf("%17d", g.m);
    		System.out.printf("%d", "%");
    		System.out.printf("%17d", M_PERCENT);
    		System.out.printf("%d", "%\n");
    		System.out.printf("%10d", "Final");
    		System.out.printf("%10d", g.final);
    		System.out.printf("%10d", E_SCORE);
    		System.out.printf("%17d", g.f);
    		System.out.printf("%d", "%");
    		System.out.printf("%17d", F_PERCENT);
    		System.out.printf("%d", "%\n");
    		System.out.printf("%10d", "_________________________________________________ ______________________\n");
    		System.out.printf("%10d", "TOTAL");
    		System.out.printf("%10d", g.total);
    		System.out.printf("%10d", tScore);
    		System.out.printf("%17d", g.percent);
    		System.out.printf("%d", "%");
    		System.out.printf("%17d", tPercent);
    		System.out.printf("%d", "%\n");
    
    		System.out.printf("%10d", "Average");
    		System.out.printf("%10d", ((double)g.total / tScore * tPercent));
    		System.out.printf("%d", "%\n");
    		System.out.printf("%10d", "Grade: ");
    		System.out.printf("%10d", g.letterGrade);
    		System.out.printf("%d", "\n\n\n");
    	}
    
    	public static final double Q_PERCENT = 12.5;
    	public static final double M_PERCENT = 25.0;
    	public static final double F_PERCENT = 50.0;
    	public static final double Q_SCORE = 10;
    	public static final double E_SCORE = 100;
    
    	public static final auto tScore = new auto(Q_SCORE * 2 + E_SCORE * 2);
    	public static final auto tPercent = new auto(Q_PERCENT * 2 + M_PERCENT + F_PERCENT);
    
    	//C++ TO JAVA CONVERTER NOTE: The following #define macro was replaced in-line:
    	//ORIGINAL LINE: #define W std::setw(17)
    	//C++ TO JAVA CONVERTER NOTE: The following #define macro was replaced in-line:
    	//ORIGINAL LINE: #define Y std::setw(10)
    
    	public static int Main()
    	{
    		byte run_again = 0;
    
    		do
    		{
    			output(getData());
    
    			System.out.print("Would you like to try again for another student? ([Y]es/[N]o) : ");
    			run_again = Byte.parseByte(ConsoleInput.readToWhiteSpace(true));
    		} while ((run_again == 'y') || (run_again == 'Y'));
    	}
    }
    
    public class StudentGrade
    {
    	public int quiz1 = 0;
    	public int quiz2 = 0;
    	public int midterm = 0;
    	public int final = 0;
    	public int total = 0;
    	public String firstName;
    	public String lastName;
    	public double percent = 0;
    	public double avg = 0;
    	public byte letterGrade = 0;
    	public double q1 = 0;
    	public double q2 = 0;
    	public double m = 0;
    	public double f = 0;
    }
    
    package tangible;
    
    //----------------------------------------------------------------------------------------
    //	Copyright © 2006 - 2015 Tangible Software Solutions Inc.
    //	This class can be used by anyone provided that the copyright notice remains intact.
    //
    //	This class provides the ability to convert basic C++ 'cin' behavior.
    //----------------------------------------------------------------------------------------
    public final class ConsoleInput
    {
    	private static boolean goodLastRead = false;
    	public static boolean lastReadWasGood()
    	{
    		return goodLastRead;
    	}
    
    	public static String readToWhiteSpace(boolean skipLeadingWhiteSpace)
    	{
    		String input = "";
    		char nextChar;
    		while (Character.isWhitespace(nextChar = (char)System.in.read()))
    		{
    			//accumulate leading white space if skipLeadingWhiteSpace is false:
    			if (!skipLeadingWhiteSpace)
    			{
    				input += nextChar;
    			}
    		}
    		//the first non white space character:
    		input += nextChar;
    
    		//accumulate characters until white space is reached:
    		while (!Character.isWhitespace(nextChar = (char)System.in.read()))
    		{
    			input += nextChar;
    		}
    
    		goodLastRead = input.length() > 0;
    		return input;
    	}
    
    	public static String scanfRead()
    	{
    		return scanfRead(null, -1);
    	}
    
    	public static String scanfRead(String unwantedSequence)
    	{
    		return scanfRead(unwantedSequence, -1);
    	}
    
    	public static String scanfRead(String unwantedSequence, int maxFieldLength)
    	{
    		String input = "";
    
    		char nextChar;
    		if (unwantedSequence != null)
    		{
    			nextChar = '\0';
    			for (int charIndex = 0; charIndex < unwantedSequence.length(); charIndex++)
    			{
    				if (Character.isWhitespace(unwantedSequence.charAt(charIndex)))
    				{
    					//ignore all subsequent white space:
    					while (Character.isWhitespace(nextChar = (char)System.in.read()))
    					{
    					}
    				}
    				else
    				{
    					//ensure each character matches the expected character in the sequence:
    					nextChar = (char)System.in.read();
    					if (nextChar != unwantedSequence.charAt(charIndex))
    						return null;
    				}
    			}
    
    			input = (new Character(nextChar)).toString();
    			if (maxFieldLength == 1)
    				return input;
    		}
    
    		while (!Character.isWhitespace(nextChar = (char)System.in.read()))
    		{
    			input += nextChar;
    			if (maxFieldLength == input.length())
    				return input;
    		}
    
    		return input;
    	}
    }
    Note the heavy use of the static keyword. That is not considered good Java. So even well-written procedural C++ converted straight into Java will not be well received. If it is an assignment, you will not get a high grade, even if it works. You are supposed to leave "the static environment of main()" as quickly as possible and never look back.

  7. #7
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,860

    Re: Convert C++ Code to Java

    It's not even a 'correct' conversion. I used unsigned to remove the need to check for a value < 0 - but Java has gone back to using int so the checks for < 0 need to be re-instated.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  8. #8
    Join Date
    Feb 2017
    Posts
    674

    Re: Convert C++ Code to Java

    Quote Originally Posted by 2kaud View Post
    It's not even a 'correct' conversion. I used unsigned to remove the need to check for a value < 0 - but Java has gone back to using int so the checks for < 0 need to be re-instated.
    Oops! Well, converting between languages is a daunting task. Nevertheless, in this case, the converter should have issued a to-do warning (as I see it usually does when it omits something). Unsigned is not part of Java but is common in C++. Maybe it is better handled in the commercial version of the converter. However, I used the converter to show that a straight conversion of procedural C++ does not produce idiomatic Java. The static keyword becomes overused. And for this purpose, the converter worked.
    Last edited by wolle; November 27th, 2022 at 01:56 AM.

  9. #9
    Join Date
    Nov 2024
    Posts
    1

    Re: Convert C++ Code to Java

    To convert C++ code to Java, you'll need to make adjustments to syntax, libraries, and object-oriented structures. While both languages are similar in many ways, Java has some differences, such as automatic memory management (no pointers) and a different way to handle input/output. Key steps include:

    Replacing C++ headers with Java import statements.
    Converting main() method and class declarations.
    Adjusting data types (e.g., int remains the same, but cin in C++ becomes Scanner in Java).
    Using Java?s exception handling (try-catch blocks) instead of C++'s try-catch.
    If you're looking to learn more about Java, Java classes in Pune at SevenMentor offer expert training that can guide you through such conversions and more, helping you transition from C++ to Java seamlessly.
    Last edited by VictorN; November 19th, 2024 at 08:21 AM. Reason: Web link was removed.

  10. #10
    Join Date
    Feb 2024
    Posts
    9

    Re: Convert C++ Code to Java

    It's very hard to do this manually, so you better get on a convert or tell ChatGPT's

  11. #11
    Join Date
    Feb 2024
    Posts
    9

    Re: Convert C++ Code to Java

    Quote Originally Posted by 2kaud View Post
    It's not even that good C++ code... Perhaps 'better' C++:

    Code:
    #include <iostream>
    #include <iomanip>
    #include <string>
    
    struct StudentGrade {
    	unsigned quiz1 {};
    	unsigned quiz2 {};
    	unsigned midterm {};
    	unsigned final{};
    	unsigned total {};
    	std::string firstName;
    	std::string lastName;
    	double percent {}, avg {};
    	char letterGrade {};
    	double q1 {};
    	double q2 {};
    	double m {};
    	double f {};
    };
    
    StudentGrade getData();
    void setLetterGrade(StudentGrade&);
    void format(int);
    void output(const StudentGrade&);
    
    constexpr double Q_PERCENT { 12.5 };
    constexpr double M_PERCENT { 25.0 };
    constexpr double F_PERCENT { 50.0 };
    constexpr double Q_SCORE { 10 };
    constexpr double E_SCORE { 100 };
    
    constexpr auto tScore { Q_SCORE * 2 + E_SCORE * 2 };
    constexpr auto tPercent { Q_PERCENT * 2 + M_PERCENT + F_PERCENT };
    
    #define W std::setw(17)
    #define Y std::setw(10)
    
    int main() {
    	char run_again {};
    
    	do {
    		output(getData());
    
    		std::cout << "Would you like to try again for another student? ([Y]es/[N]o) : ";
    		std::cin >> run_again;
    	} while ((run_again == 'y') || (run_again == 'Y'));
    }
    
    void output(const StudentGrade& g) {
    	format(1);
    
    	std::cout << "\n\nHere are the results for " << g.firstName << " " << g.lastName << ".\n";
    	std::cout << Y << "TEST" << Y << "TEST" << Y << "MAX" << W << "GRADE SCORE"
    		<< W << "MAXIMUM SCORE" << '\n';
    	std::cout << Y << "PERIOD" << Y << "SCORE" << Y << "SCORE" << W << "DISTRIBUTION"
    		<< W << "DISTRIBUTION" << "\n\n";
    	std::cout << Y << "Quiz 1" << Y << g.quiz1 << Y << Q_SCORE << W << g.q1 << "%"
    		<< W << Q_PERCENT << "%\n";
    	std::cout << Y << "Quiz 2" << Y << g.quiz2 << Y << Q_SCORE << W << g.q2 << "%"
    		<< W << Q_PERCENT << "%\n";
    	std::cout << Y << "Midterm" << Y << g.midterm << Y << E_SCORE << W << g.m << "%"
    		<< W << M_PERCENT << "%\n";
    	std::cout << Y << "Final" << Y << g.final << Y << E_SCORE << W << g.f << "%"
    		<< W << F_PERCENT << "%\n";
    	std::cout << Y << "_________________________________________________ ______________________\n";
    	std::cout << Y << "TOTAL" << Y << g.total << Y << tScore << W << g.percent << "%"
    		<< W << tPercent << "%\n";
    
    	std::cout << Y << "Average" << Y << (double(g.total) / tScore * tPercent) << "%\n";
    	std::cout << Y << "Grade: " << Y << g.letterGrade << "\n\n\n";
    }
    
    StudentGrade getData() {
    	StudentGrade g;
    
    	std::cout << "Enter the student's first name: ";
    	std::cin >> g.firstName;
    
    	std::cout << "Enter the student's last name: ";
    	std::cin >> g.lastName;
    
    	std::cout << "Enter Quiz 1 score (maximum is 10): ";
    	std::cin >> g.quiz1;
    
    	std::cout << "Enter Quiz 2 score (maximum is 10): ";
    	std::cin >> g.quiz2;
    
    	std::cout << "Enter Midterm score (maximum is 100): ";
    	std::cin >> g.midterm;
    
    	std::cout << "Enter Final score (maximum is 100): ";
    	std::cin >> g.final;
    
    	g.quiz1 = g.quiz1 > 10 ? 10 : g.quiz1;
    	g.quiz2 = g.quiz2 > 10 ? 10 : g.quiz2;
    	g.midterm = g.midterm > 100 ? 100 : g.midterm;
    	g.final = g.final > 100 ? 100 : g.final;
    
    	g.q1 = g.quiz1 / Q_SCORE * Q_PERCENT;
    	g.q2 = g.quiz2 / Q_SCORE * Q_PERCENT;
    	g.m = g.midterm / E_SCORE * M_PERCENT;
    	g.f = g.midterm / E_SCORE * F_PERCENT;
    
    	g.total = g.quiz1 + g.quiz2 + g.midterm + g.final;
    	g.percent = g.q1 + g.q2 + g.m + g.f;
    
    	setLetterGrade(g);
    	return g;
    }
    
    void setLetterGrade(StudentGrade& g)
    {
    	if (g.percent >= 90.0)
    		g.letterGrade = 'A';
    	else if (g.percent >= 80.0)
    		g.letterGrade = 'B';
    	else if (g.percent >= 70.0)
    		g.letterGrade = 'C';
    	else if (g.percent >= 60.0)
    		g.letterGrade = 'D';
    	else
    		g.letterGrade = 'F';
    }
    
    void format(int n)
    {
    	std::cout.setf(std::ios::fixed);
    	std::cout.setf(std::ios::showpoint);
    	std::cout.precision(n);
    }
    [Excluding std::format from C++20]
    To make std disappear, put after libraries ,,using namespace std;'', when it's a big code this will make your work much easier

  12. #12
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,860

    Re: Convert C++ Code to Java

    To make std disappear, put after libraries ,,using namespace std;'', when it's a big code this will make your work much easier
    It's not suggested good practice to have 'using namespace std'. It's OK for small code (never in a header file) that doesn't use anything except std. Where additional libraries are used then you can get ambiguity with names - which will probably bite you at some point. To save having to keep writing std::cout, std::cin etc it's more usual to specifically have 'using std::cout', 'using std::cin' . If you start out not having 'using namespace std' then you don't get into this habit which will have to be 'un-learnt' later if you do professional programming.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured