Switched to BigInteger and progam does not run any more - java

So right I was creating a program that made palindromic numbers based on this project. My program would work for the smaller numbers, but integer can only compute a small amount of numbers, so I changed necessary integers to BigInteger(). After doing this Ive ran into some problems that Im not really sure of. Would anyone have any advice as to how to make this work?
public class Main {
public static final boolean DEBUG = false;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//gets the number from the console
int number = input.nextInt();
if(DEBUG) System.out.println("Got your number!");
if(DEBUG) System.out.println("Bout to makePalendrome!");
makePalendrome(number);
}
public static boolean isPalendrome(BigInteger number){
String numberString = number.toString();
for(int i = 0; i < numberString.length(); i++){
if(numberString.charAt(i) != numberString.charAt(numberString.length() - 1 - i)) return false;
}
return true;
}
public static void makePalendrome(int input){
int steps = 0;
BigInteger number = new BigInteger((input + ""));
if(isPalendrome(number)) printResult(input, steps, number);
while(!isPalendrome(number)){
String numberString = number.toString();
String reversed = "";
for(int i = 0; i < numberString.length(); i++){
reversed += numberString.charAt(numberString.length() - 1 - i);
}
BigInteger numReversed = new BigInteger(reversed);
number.add(numReversed);
steps++;
}
printResult(input, steps, number);
}
public static void printResult(int number, int steps, BigInteger palendrome){
System.out.printf("The number %d becomes palendromic after %d steps, and becomes the number: %d%n", number, steps, palendrome);
System.exit(0);
}
}

Your code goes into infinite loop while(!isPalendrome(number)) because,
number.add(numReversed);
this doesn't change the value of number. You need assign it back.
number= number.add(numReversed);

Related

How to determine why a Java program is not accepting 7 console inputs?

I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}

Get int variables within a String method Java

