would someone kindly convert the following C code to java? thanks so much
# include <stdio.h> int main(void) { int changeOwed; int check; char invisibleChar; int count = 0; int numQ=0, numD=0, numN=0, numP=0; do{ printf("How much change is owed (in cents)?\n"); check = scanf("%d", &changeOwed); // returns 1 if the input is a number and returns 0 otherwise //Get's rid of any extra invisible characters if the input is a char/String do{ scanf("%c",&invisibleChar); }while(invisibleChar != '\n'); }while(check == 0 || !(changeOwed >=0 )); while(changeOwed > 0){ //Use as many quarters needed while(changeOwed >= 25){ count ++; numQ++; changeOwed = changeOwed - 25; } //Use as many dimes needed while(changeOwed >= 10){ count ++; numD++; changeOwed = changeOwed - 10; } //Use as many nickels needed while(changeOwed >= 5){ count ++; numN++; changeOwed = changeOwed - 5; } //Use as many pennies needed while(changeOwed >= 1){ count ++; numP++; changeOwed = changeOwed - 1; } } printf("Quarters: %d, Dimes: %d, Nickels: %d, Pennies: %d\nNumber of coins used= %d\n\n", numQ, numD, numN, numP, count); }
Ans:- Java code for the following c code.
import java.util.*;
public class Cent
{
//this function is used to check whether the input is integer or not
private static boolean checkInt(String x){
int y;
try{
y = Integer.parseInt(x);
return false;
}catch(NumberFormatException ex){
return true;
}
}
public static void main (String[] args)
{
int changeOwed=0;
String c;
boolean check;
int count = 0;
Scanner obj = new Scanner(System.in); //Scanner class is used to take input in java
int numQ=0, numD=0, numN=0, numP=0;
// it will run until user enter an integer
do{
System.out.print("How much change is owed (in cents)?");
c=obj.next(); //this statement will take input from user
check=checkInt(c); //check whether the input is integer or not
}while(check);
changeOwed=Integer.parseInt(c);
while(changeOwed > 0){ //this while loop remain same in java
//Use as many quarters needed
while(changeOwed >= 25){
count ++;
numQ++;
changeOwed = changeOwed - 25;
}
//Use as many dimes needed
while(changeOwed >= 10){
count ++;
numD++;
changeOwed = changeOwed - 10;
}
//Use as many nickels needed
while(changeOwed >= 5){
count ++;
numN++;
changeOwed = changeOwed - 5;
}
//Use as many pennies needed
while(changeOwed >= 1){
count ++;
numP++;
changeOwed = changeOwed - 1;
}
}
// the below statements are used to print the output
System.out.println("Quarters: "+numQ+", Dimes: "+numD+", Pennies: "+numP);
System.out.println("Number of coins used= "+count);
}
}
Output:-
Get Answers For Free
Most questions answered within 1 hours.