First, the program must prompt the user to enter the number, the root to be calculated, and the number of decimal digits. The user prompts must look exactly like the text shown below. There must be exactly one space (and no linefeed) after the colon. The printf for the prompt does not include a linefeed; we want the user to type the value on the same line, and the user will type a linefeed as part of the input, which result in the next prompt being printed on the next line. In the example below, the numbers in bold are entered by the user, not printed by the program. The user types a linefeed (the Enter key) after each number. Number: 2 Root: 2 Digits: 3 Next, print a restatement of the problem, in the following form: Compute root 2 of 2 to 3 digits. Of course, the numbers will depend on what is entered by the user. There is a period at the end of the sentence, and a linefeed. Next, print an empty line, and then print the number of n-digit groups that are in the integer. Number has 1 groups of 2 digits.
How would I go about writing a loop to calculate the amount of groups of digits?
Answer:
Java Source Code:
import java.io.*;
import java.util.*;
class Main
{
static int amount_of_groups(int pos, int prev_sum, int len, String number)
{
if (pos == len)
return 1;
int result = 0, sum = 0;
for (int i = pos; i < len; i++)
{
sum += (number.charAt(i) - '0');
if (sum >= prev_sum)
result = result + amount_of_groups(i + 1, sum, len, number);
}
return result;
}
public static void main (String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.printf("Number: ");
String number = sc.nextLine();
System.out.printf("Root: ");
String root = sc.nextLine();
System.out.printf("Digits: ");
String digit = sc.nextLine();
System.out.println("Compute root "+number+" of "+root+" to "+digit+" digits.");
System.out.println();
int length = number.length();
System.out.println("Number has "+amount_of_groups(0, 0, length, number)+" groups of "+number+" digits.");
}
}
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 1 images