Skip to main content

Java to c++ converter

This is an basic java to c++ code converter which is capable to convert some special code into well c++ code.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment






Krishna     Today
yoooo
Dddd     4 Day ago
// Include header file
#include <iostream>
#include <string>
#include <vector>

class mowing
{
    public:
    static void main(std::vector<std::string> &args) throws IOException
    {
        // initialize file I/O
        BufferedReader br =  java.io.BufferedReader( java.io.FileReader("mowing.in"));
        PrintWriter pw =  java.io.PrintWriter( java.io.BufferedWriter( java.io.FileWriter("mowing.out")));
        // 		 * Create a two-dimensional array where lastTime[i][j] stores the last time
        // 		 * that Farmer John visited point (i, j). If Farmer John has never visited that
        // 		 * point, then lastTime[i][j] == -1.
        std::vector<std::vector<int>> lastTime(2001,std::vector<int>(2001));
        for (int i = 0; i < lastTime.size(); i++)
        {
            for (int j = 0; j < lastTime[i].size(); j++)
            {
                lastTime[i][j] = -1;
            }
        }
        // (currX, currY) is the point that Farmer John is currently at.
        int currX = 1000;
        int currY = 1000;
        lastTime[currX][currY] = 0;
        int currentTime = 0;
        // the longest period of time cannot exceed 1000, so if it is still 1001, he never visits the same square twice.
        int answer = 100 * 10 + 1;
        // read in N
        int n = stoi(br.readLine());
        for (int i = 0; i < n; i++)
        {
            StringTokenizer st =  java.util.StringTokenizer(br.readLine());
            // read in the direction that Farmer John goes in
            std::string direction = st.nextToken();
            int dirX = 0;
            int dirY = 0;
            if ((direction.compare("N") != 0))
            {
                dirX = -1;
            }
            else if ((direction.compare("S") != 0))
            {
                dirX = 1;
            }
            else if ((direction.compare("W") != 0))
            {
                dirY = -1;
            }
            else 
            {
                dirY = 1;
            }
            // read in the number of steps he travels
            int numSteps = stoi(st.nextToken());
            // travel that many steps
            for (int j = 1; j <= numSteps; j++)
            {
                currX += dirX;
                currY += dirY;
                currentTime++;
                // check if Farmer John has visited that square before, and the amount of time that has elapsed since then if valid
                if (lastTime[currX][currY] >= 0 && currentTime - lastTime[currX][currY] < answer)
                {
                    answer = currentTime - lastTime[currX][currY];
                }
                lastTime[currX][currY] = currentTime;
            }
        }
        // check if he has never visited the same square twice
        if (answer == 1001)
        {
            answer = -1;
        }
        // print the answer
        pw.println(answer);
        // close file I/O
        pw.close();
    }
};
int main(int argc, char **argv){
	std::vector<std::string> parameter(argv + 1, argv + argc);
	mowing::main(parameter); 
	return 0;
};
Kiana     5 Day ago
public class LIS {
 public static void main(String[] args){

 int[] nums = {1,3,2,9,6,10,5};
 printLIS(nums);
 }

	//main function
	public static void printLIS(int[] nums){
	
	//creating size and path array
	String[] paths = new String[nums.length];
	int[] sizes = new int[nums.length];

//Initially, assign sizes and path position
for(int i=0; i<nums.length; i++){
	sizes[i] = 1;
	paths[i] = nums[i] + " " ;
}

//Creating maxLenth to keep track
int maxLength = 1; 

for(int i=1; i<nums.length; i++){ 
	for(int j=0; j<nums.length; j++){
// i at firstposition	
// j at zeroposition 

//here j<i and size must be increasing
if(nums[i]>nums[j] && sizes[i] < sizes[j] + 1){;
	//if so, we need to update sizes and path
	sizes[i] = sizes[j] + 1;
	paths[i] = paths[j] + nums[i] + " "; 
	// append current values to end!!
	
	if(maxLength < sizes[i])
		maxLength = sizes[i];
	}
   }
}

// finally go scanning the size of array again and print out the path when size matches
  for(int i=1; i<nums.length; i++){
    if(sizes[i] == maxLength)
	System.out.println("LIS: " + paths[i]);
  }
 }
}
Ab     15 Day ago
Required function definitions
function calculateSpeed(en_time, ex_time) 
{ 
 return (25/((ex_time-en_time)/60))
}

