do
{
System.out.println("Enter either limit, abundant, deficient, perfect, or prime = value:");
condition = scan.next();
String equals = scan.next();
num = scan.next();
value=Integer.parseInt(num);
if (Type.isInteger(condition) || !Type.isInteger(num) || value<0)
System.out.println("Please enter in condition = value format");
else
break;
}while(stop);
System.out.println("N" + "\t" + "Abundant" + " " + "Deficient" + " " + "Perfect" + " " + "Prime");
sigma = 0; //sets sigma=0
n=1;
while (stop)
{
for (f = 1; f <= n/2; f++)
{
if (n % f == 0)
sigma = sigma + f;
}
System.out.print(n + "\t");
if (sigma>n)
acount++;
if (sigma == 1)
p++; //prime counter
if (sigma<n)
dcount++; //deficient counter
if (sigma == n)
pcount++; //perfect counter
System.out.print(acount + " " + "\t" + " " + dcount + "\t" + " " + pcount + "\t" + " " + p); //prints abundant column
System.out.println();
if (condition.equals("limit"))
{
if(n<value)
n++;
else
break;
}
if(condition.equals("abundant"))
{
if(acount<value)
n++;
else
break;
}
if (condition.equals("deficient"))
{
if (dcount<value)
n++;
else
break;
}
if (condition.equals("perfect"))
{
if (pcount<=value)
n++;
else
break;
}
if (condition.equals("prime"))
{
if (p<value)
n++;
else
break;
}
}
}
}
Essentially, the code is supposed to print out 5 columns: n, abundant, deficient, perfect, and prime. And each row will have a column of numbers under it. The user is supposed to type in specifications in a 'condition = value' format. So if they type in limit = 10 then it will print 10 rows. And if they input abundant = 10 then it will continue to print rows until the value of abundant reaches 10. The problem I am encountering is that my program will infinity loop when I input certain values and I am not sure what the cause is. For example, if I input deficient = 2 it will work fine but if I input deficient = 10 then it will start an infinite loop. However, when I input perfect = 10 it will only print out 1 row. Like my title says I am a beginner and I can't figure out what is causing the error. Any suggestions?
Try initializing the value of sigma inside the loop:
while (stop)
{
sigma = 0;
...
}
Since sigma is never reset to zero, it just keeps growing for every number. So you will quickly stop finding deficient numbers or perfect numbers, and everything will be be abundant. That's why the abundant keyword works, but deficient does not.
Related
Problem while entering a 3 digit no and getting no result. after entering 123 and when 2 is detected as even, and if user enters 7, it should display 173. but the program is immediately ending. It might be a problem in the last 0 check if-block. but removing it also doesn't help. Thanks in advance!
// in 3 dig, check even dig., replace them with odd and disp.
import java.util.*;
public class p24123 {
public static void main(String[] args) {
int n,h,t,o,m,z=0,z1=0,z2=0,fn;
Scanner ob = new Scanner(System.in);
n=ob.nextInt();
if(n>99&&n<1000){
h= n/100;
o=n%10;
m=n/10;
t=m%10;
if(h%2==0){
z=h;
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit"+h+" with \n");
z=ob.nextInt();
if(z%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z=h;
}
else if(t%2==0) {
System.out.println("Condition enter bokachpda");
z1 = t;
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit" + t + " with \n");
z1 = ob.nextInt();
if (z % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
z1 = t;
}
}
else if(o%2==0){
z2=o;
System.out.println("Enter the odd number you would like to replace the EVEN one's digit"+h+" with \n");
z2=ob.nextInt();
if(z2%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z2=o;
}
}
else if(2==2){
if(h<1||t<1||o<1||z<1||z1<1||z2<1){
System.out.println("Error");
System.exit(0);
}
}
fn=z*100+z1*10+z;
}
}
}
}
Here's your code cleaned up and fixed. I modified as little as possible to keep it at a level a beginner would be comfortable with. Some improvements to be made:
Repeated code like this screams, "Put me in my own function!"
A loop can be used to handle any number of digits, not just three.
Error checking/handling. You should handle bad input. What if the user enters "hello" instead of a number?
Improvements I made:
Your original code never printed a result.
Better formatting. It makes the code easier to read.
Descriptive variable names!
Scanner ob = new Scanner(System.in);
int n = ob.nextInt();
if (n > 99 && n < 1000) {
int hundredsDigit = n / 100;
int tensDigit = n / 10 % 10;
int onesDigit = n % 10;
if (hundredsDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit " + hundredsDigit +" with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
hundredsDigit = replacementDigit;
}
}
if (tensDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit " + tensDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
tensDigit = replacementDigit;
}
}
if (onesDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN one's digit " + onesDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
onesDigit = replacementDigit;
}
}
System.out.println(hundredsDigit * 100 + tensDigit * 10 + onesDigit);
}
I made a program for the question and it's working fine, but in some cases it's not working like when I enter 656, it's showing like this:
The error
The code is showed below:
public static void main(String[] args) {
Scanner rx = new Scanner(System.in);
int ui,uiy,troll3,troll1;
float uix,uis,uiz,uit;
System.out.println("Enter a valid three digit number to calculate the frequency of the digits in it. \n");
ui = rx.nextInt();
if(ui>99&&ui<=999) {
uis = (float) ui;
//System.out.println(uis+" uis");
uix = uis / 10;
//System.out.println(uix+" uix");
uiy = (int) uix;
//System.out.println(uiy+" uiy");
troll3 = (int) ((uix - uiy) * 10); //1st digit
//System.out.println("3d " + troll3);
uiz = uix / 10;
//System.out.println(uiz+ " uiz");
troll1 = (int) uiz;
//System.out.println("1d " + troll1);
uit = (uiz - troll1) * 10;
//System.out.println(uit+" uit");
int troll2 = (int) uit;
//System.out.println("2d " + troll2);
if (troll1 == troll2 && troll1 == troll3) {
System.out.println("The number " + troll1 + " appears three times.");
} else if (troll1 != troll2 && troll2 != troll3 && troll1 != troll3) {
System.out.println("The number " + troll1 + " appears one time.");
System.out.println("The number " + troll2 + " appears one time.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll2) {
System.out.println("The number " + troll1 + " appears two times.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll3) {
System.out.println("The number " + troll3 + " appears two times.");
System.out.println("The number " + troll2 + " appears one time.");
} else if (troll2 == troll3) {
System.out.println("The number " + troll2 + " appears two times.");
System.out.println("The number " + troll1 + " appears one time.");
}
}
else{
System.out.println("The entered number is invalid");
}
}
It mostly gives an error when it consists of digit 5 in the middle. It shows an increment in values and swap in values. Please do help.
Thanks in advance! :-)
Why are you converting to float? float and double attempts to represent an infinite infinity of numbers (there are an infinite amount of integers. Between 2 integers, there are an infinite amount of numbers too: An infinite amount of infinities)... using only 32 bits. This is obviously impossible so instead only a few numbers are representable, and anything else is silently rounded to one of the select few. This means float and double introduce rounding errors.
After any math done to any double or float, == is broken. You can't use those; at best, you can try 'delta equality' (not a == b, but Math.abs(a - b) < 0.00001) but making the claim that your code works for all possible inputs becomes very difficult indeed, it's not going to be very fast, and the code readability isn't great either. So, don't.
Stop using floats, problem solved.
Your 'math' to get the individual digits is a bit circumspect and isn't going to just work if you replace things with int either. What you're missing is the % operator: Module (a.k.a. remainder).
Given, say, 656:
int in = 657;
int digit1 = in % 10;
in = in / 10;
System.out.println(in); // 65
System.out.println(digit1); // 7
int digit2 = in % 10;
in = in / 10;
System.out.println(in); // 6
System.out.println(digit1); // 5
int digit3 = in;
I need to print the factors of a perfect number. Here's the gist of my main class:
ArrayList<Integer> perfNums = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the upperbound: ");
upperbound = in.nextInt();
for (int i = 1; i <= upperbound; i++) {
if (isPerfect(i)) { //boolean to check if number is a perfect number
perfNums.add(i);
}
}
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for (int i = 0; i < perfNums.size(); i++) {
System.out.print(perfNums.get(i) + " = ");
printFactor((int)perfNums.get(i));
System.out.println();
}
Here's the printFactor class.
private static void printFactor(int number){
int factor = 1;
while(factor < number){
if (number%factor == 0) System.out.print(factor+ " + ");
//I don't know how to print the + sign otherwise.
factor++;
}
}
And here's a sample output:
Enter the upperbound: 10000
Perfect numbers between 1 and 10000 are:
6 = 1 + 2 + 3 +
28 = 1 + 2 + 4 + 7 + 14 +
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 +
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 +
I've got the main gist of it but I've struggled with an output issue. Due to the restrictions of my online submission system, my output needs to fit exact specifications.
My question is how do I go about printing all the factors of my perfect number but removing the + sign at the end? (e.g)6 = 1 + 2 + 3
I'm not too sure of many methods to print from a while loop. Would a for-loop be better for my goals? Or are there alternative methods to print the factors of a number?
The least amount of change to address this might be something like this:
private static void printFactor(int number)
System.out.print(1);
int factor = 2;
while (factor<number) {
if (number%factor == 0) System.out.print(" + " + factor);
factor++;
}
}
1 is always a factor, so you can print that before the loop and then prepend + to every subsequent factor.
You should cache the output you want to print into a StringBuilder. Then you are able to remove the last plus sign before you print the whole String. It also has a better performance.
private static void printFactor(int number)
{
StringBuilder output = new StringBuilder();
int factor = 1;
while (factor < number)
{
if (number % factor == 0)
output.append(factor + " + ");
factor++;
}
// remove last plus sign
output.deleteCharAt(output.length() - 1);
// print the whole string
System.out.print(output.toString());
}
Since factor starts from value 1 and number % 1 == 0 will always be true, you might print 1 first and then flip factor and + in System.out.print. Like this:
private static void printFactor(int number) {
if(number > 0) {
System.out.print(1);
}
int factor = 2;
while (factor<number) {
if (number % factor == 0) {
System.out.print(" + " + factor);
}
factor++;
}
}
Not the best solution, but it will do the job.
Try to create a variable String numb and use substring method like this:
String numb ="";
while(factor<number){
if(number%factor == 0)
numb= numb + factor+ " + ";
factor++;
}
System.out.print(numb.substring(0, numb.trim().length()-1));
Just for the sake of using Java 8 :)
private static void printFactor(int number){
System.out.println(IntStream.range(1, number)
.filter(p -> number % p == 0)
.mapToObj(i -> String.valueOf(i))
.collect(Collectors.joining(" + ")));
}
Thanks everyone for the quick response. You all have been a lifesaver, and I managed to pick up some new things to consider when I code in the future.
Anyway, while waiting for a reply I was fiddling with the code and came up with a rather inelegant solution, if anybody's interested. Here's the changes to the main class:
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for(int i=0; i<perfNums.size(); i++){
System.out.print(perfNums.get(i) + " = ");
outputString = printFactor2(perfNums.get(i));
if(outStr.endsWith(" + ")) outStr = outStr.substring(0, outStr.length()-3);
//because the submission system would cry foul with even a single extra space
System.out.println(outStr);
}
And here's the changes to the printFactor class:
private static String printFactor2(int number){
String out = "";
int factor = 1;
while(factor<number){
if(number%factor == 0) out += factor + " + ";
factor++;
}
return out;
}
Basically, what I did was append the factors to a string, then removing the trailing + sign using the substring method. On hindsight, I probably should've called the substring method inside the printFactor class instead. Something like return out.substring(0, out.length()-3); perhaps?
Nevertheless, thanks everyone!
I have written a simple program in java to find the factorial, which works fine. I am now trying to refine the output, but I'm not sure how to do it.
My Program:
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
int fact = 1;
Scanner number = new Scanner(System.in);
System.out.println("Enter the number : ");
int n = number.nextInt();
if (n < 0) {
System.out.println("Enter positive number");
} else {
System.out.print("Factorial Sequence is :");
for (int i = n; i >= 1; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("Factorial of number " + n + " is :" + fact);
}
}
}
Output shown is in this format (a single line, * after the 1):
Factorial Sequence is :5*4*3*2*1*Factorial of number 5 is :120
I want output in this format:
Factorial Sequence is :5*4*3*2*1
Factorial of number 5 is :120
Since 1 is not going to modify the factorial result your code can be rewriten as:
for (int i = n; i >= 2; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("1");
Another option is to use string concatenation during your for loop:
String s = "Factorial Sequence is :";
for (int i = n; i >= 1; i--) {
fact = fact * i;
s += i + (i > 1 ? "*" : "");
}
System.out.println(s);
Only 'benefit' this has over the other options is it saves calling System.out.print each iteration, at the expense of a string concatenation operation. Probably no performance difference at all, and certainly not significant here, but it is an alternate means to the same end.
EDIT: Use #demostene's excellent suggestion to avoid the final '*' after the final '1' - it avoids the conditional expression within the for loop, which is really nice as your factorial becomes larger.
To make the gap, you can add an \n literal to represent a newline.
System.out.println("\nFactorial of number " + n + " is :" + fact);
And for the last *, you can either remove it at the end or not add it if i is 1..
System.out.print(i + (i > 1?"*":""));
This says if i is greater than 1, return a *, otherwise return an empty string.
Just add a print line statement:
System.out.println(); // add this line
System.out.println("Factorial of number " + n + " is :" + fact);
I am trying to approximate pi by iteration. This is only a portion of the code.
I'm trying to put this equation into java: pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 + ... + ((-1)^(i+1)) / (2i - 1) ). The problem I have is the summation of this equation (illustrated in my code). If the user keeps on entering y, the program is supposed to multiply i by 2 and calculate pi until user enters n, then it returns to the main menu.
else if(input == 4)
{
System.out.print("i=1 pi=4.0\tWould you like to continue? (y|n) ");
char y = keyboard.next().charAt(0);
if (y =='y')
{
for (int i=2; i<=1000; i=i*2)
{
int sum = 0;
double pi =4 * (Math.pow(-1, i+1)/(2*i-1));
//Right here, how do I modify it to get a sum across a multitude of i's?
System.out.print("i=" + i + " " + "pi" + "=" + pi + "\tcontinue (y|n)? " );
keyboard.next().charAt(0);
}
}
else
{
}
I think your issue is the difference between the summation equation using i and the programmatic way to loop through a calculation. Something like this will loop through is adding/subtracting the fraction, and then multiply it all by 4 in the end.
boolean plus = true
double sum = 0;
for (double i=1.0; i<=1000; i+=2.0)
{
if (plus) {
sum += 1.0/i;
plus = false;
} else {
sum -= 1.0/i;
plus = true;
}
}
sum *= 4;