Counting by factors of two with a while loop? - java

I want this while loop to print every multiple of two below the number submitted(ex. if 100 was submitted it would print 2 4 8 16 32 64). Here's what I have(I'm only going to include a portion of the class because there was other things in it that don't pertain to this part)
i = 1;
Scanner myScanner = new Scanner(System.in);
System.out.print("Would thoughst be inclined to enter a number fair sir/madam: ");
String answer = myScanner.nextLine();
int number = Integer.parseInt(answer);
System.out.print("Your number set is: ");
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
What this prints if I enter 100 is: 2 4 8 16 32 64 128
How do I get rid of that last number?

You would get rid of that number by modifying your logic to match. Your code is doing precisely what it says. One option is to start at 2, and increase i at the end of the loop instead of just before printing it. You could also use a for loop:
for (int i = 2; i < 100; i *= 2)
...
If you want to save the last power, you have a few options, e.g.:
int k = 2;
for (int i = k; i < 100; i *= 2) {
k = i;
...
}
Or undo the last operation:
int i;
for (i = 2; i < 100; i *= 2)
...;
i /= 2;
Or check the next one:
int i;
for (i = 2; i * 2 < 100; i *= 2)
...;
Checking the next one, in your original form:
while (i * 2 <= number)
...;
Etc.
By the way, your title says "factors", your description says "multiples", and your code says "powers"...

In your code
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
the problem is that i, when it is equal to 64, is indeed less than 100, so the loop continues.
If you change it to
i = 2*i;
while(i <= number)
{
System.out.print(" " + i + " ");
i = 2*i;
}
it does as you wish, because it pre-computes the value before being analyzed as the while-loop terminator.

Try
while( i <= number / 2)

Those are powers of 2, not factors of 2.
"thoughst" is not a word. It should be "thou".
Update the value of i after you print it.

Related

ask the user for the maximum number to print out to and then print each multiple of the base number starting from the base to the maximum

System.out.print("Please enter the max number:");
int max = input.nextInt();
System.out.print("Please enter the base:");
int base = input.nextInt();
for (int i = 0; i <= max; max % base == 0;) {
System.out.println("Number is " + i);
}
How do I get it to print the multiples of a number?
Although Diabolus already has a solution, here's the same using a for loop:
for(int i = base; i <= max; i++)
{
if(i % base == 0)
System.out.println("Number is - " + i);
}
The number iterates from the base to the maximum number (if you start from zero, 0 too will be printed, as it divides completely by any number)
Note that even the base number will be printed. If you wish to avoid this, set i = base to i = base + 1.
I'm not sure if I have fully understood your question. However, I believe this is the solution you were looking for:
int currentMultiple = 0;
int step = 1;
do {
currentMultiple = (base * step);
System.out.println(currentMultiple);
step += 1;
} while ( currentMultiple <= max );
You're needing a while or do while loop for this problem. Since you are unaware of when the current multiple is going to exceed the input.
Let me know if this is what you needed!

