My factorial method is working correctly although I would like to change the output from just outputting the number and the factorial result. For example I would like if the user enters 6 for the output to say 6 * 5 * 4 * 3 * 2 * 1 = 720, instead of factorial of 6 is: 720.
int count, number;//declared count as loop and number as user input
int fact = 1;//declared as 1
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
System.out.println(number);//prints number the user input
if (number > 0) {
for (i = 1; i <= number; i++) {//loop
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
}
create a string and store the numbers.
try something like this.
int count, number;//declared count as loop and number as user input
String s; //create a string
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
int fact = number;//store the number retrieved
System.out.println(number);//prints number the user input
if (number > 0) {
s=String.valueOf(number);
for (int i = 1; i < number; i++) {//loop
fact = fact * i;
s = s +" * "+String.valueOf(number-i);
}
System.out.println(s+ " = " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
Check out this recursive approach: (check negative numbers yourself :D)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(getFactorialString(num, " = " + getFactorial(num)));
}
public static String getFactorialString(int num, String result) {
if (num == 0) return "0 => 1";
if (num == 1) {
result = "" + num + "" + result;
} else {
result = getFactorialString(num - 1, result);
result = "" + num + " x " + result;
}
return result;
}
public static int getFactorial(int num) {
if (num == 0) return 1;
return num * getFactorial(num - 1);
}
Related
I'm trying to solve this program using recursive function which is needed for our program. The program is converting a decimal number system from a decimal 16 divided to a base of 2 using recursion, but my problem is that instead of the expected output of 10000 somehow it is reversed into 00001.
public static void main(String[] args) {
int decimalValue = 0;
int targetBase = 0;
while (decimalValue != -1){
Scanner input = new Scanner(System.in);
System.out.print("Decimal value: ");
decimalValue = input.nextInt();
if (decimalValue == -1){
System.out.println("Thank you for using the program. bye!");
System.exit(0);
}
while (targetBase < 2 || targetBase > 16){
System.out.print("Target base: ");
targetBase = input.nextInt();
}
System.out.print("Value of " + decimalValue + " in base " + targetBase + " is ");
recursionFunction(decimalValue, targetBase);
targetBase = 0;
}
}
public static void recursionFunction(int Decimal, int Base){
int result,test1;
if (Decimal == 0) {
System.out.println(" " );
return;
}
result = Decimal / Base;
System.out.print(Decimal % Base);
recursionFunction(result, Base);
}
I'm fairly new to Java and the problem I am having is that this code compiles, but does not run after the hexadecimal conversion; it instead just ends after the method hexCharToDecimal. I can't reuse method main and I'm not sure how to call the method intreverse and actually have it run. Is there a way to get back into main or do I have to call intreverse somewhere?
import java.util.Scanner;
public class Homework4 {
public static void main(String[]args) {
// Sum and average of a set of intergers entered by the user
// First we will declare some variables
int userInput = 1;
int positives = 0;
int negatives = 0;
int sum = 0;
int numCount = 0;
Scanner input = new Scanner(System.in);
// Will start a while loop that will stop when user enters 20 integers
while ((numCount <= 20)) {
System.out.println("Please enter a nonzero integer or enter 0 to finish ");
userInput = input.nextInt();
if (userInput == 0) {
break;
} else if (userInput > 0) {
positives += 1;
numCount += 1;
sum = sum + userInput;
} else if (userInput < 0) {
negatives += 1;
numCount += 1;
sum = sum + userInput;
} else
System.out.println("Error, please enter an integer");
continue;
}
double average = (sum / numCount);
System.out.println("The sum of the entered integers is " + sum);
System.out.println("The average of the enetered integers is " + average);
System.out.println("There are " + positives + " positive integers and " + negatives + " negative integers");
// Convert Hexadecimal number to decimal
// Ask the user to input a string of 5 digits or less in hex
System.out.println("Please enter a hexadecimal number of up to 5 characters");
String hex = input.next();
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
}
// Now we will create the method to convert to decimal
public static int hexToDecimal(String hex) {
int decimal = 0;
for (int i = 0; i < hex.length(); i++) {
char hexcharacter = hex.charAt(i);
decimal = decimal * 16 + hexCharToDecimal(hexcharacter);
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') // check to see if there is any letters in the string
return 10 + ch - 'A';
else
return ch - '0';
}
// Print entered integer in reverse
public static void intreverse(String[]args) {
// Ask user for an integer to be reversed
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer to be reversed");
int number = input.nextInt();
reverse(number); // Method to be called
}
// Will now state our method
public static void reverse(int number) {
// use a while loop to get each digit
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
}
}
}
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
Will always run once because it is not enclosed in any sort of loop. If you want it to run again when the second case is called then enclose it in a while(true) loop and have a break statement in the first case where you want it to stop execution.
New to programming here. I need to write application that does the following...
Squaring application instructions
The code I have so far follows. I am running into a problem where my code will not read from negative integers to strings and properly prompt the user to enter valid data. I believe I need to nest my loops but am having trouble doing so. Any help would be greatly appreciated. Thanks.
import java.util.Scanner;
public class Squaring {
public static int getValidInt(int greaterThan, Scanner scan) {
System.out.println("Enter an integer greater than " + greaterThan + ":" );
int input;
while ( !scan.hasNextInt() ) {
String garbage = scan.next();
scan.nextLine();
System.out.println(garbage + " is not valid input.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
while ( !((input = scan.nextInt()) > greaterThan )) {
int garbage = input;
System.out.println(garbage + " is not greater than 1.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 1 ;
int total = 0;
a = getValidInt(a,scan);
int b = a;
System.out.println(a);
long n = a;
while ( n < 1000000 ) {
System.out.println(n*n);
n = n * n;
total = total + 1;
}
System.out.println(b + " exceeded 1,000,000 after " + total + " squarings.") ;
}
}
Without any try-catch:
public static int getValidInt(int greaterThan, Scanner scan) {
int input = 0;
boolean valid = false;
while (!valid) {
System.out.println("Enter an integer greater than " + greaterThan + ":");
if (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
} else {
input = scan.nextInt();
if (input <= greaterThan) {
System.out.println(input + " is not greater than " + greaterThan);
} else {
valid = true;
}
}
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = getValidInt(1, scan);
System.out.println(a);
int total = 0;
long n = a;
while ( n < 1000000 ) {
n = n * n;
System.out.println(n);
total++;
}
System.out.println(a + " exceeded 1,000,000 after " + total + " squarings.") ;
}
I've come up with the following:
public static int getValidInt(int greaterThan, Scanner scan) {
int number = greaterThan;
do {
while (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
}
number = scan.nextInt();
if (number < greaterThan) {
System.out.println("input is: " + number + " minimum is: " + greaterThan);
}
} while (number < greaterThan);
return number;
}
It has a do while loop which makes sure number cannot be smaller than greaterThan, if it is it will do the while loop again.
Inside the do while loop is another loop which tells the user that their input is garbage, and will continue doing so until a number is inserted.
In this java program you (the user) keeps entering numbers until you enter a zero, which is when the list terminates. It will compute the sum of positive even & sum of odd even and negative numbers. It will also compute the average.
I'm stuck at the part to get the average of sum of even positive numbers, sum of odd positive numbers, and sum of negative numbers.
import java.util.*;
class sumPositiveAverage {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println ("Enter numbers. List terminates when you enter a zero.
Enter a zero when you want to begin the addition.");
int a = sc.nextInt();
int esum=0;
int osum=0;
int nsum=0;
while (a !=0)
{
if (a>0)
{
if (a%2==0)
{
esum = esum+a;
}// end of 3rd innermost if statement
else
{
osum = osum+a;
}// end of 3rd else statement
}//end of 2nd middle if-else-loop
else if (a<0)
{
nsum=nsum+a;
}//end of 2nd middle else statement
}//end of while loop
System.out.println ("The sum of even positive numbers is "+esum);
System.out.println ("The sum of odd positive numbers is "+osum);
System.out.println ("The sum of negative numbers is "+nsum);
}//end of main
}//end of class2
import java.util.*;
public class sumPositiveAverage {
public static void main(String[] args)
{
int sum_even = 0;
int sum_odd = 0;
int sum_negative = 0;
int sum_positive = 0;
int count_even = 0;
int count_odd = 0;
int count_negative = 0;
int count_positive = 0;
double avg_sum_even = 0;
double avg_sum_odd = 0;
double avg_sum_negative = 0;
double avg_sum_positive = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
int data = 0;
do
{
System.out.print("Type in a positive or negative number and press enter key, if 0 is entered program stops: ");
data = input.nextInt();
if(data > 0){
if(data%2 == 0){
//even number
sum_even = sum_even + data;
count_even++;
}else{
//odd
sum_odd = sum_odd + data;
count_odd++;
}
sum_positive = sum_positive + data;
count_positive++;
}else if(data < 0) {
//negative number
sum_negative = sum_negative + data;
count_negative++;
}
}
//Stops if the value of data is ZERO(0) and continues if it's not
while(data != 0);
//here means zero has been entered
if(count_positive > 0) { avg_sum_positive = (double)sum_positive/count_positive; }
if(count_negative > 0) { avg_sum_negative = (double)sum_negative/count_negative; }
if(count_even > 0) { avg_sum_even = (double)sum_even/count_even; }
if(count_odd > 0) { avg_sum_odd = (double)sum_odd/count_odd; }
System.out.println("Sum of Positive Numbers = " + sum_positive);
System.out.println("Sum of negative Numbers = " + sum_negative);
System.out.println("Sum of odd Numbers = " + sum_odd);
System.out.println("Sum of even Numbers = " + sum_even);
System.out.println("Count of Positive Numbers = " + count_positive);
System.out.println("Count of negative Numbers = " + count_negative);
System.out.println("Count of odd Numbers = " + count_odd);
System.out.println("Count of even Numbers = " + count_even);
System.out.println("Average of Positive Numbers = " + avg_sum_positive);
System.out.println("Average of negative Numbers = " + avg_sum_negative);
System.out.println("Average of odd Numbers = " + avg_sum_odd);
System.out.println("Average of even Numbers = " + avg_sum_even);
}//closing main
} // closing class
I am trying to have the code listed below receive an int input from user, then find amount of even numbers in that int. I'm getting an error when I try to print the return... any help?
import java.util.Scanner;
public class evenDigits {
public static int countEvenDigits(int number){
if (number == 0)
return 0;
else{
int lastDigit = number % 10;
int result = countEvenDigits(number / 10);
if (lastDigit % 2 == 0)
return result + 1;
else
return result;
}
}
public static void main(String[] args) {
System.out.println("Please enter an integer.");
Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt();
countEvenDigits(number);
System.out.println("There are " + result + " even digits in " + number);
}
}
Specifically, there is an error in this statement:
System.out.println("There are " + result + " even digits in " + number);
In main you need to change:
countEvenDigits(number);
to:
int result = countEvenDigits(number);
Otherwise, you're accessing a nonexistent variable in your println