function calculatePercentage(num_violations, num_cars){
 return 100*(num_violations/num_cars) 


violations= 0 
for (let i=0; i < 10; i++){
 s= prompt("Enter entry time of vehicle ${i+1} (minutes):" )
 e= prompt("Enter exit time of vehicle ${i+1} (minutes):" )
 avg_speed= calculateSpeed(s,e);
 if (avg_speed>=130){
 
}
violations_percent= calculatePercentage(violations, 10)
if(violations_percent<20){
 console.log("The new speed control system was effective as violations were below 20%")
 alert("The new speed control system was effective as violations were below 20%")
}
else{
 console.log("The new speed control system was not effective as violations exceeded 20%")
 alert("The new speed control system was not effective as violations exceeded 20%")
}
Zahra Malik     39 Day ago

    Scanner keyboard = new Scanner(System.in);
    int studentVisitCount = 0;
    cout<<"Enter the number of lockers: "<<endl;
    int numberOfLockers = keyboard.nextInt();
    for (int x = 1; x <= numberOfLockers; x++)
     {
        for (int y = 1; y <= x; y++) {
            if (x % y == 0) {

                studentVisitCount++;
            }
        }
    }
    cout<<"The number of lockers and students are: " + numberOfLockers);
    if (studentVisitCount % 2 == 0) {
        System.out.print(studentVisitCount + " ");
        System.out.println("The locker numbers of lockers that are left open at the end of the game are: ");
    }
}
}

for(int j=1; j <= number; j++)

If i is divisible by j, it means locker number i is visited by student number j

if((i % j)==0)



numberOfDivisors++;

If number of students visiting a locker is odd then it is open, otherwise it is closed.

if (( numberOfDivisors % 2)!=0 )



System.out.println("Locker " + i+ " is open.");

} // end of outer loop
Zicong Hua     43 Day ago
def printName(nameArray):
    if(len(nameArray[1])>0):
        fistIn=nameArray[1][0]
    if(len(nameArray[2])>0):
        midlleIn=nameArray[2][0]
    print(nameArray[0],", ",fistIn,".",midlleIn,".")

name=input("enter the name:")
nameArray=name.split(" ")
printName(nameArray) 
Tony     57 Day ago
import java.util.* ;
import java.io.*; 
public class Solution {
    public static boolean areAnagram(String str1, String str2){
               int sum1=0;
       int sum2=0;
       if(str1.length()!=str2.length())
           return false;
       
       if(!str2.contains(str1.substring(0,1)))
           return false;
       for(int i=0;i<str1.length();i++){
           sum1+=str1.charAt(i);
       }
       for(int i=0;i<str2.length();i++){
           sum2+=str2.charAt(i);
       }
       if(sum1==sum2)
           return true;
       else
           return false;
    }
}
Kalkicode     66 Day ago
Ayxan [Change your code before translate]

