Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
if a input a number, how do i count the multiples of that inputted number until 100.
For example if i input the number 8
It would print out 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96
You can modify a for loop very nicely so that it only increments by the number that you want. The upside is that it is not only easy to follow, and shorter, but it is also more efficient. Don't loop more times than you need. Keep it simple.
Eg
int n = 8;//your chosen number (however you decide to get it)
for (int x = n; x <= 100;x+=n)
{
System.out.println (x);
}
What we have done:
made an int n holding the number that the user wants to increment by.
Then in the for loop, we:
Made the for loop variable,x equal to n.
Made the condition that the loop must break once x reaches or passes 100
Tell the loop to increase x by n for every iteration.
You can use a for loop starting from 8, and at each iteration add 8 to the current number. I let you fill up the ??? :
for (???; value <= 100; ???) {
System.out.print(value);
}
Here's also a one-liner using java 8 :
IntStream.iterate(8, i -> i+8).limit(100/8).forEach(System.out::println);
The most basic way is to use a for loop
public static void printMultiples(int k) {
boolean isHead = true;
for (int i = 0; i < 100; i++) {
if (i % k == 0) {
if (isHead) {
System.out.print(i);
isHead = false;
}
else System.out.print(", " + i);
}
}
}
Use this. It will not use java 8, as that is very new, so its not recommended.
public class MyClass {
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("You must enter at least one number!");
}
int originalNumber = Integer.parseInt(args[0]);
int number = originalNumber * 1; // For avoiding pointer problems
while((number + originalNumber) > 100) {
System.out.println(number);
number += originalNumber;
}
}
}
Here:
import java.util.Scanner;
Scanner input = new Scanner(System.in);
int i = n;
System.out.println("Enter number: ");
int n = input.nextInt();
while (true) {
System.out.println(i);
i += n;
if (i > 100) break;
}
int input = 8;
int result = input;
while(result < 100){
System.out.println(result);
result += input;
}
You can use the modulo operator %:
if (n % 8 == 0) {
System.out.println(n);
}
This means: if the remainder of dividing n by 8 is equal to 0, we should print this number.
Related
Lets assume n=20
so after every 6 iterations I will do some processing
int i=0
for (t=6;t<20;t=t+6){
while(i<=t){
will do some processing
i++;
}
}
In the above code it will terminate when t=18, but I want to continue until 20.
How to do that ?
You are increasing the t variable 6 units... the last condition that satisfies the t<20 is when t = 18.
instead of doing t+=6 do a normal t++ and play with the modulo %6
example:
public static void main(String[] args) {
int n = 20;
for (int i = 0; i < n; i++) {
//TODDY
insert your while in here depending on when that must be executed
if (i % 6 == 0) {
System.out.println("am on a 6 modulo step..." + i);
} else {
System.out.println("foo#" + i);
}
}
System.out.println("done");
}
The behaviour is correct only.. Still if you want to perform any operation, do it after the condition is met, try below snippet:
int i = 0, n = 20;
do{
i += 6;
System.out.println(i);
} while (i < n);
System.out.println(i);
your code is not doing something every 6th iteration, but instead you are doing (n - n%6) times. your "will do some processing" is inside the while. If you add a print (or debug) there you will notice it; on the n=20 example the while will be executed 18 times; it will do something 18 times.
if you want to execute every 6th iterations, and include one extra for the cases that are not exactly divisible by 6, then you could do:
if (n == 0) {
return;
}
int number_iterations = n/6 + (n%6!=0 ? 1:0);
for (int i=0; i<number_iterations; i++) {
// do something
}
That covers what you requested; if not, pls edit question to be more clear on your exact needs.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
EDIT: Since there are claims that this is a duplicate question, I will state my stance on why it is not.
The other question had posed a problem regarding the conversion of a string input to an integer (the answer deemed correct). This is irrelevant here, as the problem in my case is one of logic.
The solutions on the other question cannot correct the problem this question presents (finding the syntactical "charAt" error).
Frankly, the context of the other question is beyond the scope of my knowledge in Java.
I have successfully created a program that converts binary numbers to decimal numbers.
import java.util.Scanner;
public class ProblemThree // to convert binary to decimal
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
int[] number = new int[length];
int[] powerTwo = new int[length];
// To list every digit separately //
for (int n = 0; n <= length - 1; n++)
{
number[n] = (int) (binary / Math.pow(10, n)) % 10;
}
// To set the values in powerTwo to 2 //
for (int n = 0; n <= length - 1; n++)
{
powerTwo[n] = 2;
}
// To update the values in powerTwo //
for (int n = 0; n <= length - 1; n++)
{
if (n == 0)
powerTwo[0] = 1;
else if (n == 1)
powerTwo[1] = 2;
else
powerTwo[n] *= powerTwo[n-1];
}
// To add if current value is 1 //
for (int n = 0; n <= length - 1; n++)
{
if (number[n] == 1)
answer += powerTwo[n];
}
System.out.println(powerTwo[0]); // for testing
System.out.println(number[0]); // for testing
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
Seeing how some of the steps were redundant, I tried to simplify the code.
import java.util.Scanner;
public class ProblemThreeTestFunction
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
String number = String.valueOf(binary);
for (int n = 0; n <= length - 1; n++)
{
if (number.charAt(n) == 1)
answer += (int)Math.pow(2, n);
}
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
I actually have no idea why the simplified code logic does not work. It uses the same concept as my original.
Thanks in advanced!
Why don't you just use:
int decimalValue = Integer.parseInt(binary, 2);
But if you use this you Need to use scan.nextLine() not scan.nextInt().
This will just convert your binary number to decimal using base 10 like seen here.
You need to test against the character '1':
if (number.charAt(n) == '1')
not the number 1 that you are currently doing:
if (number.charAt(n) == 1) // WRONG!
Also, since charAt counts from the left, and binary expansion counts from the right, you need to reverse the sense. Change
Math.pow(2, n)
to
Math.pow(2, length - 1 - n)
You are comparing with digit 1, it should be character 1 i.e. '1'.
for (int n = 0; n <= length - 1; n++) {
if (number.charAt(n) == '1') {
answer += (int)Math.pow(2, length - n - 1);
}
}
Also you need to correct the exponent part.
I'm kind of a newbie at Java, and not very good at it. It's a trial and error process for me.
I'm working on a Java program to output the amount of primes in an array. I can get it to output the primes, but I want to also output the quantity of primes. I tried to add each prime to an array list titled "primes" then return "primes.size()" at the end of my program. It doesn't work as intended. The count is actually off. When I create an array of 5 numbers, it outputs 3 primes, 2, 3, and 5. But then it says I have 4 primes. I think it might be counting 1 as a prime. Because when I create an array of 20, the prime numbers output 2,3,5,7,11,13,17 and 19. Then it says the total prime numbers = 9. It should be 8 though.
Here's my code
public class Prime {
public static void main(String[] args) {
int index = 0;
Scanner scan = new Scanner(System. in );
System.out.println("How big would you like the array? ");
int num = scan.nextInt();
int[] array = new int[num];
ArrayList < Integer > primes = new ArrayList < Integer > ();
//System.out.println("How Many threads? ");
//int nThreads = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
//Thread[] thread = new Thread[nThreads];
for (int n = 1; n <= array.length; n++) {
boolean prime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(n);
}
if (prime && n != 1) {
System.out.println(n + "");
}
}
System.out.println("Total Prime numbers = " + primes.size());
System.out.println("Prime Numbers within " + array.length);
}
}
Forgive the sloppiness of it. I actually plan on adding multithreading to it, but I wanted to get this down first.
Any help would be greatly appreciated. Thanks.
You have included 1 in your array of primes, because you started the n for loop at 1. You don't print it because of the final if statement, but it's there in the ArrayList.
Start your n for loop with n = 2. As a consequence, you won't need the final if statement, because n won't be 1 ever. You could print the prime at the same time as you add it to the ArrayList.
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors.
import java.util.Scanner;
public class objects {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int nmbr[] = new int[x];
for(int f=0;f<nmbr.length;f++)
nmbr[f]=scan.nextInt();
int counter = 0;
int max = 0;
for (int i = 0; i < nmbr.length - 1; i++) {
if (nmbr[i] == (nmbr[i + 1]-1))
counter++;
else
counter = 0;
if (counter > max)
max = (counter+1);
}
System.out.println(max);
}
}
Why is my code still printing the counter without adding one? I am not finding the mistake
sample run:
7 2 3 5 6 7 9 10
2
it is printing 2 instead of 3.
When you see the first number out of sequence, you should reset counter to 1, not 0 - as it's the start of a sequence with length at least 1. You then need to also change the code which changes max:
if (counter > max) {
counter = max;
}
After all, you just want max to be the maximum value of counter.
(I would strongly recommend using braces for every if statement, by the way - it's easier to avoid mistakes that way.)
import java.util.Scanner;
public class objects {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int nmbr[] = new int[x];
for(int f=0;f<nmbr.length;f++) {
nmbr[f]=scan.nextInt();
}
int counter = 0;
int max = 0;
for (int i = 0; i < nmbr.length - 1; i++) {
if (nmbr[i] == (nmbr[i + 1]-1)) {
counter++;
} else {
if (counter > max)
max = (counter+1);
counter = 0;
}
}
System.out.println(max);
}
}
Just a minor error in your logic there, you were updating max every single time the counter was greater than max, so the next time if the sequence comes to an end, it actually fails to register as the longest sequence. Just reorder it as I have done and it works.
Start your conter from 1. because if you start from 0 then it means you are not counting the 1st value.
else
counter = 1;
And Change the dont increment your counter when assigning to max.
max =counter;
Your maximum condition is incorrect:
if (counter > max)
max = (counter+1);
You compare max with counter and assign counter+1. This way when max is equal to 2 it can't be updated with 2+1.
Probably you should use:
if (counter + 1 > max)
max = (counter+1);
P.S.: Your question doesn't show research effort. You could use debug output to understand what is going on with your program. Simplistic example:
for (int i = 0; i < nmbr.length - 1; i++) {
if (nmbr[i] == (nmbr[i + 1]-1))
counter++;
else
counter = 0;
System.out.println("Current value: "+counter);
if (counter > max) {
max = (counter+1);
System.out.println("New max value: "+max);
}
}
This was an easy one and already pointed out in previous answers you are wrongly setting the value of counter in your code.
Run your code through a debugger to keep a track of variable values of what you are expecting from your program versus what you are actually getting.
Stepping through each line of code can help you understand your mistakes better.
you don't take into account the first number, in this case 5
when i == 2 its the start of the sequence, however, nmbr[1] is 3 therfore counter will stil be 0
start the counter to be 1 (this is logic, since the smallest sequence is 1)
you need to change the if to be:
import java.util.Scanner;
public class objects {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int nmbr[] = new int[x];
for(int f=0;f<nmbr.length;f++)
nmbr[f]=scan.nextInt();
int counter = 1;
int max = 1;
for (int i = 0; i < nmbr.length - 1; i++) {
if (nmbr[i] == (nmbr[i + 1]-1))
counter++;
else
counter = 1;
if (counter > max)
max = counter;
}
System.out.println(max);
}
}
I would like to understand, why is it when I specify the number for the method to sum up numbers it returns 21, but when i enter the value through scanner it gives me the correct value. For example number 3 should be 1 + 2 + 3 = 6 but its giving me 21, any ideas thanks.
public class sumInt
{
public static void main(String[] args)
{
int i = sumInt(3);
int j = sumInt(10);
Scanner in = new Scanner (System.in);
System.out.println("Please enter posiutive integer: ");
int k = in.nextInt();
System.out.println(sumInt(i));
System.out.println(sumInt(j));
System.out.println(sumInt(k));
}
public static int sumInt(int n)
{
int sum = 0;
for (int i = 0; i <= n; i++)
{
sum += i;
}
return sum;
}
}
You are actually summing up to 6 for i, your current code could also be written as:
System.out.println(sumInt(sumInt(3)));
You'll need to print out i directly instead of calling sumInt on it again.
When you first do int i = sumInt(3);, i gets set to 6 (1 + 2 + 3). When you System.out.println(sumInt(i)), it does sumInt(6), which is 21, because you haven't reset i to 3.
To see the actual results, you should change what you're outputting to:
System.out.println(i);
System.out.println(j);
System.out.println(sumInt(k));
Or change your initial definitions of i and j to:
int i = 3;
int j = 10;
It's because you're calling sumInt in two places, when you only meant to call it in one:
int i = sumInt(3); // sets i = sumInt(3) == 6
System.out.println(sumInt(i)); // prints sumInt(i) == sumInt(6) == 21
Because you're calling sumInt() twice; once at the beginning, then again in the print statements.
You are saying i = sumInt(3) so i == 6.
Then your print sumInt(i) == sumInt(6) which I'm guessing is 21..
You call sumInt twice for the same number.
int i = sumInt(3); //i gets 6
System.out.println(sumInt(i)); //called with 6 =21
This is because of the following lines
System.out.println(sumInt(i));
System.out.println(sumInt(j));
System.out.println(sumInt(k));
You are already calculating i and j as the sum of the integers you want, and when you printout , you are again calculating sum of i and j
change the above three lines to the following:
System.out.println(i);
System.out.println(j);
System.out.println(sumInt(k));