# Java Programming > Java Programming >  Convert C++ Code to Java

## ForgottenLaw

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);
}

----------


## 2kaud

What part of the C++ code don't you understand?

----------


## wolle

> 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.

----------


## 2kaud

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.

----------


## 2kaud

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



```
#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]

----------


## wolle

> 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:



```
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.

----------


## 2kaud

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.

----------


## wolle

> 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.

----------