import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Comparator;
public class Main
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		PriorityQueue < Integer > pq = new PriorityQueue < Integer > (10, new Comparator < Integer > ()
		{
			@Override
			public int compare(Integer o1, Integer o2)
			{
				return o2 - o1;
			}
		});
		Stack < Integer > s = new Stack < Integer > ();
		Queue < Integer > q = new LinkedList < Integer > ();
		boolean pqb, sb, qb;
		while ( in .hasNextInt())
		{
			pqb = true;
			sb = true;
			qb = true;
			pq.clear();
			s.clear();
			q.clear();
			for (int i = in .nextInt(); i > 0; i--)
			{
				int t = in .nextInt(), v = in .nextInt();
				if (t == 1)
				{
					if (pqb) pq.add(v);
					if (sb) s.push(v);
					if (qb) q.add(v);
				}
				else
				{
					if (pqb) try
					{
						pqb = v == pq.poll();
					}
					catch (Exception e)
					{
						pqb = false;
					}
					if (sb) try
					{
						sb = v == s.pop();
					}
					catch (Exception e)
					{
						sb = false;
					}
					if (qb) try
					{
						qb = v == q.poll();
					}
					catch (Exception e)
					{
						qb = false;
					}
				}
			}
			String typ;
			if (sb && !pqb && !qb) typ = "stack";
			else if (!sb && pqb && !qb) typ = "priority queue";
			else if (!sb && !pqb && qb) typ = "queue";
			else if (!sb && !pqb && !qb) typ = "impossible";
			else typ = "not sure";
			System.out.println(typ);
		}
	}
}


-------------------------
This work but note that not 100% accurate.
We check result like this.

// Include header file
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <list>
/* This class are provide by kalkicode.com (java to c++) */

class Settlement {
	public:
	// returns a value of standard input in c++
	template < typename T > static T input() {
		T value;
		std::cin >> value;
		return value;
	}
};
class Main
{
    public:
    static void main(std::vector<std::string> &args)
    {
        Scanner in =  java.util.Scanner(java.io.BufferedInputStream@7c53a9eb);
        java.util.PriorityQueue pq = java.util.PriorityQueue(10, new java.util.Comparator(){
        int compare(int &o1, int &o2)
        {
            return o2 - o1;
        }
});
        stack<int> s = stack<int>();
        std::list<int> q = std::vector<int>();
        bool pqb;
        bool sb;
        bool qb;
        while (in.hasNextInt())
        {
            pqb = true;
            sb = true;
            qb = true;
            pq.clear();
            s.clear();
            q.clear();
            for (int i = Settlement::input<int>(); i > 0; i--)
            {
                int t = Settlement::input<int>();
                int v = Settlement::input<int>();
                if (t == 1)
                {
                    if (pqb)
                    {
                        pq.add(v);
                    }
                    if (sb)
                    {
                        s.push(v);
                    }
                    if (qb)
                    {
                        q.push_back(v);
                    }
                }
                else 
                {
                    if (pqb)
                    {
                        try
                        {
                            pqb = v == pq.poll();
                        }catch (Exception e)
                        {
                            pqb = false;
                        }
                    }
                    if (sb)
                    {
                        try
                        {
                            sb = v == s.pop();
                        }catch (Exception e)
                        {
                            sb = false;
                        }
                    }
                    if (qb)
                    {
                        try
                        {
                            qb = v == q.pop_front();
                        }catch (Exception e)
                        {
                            qb = false;
                        }
                    }
                }
            }
            String typ;
            if (sb && !pqb && !qb)
            {
                typ = "stack";
            }
            else if (!sb && pqb && !qb)
            {
                typ = "priority queue";
            }
            else if (!sb && !pqb && qb)
            {
                typ = "queue";
            }
            else if (!sb && !pqb && !qb)
            {
                typ = "impossible";
            }
            else 
            {
                typ = "not sure";
            }
            std::cout << typ << std::endl;
        }
    }
};
int main(int argc, char **argv){
	std::vector<std::string> parameter(argv + 1, argv + argc);
	Main::main(parameter); 
	return 0;
};