Java: Min/Max/Average (4 variables) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Anyone knows how to run this program using 4 variables only? I tried using 1 variable for min and max "lowhigh" but I was having a hard time figuring out where to put the statements.
int numbers[] = new int[5];
int low = 0; int high = 0;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number < high) {
high= number;
}
if(number > low){
low = number;
}
}
numbers[count] = number;
}
double ave = numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4]/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
Another way to do it in Java 8.
int numbers[] = new int[5];
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
numbers[count] = number;
}
LongSummaryStatistics statistics = Arrays.stream(numbers)
.asLongStream()
.summaryStatistics();
System.out.println("Highest: " + statistics.getMax());
System.out.println("Lowest: " + statistics.getMin());
System.out.println("The average of all number is: " + statistics.getAverage());
Looks like your logic is backwards to finding high and low. Also your average wont work because order of operations. Need parens
int numbers[] = new int[5];
int low = Integer.MAX_VALUE; int high = Integer.MIN_VALUE;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number > high) {
high= number;
}
if(number < low){
low = number;
}
}
numbers[count] = number;
}
double ave = (numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4])/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
You don't have to use an array if all you're doing is finding the min, max and mean.
final int COUNT = 5; //this is just to be neat, and not needed as a variable.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
int sum = 0;
for(int i = 0; i < COUNT; i++){
int n = s.nextInt();//or whatever
if(n > high)
high = n;
if(n < low)
low = n;
sum += n;
}
System.out.println("Max: " + high);
System.out.println("Min: " + low);
System.out.println("Average: " + ((double) sum) / COUNT);
Based on what you mean by 4 variables, this may or may not work. final int COUNT is not really required and 5 can be put in directly instead.
This answer likely goes well beyond the scope of the question, but since the requirements/restrictions are not listed in full, it may still be a valid answer.
With a super strict interpretation of "4 variables", even the Scanner variable s counts.
Using streams, it can be done with 3 variables:
Scanner s; // variable 1
List<Double> values; // variable 2
String line; // variable 3
s = new Scanner(System.in);
values = new ArrayList<>();
while (true) {
System.out.print("Please enter a numbers, or press enter when done: ");
if ((line = s.nextLine().trim()).isEmpty())
break;
values.add(Double.valueOf(line));
}
if (values.isEmpty())
return;
System.out.println("Minimum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.min().getAsDouble());
System.out.println("Maximum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.max().getAsDouble());
System.out.println("Average: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.sum() / values.size());
Sample output
Please enter a numbers, or press enter when done: 10
Please enter a numbers, or press enter when done: 42
Please enter a numbers, or press enter when done: 19
Please enter a numbers, or press enter when done: 88
Please enter a numbers, or press enter when done: 1
Please enter a numbers, or press enter when done: 3774
Please enter a numbers, or press enter when done:
Minimum: 1.0
Maximum: 3774.0
Average: 655.6666666666666
There is no point in the numbers[] array; so eliminate that.
You need a control variable for the loop, a temporary storage for the input, then three running variables for min, max and sum (average is sum devided by count, which seems to be fixed to 5).
Thats 5 variables, and you strictly need all of them. Its possible to stuff multiple values into a single variable, but I highly doubt thats what you're supposed to do.
Depending on what the requirements really are (I presume this is homework), one of the five I named above doesn't count as a variable per requirement (most likely the loop control or the temporary input storage).
Edit: Here's a variant using multiple values encoded in one variable that works with three variables (or four if you count the scanner, which I replaced with random for my convinience):
public class HighLowAverage {
public static void main(String[] args) {
long sum = 0;
long highLow = 0x8000_0000_7FFF_FFFFL;
long countNumber = 0;
for (; (countNumber >> 32) < 5; countNumber += 0x1_0000_0000L) {
countNumber = (countNumber & 0xFFFF_FFFF_0000_0000L)
| ((int) (Math.random() * 100) & 0xFFFF_FFFFL);
System.out.println(((countNumber >> 32) + 1) + ". number is: " + (int) countNumber);
sum += (int) countNumber;
if ((highLow >> 32) < (int) countNumber)
highLow = (highLow & 0xFFFF_FFFFL) | (countNumber << 32);
if (((int) highLow) > (int) countNumber)
highLow = (highLow & 0xFFFF_FFFF_0000_0000L) | (countNumber & 0xFFFF_FFFFL);
}
System.out.println("Average: " + ((double) sum) / (countNumber >> 32));
System.out.println("Min: " + (int) highLow);
System.out.println("Max: " + (highLow >> 32));
}
}
The techniques used are bit-shifting and masking to use the upper/lower half of the long datatype as independendly accessible values. Note amount of complicated expressions necessary as well as the numerous constansts in the expressions plus typecasts almost everywhere.
This is code you should never ever use - it works, but even an experienced programmer will need an excessive amount of thinking to figure out if its working correctly. My guess is that a typical beginner class teacher will have trouble understanding it at all.
Edit2: Scratch the above, it can be done with one variable. How? By replacing multiple variables with an array:
public static void main(String[] args) {
long[] vars = new long[5];
vars[1] = Long.MIN_VALUE;
vars[2] = Long.MAX_VALUE;
for (vars[0] = 0; vars[0] < 5; ++vars[0]) {
vars[4] = (int) (Math.random() * 100);
System.out.println((vars[0] + 1) + ". number is: " + vars[4]);
vars[3] += vars[4];
if (vars[4] > vars[1])
vars[1] = vars[4];
if (vars[4] < vars[2])
vars[2] = vars[4];
}
System.out.println("Average: " + ((double) vars[3]) / vars[0]);
System.out.println("Min: " + vars[1]);
System.out.println("Max: " + vars[2]);
}
Needless to say thats still confusing code. Each index of the vars array is used to hold one of the variables (0 = loop control, 1 = min, 2 = max, 3 = sum, 4 = number).
You see it all depends on what is considered a variable.

Java - Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits

I have seen this question asked a few times, but all of the responses have included functionality that I haven't learned yet in this class and am I sure there must be a way to do it with only what I have learned. No arrays, etc... just loops and prior. I am not really looking for the answer, but just some direction. I have included the code I have already done. The program needs to be able to hand negative numbers, the sum and then print in the proper order. Right now my code does everything except print in the proper order. I understand why it is printing in reverse order (because the loop gets rid of and then prints the last number in the int), but I can't seem to figure out a way to change it. I have tried converting it to a string, char and just can't get it. Please take a look, and provide some guidance if you don't mind. thank you in advance.
public static void main(String[] args) {
int num;
int sum;
int temp;
System.out.print("Enter an integer, positive or negative: ");
num = keyboard.nextInt();
System.out.println();
if (num < 0)
num = -num;
sum = 0;
while (num > 0) {
temp = num;
sum = sum + num % 10; //Extracts the last digit and adds it to the sum
num = num / 10; //removes the last digit
System.out.print(temp % 10 + " ");
}
System.out.println(" and the sum is " + sum);
}
}
Not knowing what they've taught you in class so far, an easy albeit inefficient thing to do is to recreate the number as string.
String numbers = "";
while (num > 0) {
temp = num;
sum = sum + num % 10; //Extracts the last digit and adds it to the sum
num = num / 10; //removes the last digit
// System.out.print(temp % 10 + " ");
numbers = (temp % 10) + " " + numbers;
}
System.out.println(numbers + "and the sum is " + sum);
You were already grabbing the ones digit with (temp % 10) and then right shifting the original number with num = num / 10. There are other data structures you could use like a Stack or a LinkedList that are more natural to use in a situation like yours, or you could use a StringBuilder to append the digits to the end and then use the reverse() method to get them back in the correct order, but those data structures probably come after Arrays which you mentioned you didn't know.
Given those constraints, I used String concatenation. In general here is what happens:
String numbers = "";
num = 123;
digit = num % 10; // digit=3
num /= 10; // num=12
numbers = digit + " " + numbers; // numbers="3 " uses old value on right side of the equals
// next iteration
digit = num % 10; // digit=2
num /= 10; // num=1
numbers = digit + " " + numbers; // numbers="2 3 " see how the digit is put to the left of the old value
// last iteration
digit = num % 10; // digit=1
num /= 10; // num=0
numbers = digit + " " +numbers; // numbers="1 2 3 " notice there is an extra space at the end which is ok for your example
Set a counter, loop num/10, if result>0 counter++. In the end, counter+1 will be the number of digits
System.out.println("Please enter numbers: ");
int number_entered = input.nextInt();
int sum = 0;
String reserve = "";
if (number_entered < 0 ) {
number_entered = number_entered * -1;
}
for (number_entered = number_entered; number_entered > 0; number_entered/=10){
int lastdgt = number_entered%10;
sum += lastdgt;
reserve = lastdgt + " " + reserve + " ";
}
System.out.println(reserve);
System.out.println("The sum is = " + sum );
}
}

