Question
Explain this code, please. package lab3; import java.io.PrintStream; import java.util.Scanner; public class Lab3 { public static void main(String[] args) { Scanner in = new Scanner(System.in);
Explain this code, please.
package lab3;
import java.io.PrintStream;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
BasedNumber b1 = promptForNumber(in),
b2 = promptForNumber(in);
in.close();
System.out.printf("These numbers represent %s! ", b1.equals(b2)? "the same value" : "the different values");
}
private static BasedNumber promptForNumber(Scanner in) {
PrintStream out = System.out;
out.println("Enter a base: ");
int base = Integer.parseInt(in.nextLine());
out.printf("Enter base-%d digits (separated by space): ", base);
String[] digitStrings = in.nextLine().split(" ");
return new BasedNumber(base, parse(digitStrings));
}
private static int[] parse(String[] digitStrings) {
int[] digits = new int[digitStrings.length];
for(int i = 0; i digits[i] = Integer.parseInt(digitStrings[i]); } return digits; } } class BasedNumber { private int base; private int[] digits; BasedNumber(int base, int[] digits) { this.base = base; this.digits = digits; } int getBase() { return base; } int getDigit(int n) { return digits[n]; } int getValue() { int ret = 0; for(int i=0; i ret = ret * base + digits[i]; } return ret; } boolean equals(BasedNumber that) { return getValue() == that.getValue(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started