// You will need to change the code manually
Ayxan     83 Day ago
import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o2 - o1;
      }
    });
    Stack<Integer> s = new Stack<Integer>();
    Queue<Integer> q = new LinkedList<Integer>();
    boolean pqb, sb, qb;
    while(in.hasNextInt()) {
      pqb = true; sb = true; qb = true;
      pq.clear(); s.clear(); q.clear();
      for(int i=in.nextInt(); i>0; i--) {
        int t = in.nextInt(), v = in.nextInt();
        if(t == 1) {
          if(pqb) pq.add(v);
          if(sb) s.push(v);
          if(qb) q.add(v);
        } else {
          if(pqb) try { pqb = v == pq.poll(); } catch (Exception e) { pqb = false; }
          if(sb) try { sb = v == s.pop(); } catch (Exception e) { sb = false; }
          if(qb) try { qb = v == q.poll(); } catch (Exception e) { qb = false; }
        }
      }
      String typ;
      if(sb && !pqb && !qb) typ = "stack";
      else if(!sb && pqb && !qb) typ = "priority queue";
      else if(!sb && !pqb && qb) typ = "queue";
      else if(!sb && !pqb && !qb) typ = "impossible";
      else typ = "not sure";
      System.out.println(typ);
    }
  }
}
Ayxan     83 Day ago
please convert the code
Lyn     99 Day ago
import java.util.Scanner;

public class Ejercicio7 {
    public static int ingresarEntero(String mensaje, int min, int max) {
        Scanner ingreso = new Scanner(System.in);
        int dato;
        do {
            System.out.println(mensaje +" entre "+min +" y "+max);
            dato = ingreso.nextInt();
        } while (dato < min || dato > max);
        return dato;
    } 
     public static String ingresarString(String mensaje){
        Scanner ingreso=new Scanner(System.in);
        String texto=""; 
        System.out.println(mensaje);
        texto= ingreso.nextLine();
        return texto;
    }   
    public static void main(String[] args) {
        int resp=0, num=0 ,grado=0,op=0;
        Lista coleccion=new Lista();
        Scanner Entrada= new Scanner(System.in);
        do{
            System.out.println("1-->Ingresar terminos \n2-->Reemplazar terminos(varios valores)\n3-->reemplazar con un valor determinado\nSeleccione una: ");
            op=Entrada.nextInt();
            switch(op){
                
                case 1:{
                    do{
                       coleccion.agregarNodoAlFinal(new Numero(ingresarString("Ingrese el signo del termino \n Positivo --> +\n Negativo --> -"),
                               ingresarEntero("Ingrese el termino: ",1,100),
                               ingresarEntero("Ingrese el grado deltermino ",0,100)));
                       System.out.println("¿Desea ingresar un termino adicional?");
                       resp=Entrada.nextInt();
                    }while(resp!=0);
                    coleccion.recorreLista();
                    }
                    break;
                case 2:
                    coleccion.reemplazo(0.5);
                    coleccion.reemplazo(1.0);
                    coleccion.reemplazo(1.5);
                    coleccion.reemplazo(2.0);
                    coleccion.reemplazo(2.5);
                    coleccion.reemplazo(3.0);
                    coleccion.reemplazo(3.5);                 
                    coleccion.reemplazo(4.0);
                    coleccion.reemplazo(4.5);
                    coleccion.reemplazo(5.0);
                    break;
                case 3:
                    coleccion.reemplazo(ingresarEntero("Ingrese un numero ",-100,100));
                    break;
            }
        System.out.println("\n¿Desea ingresar otro termino? 1--->Si 0--->No");
        resp=Entrada.nextInt();
        }while(resp!=0);
        System.out.println("\nEl polinomio es: ");
        coleccion.recorreLista();
    }
    
} 



Clase Lista


 import static java.lang.Math.pow;