Split number into several numbers

I wrote a programm to get the cross sum of a number:
So when i type in 3457 for example it should output 3 + 4 + 5 + 7. But somehow my logik wont work. When i type in 68768 for example i get 6 + 0 + 7. But when i type in 97999 i get the correct output 9 + 7 + 9. I know that i have could do this task easily with diffrent methods but i tried to use loops . Here is my code: And thanks to all
import Prog1Tools.IOTools;
public class Aufgabe {
public static void main(String[] args){
System.out.print("Please type in a number: ");
int zahl = IOTools.readInteger();
int ten_thousand = 0;
int thousand = 0;
int hundret = 0;
for(int i = 0; i < 10; i++){
if((zahl / 10000) == i){
ten_thousand = i;
zahl = zahl - (ten_thousand * 10000);
}
for(int f = 0; f < 10; f++){
if((zahl / 1000) == f){
thousand = f;
zahl = zahl - (thousand * 1000);
}
for(int z = 0; z < 10; z++){
if((zahl / 100) == z){
hundret = z;
}
}
}
}
System.out.println( ten_thousand + " + " + thousand + " + " + hundret);
}
}
Is this what you want?
String s = Integer.toString(zahl);
for (int i = 0; i < s.length() - 1; i++) {
System.out.println(s.charAt(i) + " + ");
}
System.out.println(s.charAt(s.length()-1);
The problem with the code you've presented is that you have the inner loops nested. Instead, you should finish iterating over each loop before starting with the next one.
What's happening at the moment with 68768 is when the outer for loop gets to i=6, the ten_thousand term gets set to 6 and the inner loops proceed to the calculation of the 'thousand' and 'hundred' terms - and does set those as you expect (and leaving zahl equal to 768 - notice that you don't decrease zahl at the hundreds stage)
But then the outer loop continues looping, this time with i=7. With zahl=768, zahl/1000 = 0' so the 'thousand' term gets set to 0. The hundred term always gets reset to 7 with zahl=768.
The 97999 works because the thousand term is set on the final iteration of the 'i' loop, so never gets reset.
The remedy is to not nest the inner loops - and it'll perform a lot better too!
You should do something like this
input = 56789;
int sum = 0;
int remainder = input % 10 // = 9;
sum += remainder // now sum is sum + remainder
input /= 10; // this makes the input 5678
...
// repeat the process
To loop it, use a while loop instead of a for loop. This a great example of when to use a while loop. If this is for a class, it will show your understanding of when to use while loops: when the number of iterations is unknown, but is based on a condition.
int sum = 0;
while (input/10 != 0) {
int remainder = input % 10;
sum += remainder;
input /= 10;
}
// this is all you really need
Your sample is a little bit complicated. To extract the tenthousand, thousand and the hundreds you can simply do this:
private void testFunction(int zahl) {
int tenThousand = (zahl / 10000) % 10;
int thousand = (zahl / 1000) % 10;
int hundred = (zahl / 100) % 10;
System.out.println(tenThousand + "+" + thousand + "+" + hundred);
}
Bit as many devs reported you should convert it to string and process character by character.