This is homework. Just going to put that out there. I feel it is best to show my code first and explain what I'm attempting to do
import java.util.Scanner;
public class Question1 {
public static void main(String[] args){
int length, odd, even, largest;
int n = getNumber();
length=odd=even=largest=initialize();
String sequence=createSequence(n, largest, odd, even, length);
displaySequence(sequence);
displayStatistics(largest, length, odd, even);
}
private static int getNumber(){
Scanner kb = new Scanner(System.in);
System.out.println("Enter the value of the number: ");
int number = kb.nextInt();
return number;
}
private static int initialize(){
return 0;
}
public static String createSequence(int n, int largest, int odd, int even, int length){
String sequence="";
sequence+=n+" ";
while (n!=1){
n = (n%2==0) ? n/2 : 3*n+1;
System.out.print(", "+n);
sequence+=n+" ";
if(n%2==0){ even++;
}else{ odd++;}
if(n>=largest){ largest = n;
}
length++;
}
return sequence;
}
private static void displaySequence(String sequence){
System.out.println(sequence);
}
public static String displayStatistics(int length, int even, int odd, int largest){
String nil = "";
System.out.println("The largest number in the sequence was "+largest);
System.out.println("The length of the sequence was "+length);
System.out.println("There were "+odd+" odd numbers");
System.out.println("There were "+even+" even numbers");
return nil;
}
}
I need attempting to display the largest number in the sequence, the length of the sequence, how many even numbers there were in the sequence and how many odd numbers there were in the sequence. But since I cannot return an int value in the createSequence method, I cannot get the new values for each statistic. Preventing me from displaying said statistics. How would I access these new variables to be used in the final method?
Note:
Requirements:
Declare variables in main
Initialize variables in Initialize()
createSequence (Create the sequence)
displaySequence (Then display the sequence in a separate method)
finally displayStatistics i.e. length, evens, odds, largest (in its own method), this is the one that's troubling me
Try reimplementing your code off of my basecode
public class Question{
public class NumberStats {
int len;
boolean isOdd;
}
private ArrayList<NumberStats> stats = new ArrayList<>();
public static void main(String[] args){
Question q = new Question();
Scanner kb = new Scanner(System.in);
String number = "";
do {
System.out.println("Enter a series of numbers or q to quit: ");
number = kb.next();
q.stats.add(q.parseNumber(number));
} while (number.equals("q")==false);
q.printSummary();
}
private void printSummary(){
int oddCount = 0;
int evenCount = 0;
int longestNumber = 0;
for (NumberStats s : stats){
if (longestNumber<s.len){
longestNumber = s.len;
}
if (s.isOdd){
oddCount+=1;
} else {
evenCount+=1;
}
}
System.out.println(String.format("Longest number length was : %i, Odd Numbers: %i, Even Numbers: %i",longestNumber,oddCount,evenCount));
}
private NumberStats parseNumber(String number){
NumberStats stats = new NumberStats();
Integer lastNumber = Integer.parseInt(String.valueOf(number.charAt(number.length()));
stats.isOdd = true;
if (lastNumber%2==0){
stats.isOdd = false;
}
stats.len = number.length();
return stats;
}
}
Your teacher may be a bit more impressed if you created a Sequence class. The class attributes would be the stats (which could be accessed via getter methods). The createSequence method would become the constructor. And you could implement a toString method to return a string representation of the contents.

Recursive methods which exclude each other?

I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;

How to avoid running my program 10 times for 10 answers?

Once I run my program, it works, but after I input my first integer, it stops returning boolean values and just reads my input back to me. I want it to read multiple integers and tell me if they are prime numbers, how would I do that?
import java.util.Scanner;
public class PrimeCalculator{
public static boolean IsPrimeNumber(int Number){ //Tells me if it's a prime number
int Num = Number;
int x = 0;
for (int i=0;i<=Num;i++){
if(Num%(i+1)==0){
x++;
}
}
Boolean TwoFactors = (x==2);
return TwoFactors;
}
public static void main(String[] args){ // this prints out true/false depending on input
System.out.println("Enter a number");
Scanner Reader = new Scanner(System.in);
int IntRead = Reader.nextInt();
System.out.println(IsPrimeNumber(IntRead));
}
}
you should use do-while loop
int counter = 0;
do
{
counter++;
int IntRead = Reader.nextInt();
System.out.println(IsPrimeNumber(IntRead));
}
while(counter < 10);
or the for loop version:
for(int i = 0; i < 10; i++)
{
int IntRead = Reader.nextInt();
System.out.println(IsPrimeNumber(IntRead));
}
in your main method

Creating a method with a for loop to find odd abundant sigma function numbers

I'm trying to create a method that will take a number and determine whether the number is an odd, abundant number with the sigma function. An abundant number is any number that when put into the sigma function generates a sum greater than the number given.
For instance, sigma(12) is abundant because sigma(12) = 1+2+3+4+6+12 = 28. However, it is not odd, so my method would not consider it. I can't figure out why my loop function isn't working , because when I try to input a range it spits up a bunch of number gibberish. Here's what I have so far:
import java.util.*;
public class OddAbundant {
static Scanner input = new Scanner(System.in);
public static void findOddAbundant(){
System.out.println("Please enter the start of the range you want to test for odd abundant integers");
int startRange = input.nextInt();
System.out.println("Please enter the end of the range you want to test for odd abundant integers");
int endRange = input.nextInt();
for(int b = startRange; b <= endRange; b++) {
if (Sigma.Sigma(b)<(b*2))
continue;
else{
if (b % 2 == 1)
System.out.println(b);
}
}
}
public static void main(String[] args) {
findOddAbundant();
}
}
I go through the loop and I can't figure out what's going wrong. I've tested the sigma method, which I can provide if it will help you guys, and it does spit out the correct value when given an integer. Thoughts?
Here is my sigma function:
import java.util.*;
public class Sigma {
static Scanner input = new Scanner(System.in);
public static int Sigma(int s){
int a = 0;
for(int i=1;i<=s;i++){
if(s%i==0)
a = a + i;
}
System.out.print(a);
return a;
}
public static void main(String[] args) {
System.out.println("Please enter the number you want to perform the sigma function on");
int s = input.nextInt();
Sigma.Sigma(s);
System.out.print(" is the sum of all the divisors of your input" );
}
}
The silly problem it was; remove the print statement from Sigma function.
public static int Sigma(int s){
int a = 0;
for(int i=1;i<=s;i++){
if(s%i==0)
a = a + i;
}
System.out.print(a); //why do you have it here?
return a;
}

Categories