public class Lista {
    Nodo inicio;
    Nodo fin;
     public void agregarNodoAlFinal(Numero obj){
       Nodo nuevo=new Nodo(obj);
        Nodo reco1;
        Nodo reco2;
        if(inicio==null){
            inicio=nuevo;
            nuevo.setSiguiente(null);
        }else{
            reco1=inicio;
            while(reco1!=null){
                reco2=reco1.getSiguiente();
                if(nuevo.getNum().getGrado()>=reco1.getNum().getGrado()){
                    nuevo.setSiguiente(inicio);
                    inicio=nuevo;
                    break;
                }else{
                    if(nuevo.getNum().getGrado()nuevo.getNum().getGrado()&&reco2.getNum().getGrado()<=nuevo.getNum().getGrado()){
                            reco1.setSiguiente(nuevo);
                            nuevo.setSiguiente(reco2);
                            break;
                        }else{
                            reco1=reco1.getSiguiente();
                        }
                    }
                }
            }
        }
    }
    public void recorreLista(){
        Nodo aux=inicio;
        while(aux!=null){
            if(aux.getNum().getGrado()>=1){
                System.out.printf(aux.getNum().getSigno()+aux.getNum().getNum()+"x^"+aux.getNum().getGrado());
                aux=aux.getSiguiente();
            }else{
                System.out.printf(aux.getNum().getSigno()+aux.getNum().getNum());
                aux=aux.getSiguiente();
            }
        }
        System.out.println("\n");
    }
    public void reemplazo(double n){
        Nodo aux=inicio;
        int r=0;
        double exp=0, re=0, base=0, acu=0;
        while(aux!=null){
            base=(double)aux.getNum().getNum();
            exp=(double)aux.getNum().getGrado();
            re= pow(n,exp);
            if(aux.getNum().getSigno().compareTo("+")==0){
                acu=acu+(base*re);
            }
            if(aux.getNum().getSigno().compareTo("-")==0){
                acu=acu-(base*re);
            }
            aux=aux.getSiguiente();
        }
        System.out.printf("\nEl resultado del reemplazo de: "+"f("+n+")=");
        recorreLista();
        System.out.printf("f("+n+")= "+acu);
    }
} 



Clase Nodo


public class Nodo {
    Numero num;
    Nodo Siguiente;

    public Nodo(Numero num) {
        this.num = num;
    }
    public Numero getNum() {
        return num;
    }
    public void setNum(Numero num) {
        this.num = num;
    }
    public Nodo getSiguiente() {
        return Siguiente;
    }
    public void setSiguiente(Nodo Siguiente) {
        this.Siguiente = Siguiente;
    } 
} 

 
Clase Número


public class Numero {
    String signo;
    int num;
    int grado;
    public Numero(String signo, int num, int grado) {
        this.signo = signo;
        this.num = num;
        this.grado = grado;
    }
    public String getSigno() {
        return signo;
    }
    public void setSigno(String signo) {
        this.signo = signo;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public int getGrado() {
        return grado;
    }
    public void setGrado(int grado) {
        this.grado = grado;
    }
}

Lani     101 Day ago
package bol01ej02;
public class Main {
public static void main(String[] args) {
double a,r; // área y radio
System.out.print("Introduce el radio de un circulo: ");
r=Entrada.real();
a=Math.PI*(r*r); // para elevar al cuadrado otra opción es: Math.pow (r, 2)
System.out.println("El área de una circunferencia de radio " + r+ " es: " + a);
Lani     101 Day ago
package bol01ej02;
public class Main {
public static void main(String[] args) {
double a,r; // área y radio
System.out.print("Introduce el radio de un circulo: ");
r=Entrada.real();
a=Math.PI*(r*r); // para elevar al cuadrado otra opción es: Math.pow (r, 2)
System.out.println("El área de una circunferencia de radio " + r+ " es: " + a);
}
}
Musa     104 Day ago
// file : Test.java
import java.util.*;
class Solution {
    public int solution(int X, int[] A) {
        // write your code in Java SE 8
        Set<Integer> set = new LinkedHashSet();
        int i;
        for(i=1;i<=X;i++){
            set.add(i);
    }
    for(i=0;i<A.length;i++){
        if(set.contains(A[i])) set.remove(A[i]);
        if(set.size()==0) break;
}
 return set.size()==0?i:-1;
}
}
// Write note here