Loop to Find Sum of Digits

I am trying to write a simple and quite useless program to generate a list of all integers 1><1000 where the sum of digits is 11. Every time I run this, I end up in an infinite loop. I've tried different things - for(){}, while(){}, adding a if(count>500){break;} to halt it after the loop counter reaches 500....still nothing...where am I going wrong in this?
Thanks in advance
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
You are using same variable as controller for your fors. Try to change the controller variable within the for structure from number to number1
You are changing the variable here:
---------------------------------
int hPlace = number / 100; number = number - (hPlace * 100);
---------------------------------
Don't do this
number = number - (hPlace * 100);
when your condition is dependent on number
for(int number = 29; number < 1000; number++)
because you have two nested for loops which both of them use the same variable as counter
for(int number = 29; number < 1000; number++) {
for(number = 29;number < 930;number++) {
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100;
**number** = number - (hPlace * 100); // PROBLEM!!!
int tPlace = number / 10;
**number** = number - (tPlace * 10); // PROBLEM!!!
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
if(count>500){break;} to halt it after the loop counter reaches 500....still nothing
This won't work because you're redeclaring count with an initial value of 0 everytime. So the if will always return false.
Also, these following lines:
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
Modify number, which is your loop variable. Your loop will not perform correctly if you modify the loop variable in unexpected ways. Instead, copy the value over to another variable.
Don't change the value of you loop control variable inside the loop, or dangerous things may result. Instead, copy the value into a new variable and use that in the loop.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SumDigits
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a Number:");
String string=br.readLine();
System.out.println("length of Number:"+string.length());
int sum=0;
int number=0;
for(int i=0;i<=string.length()-1;++i)
{
char character=string.charAt(i);
number=Character.getNumericValue(character);
sum=sum+number;
}//for
System.out.println("Sum of digits of Entered Number:"+sum);
}//main()
}//class

Categories

Resources