Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I can't get this code to align correctly. I need it to display in 5 rows of ten, aligned neatly. This is what i have, please help!
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String...args) { //start main method
Scanner sc = new Scanner(System. in ); //renamed Scanner to sc
int a = 1; // first prime number
int b = 227; // 50th prime number
System.out.println(" ");
for (int i = a; i <= b; i++) //this is the primer for the prime number formula
{
boolean isPrime = true; //sets the statement to true
if (isPrime) for (int j = 2; j <= i; j++) //formula to get the prime
{
if (i != j && i % j == 0) //formula checking prime
isPrime = false; //sets statement to false
}
if (isPrime) {
System.out.print(i + " "); //if true it prints prime number
System.out.printf("\n "); //if false it prints a dash
}
}
} //end of main method
} //end of class
You can do it using a counter variable which you will increment once you print a prime number.If counter%10 returns 0 then you can add a new line.
//initialize counter with 0
...
if (isPrime)
{
System.out.print(i+" ");//if true it prints prime number
counter++;
if(counter%10==0)
System.out.println();//it will add a new line
}
...
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
There is this program that asks me to write a java program that asks the user to type a positive number n and prints the sum of odd numbers using while loop: 1+3+5+7…+(2n-1).
Example : If the input is 4, then the program will print 16
so what i did is made this code :
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 0;
int sum = 0;
while (i<=n)
{
sum += i ;
i++;
}
System.out.println("Sum = " + sum);
}
}
And the program is not working like how the question wants it to be like
You can use i += 2; which is same as i = i + 2;, instead of using i++;.
But this won't give you the output you expect. So, there has to be made several changes in your code to get the expected result.
First initialise the value of i to 1.
int i = 1;
Then, change the while loop statement to,
while (i <= (2 * n - 1)){
// Your Code
}
Finally, use i += 2; as your increment statement.
The full code is shown below.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 1;
int sum = 0;
while (i<=(2 * n - 1))
{
sum += i ;
i += 2;
}
System.out.println("Sum = " + sum);
}
}
You've initialized i wrong. It should start from 1 since you want to add only odd numbers. Also increase i by 2 units using +=2. Another problem is with the while loop condition. The last number in the sequence will be 2n-1 and not n. So the program will be:
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 1;
int sum = 0;
while (i <= (2 * n - 1)) // Here is the new condition for last number...
{
sum += i ;
i+=2; // Here goes the 2 unit increment...
}
System.out.println("Sum = " + sum);
}
}
You can keep a variable like odd and increase its value by 2 in every iteration.
Also,
you should run the loop less than n times
because you start the loop from 0. Then I hope you will get your desired answer. Here is the sample code which may help you to understand.
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 0;
int sum = 0;
int odd = 1;
while (i<n)
{
sum += odd ;
odd += 2;
i++;
}
System.out.println("Sum = " + sum);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
When I enter an even number, the code works and asks for an odd number, but when I input an odd number, it never closes and carries on the sum for every odd number.
import java.util.Scanner;
public class OddSums {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter an odd number");
int oddSumMax = in.nextInt();
int oddSum = 0;
do {
if (oddSumMax % 2 == 1) {
for(int i=1; i<=oddSumMax; i++) {
if (i % 2 == 1){
oddSum = oddSum + i;
}
}
System.out.println(oddSum);
} else if(oddSumMax % 2 == 0) {
System.out.println("This is even Please enter an odd number");
oddSumMax = in.nextInt();
}
} while (oddSumMax % 2 == 1 );
}
}
You should separate the loops. One loop to ensure the user inputs an odd number and a second one to do the calculations.
Scanner in = new Scanner(System.in);
int oddSumMax;
// Get user input
do {
// TODO: handle case where user does not enter a number
System.out.println("Enter an odd number");
oddSumMax = in.nextInt();
} while (oddSumMax % 2 == 0);
// Calculate
int oddSum = 0;
for (int i = 1; i <= oddSumMax; i += 2) {
oddSum += i;
}
System.out.println(oddSum);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to create a program that will ask the user to input 5 integers using array and determine all the prime numbers entered. But I have difficulty with it. What seems to be the problem? I use JCreator for this.
package arrays;
import java.util.Scanner;
public class Examples {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in) ;
System.out.println("Total numbers : ");
int n = sc.nextInt();
boolean isPrime =true;
int result =0;
System.out.println("Enter the Numbers : ");
int [] numbers = new int[n];
for(int i=0;i<n;i++) {
numbers[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
for(int j=2;j*j<numbers[i];j++) {
if(numbers[i]%j ==0) {
isPrime =false ;
break;
}
}
}
if(isPrime) {
System.out.println("The Prime Numbers : " +numbers[i]);
}
}
}
You should put the isPrime() inside the outer loop as below -
System.out.println("The Prime Numbers : ");
for(int i=0;i<n;i++) {
isPrime =true; // setting it to true before checking for every numbers
for(int j=2;j*j<numbers[i];j++) {
if(numbers[i]%j ==0) {
isPrime =false ; // will become false only when not an prime
break;
}
}
// isPrime will remain true if numbers[i] is a prime number. So print the prime number
if(isPrime) {
System.out.println(numbers[i]+" ");
}
}
You code had few errors -
if(isPrime) {
System.out.println("The Prime Numbers : " +numbers[i]);
}
Firstly, the above piece of code wouldn't work, since the scope of i is limited only to the for() loop. Even if i was declared outside the for loop, the number that would have been printed would always have been last number (if a prime existed in the user inputted number). That is not we want.
So, print the numbers whenever you verify that a number is not prime. After you complete every inner loop, check the boolean isPrime and if it is true, we know that the number we are currently checking(numbers[i]) is surely a prime. So print the number there itself.
Hope this helps !
The following code snippet fixes all the issues and checks only odd numbers in the loop:
for (int i = 0; i < n; i++) {
isPrime = numbers[i] % 2 == 1;
for (int j = 3; isPrime && j * j <= numbers[i]; j += 2) {
if (numbers[i] % j == 0) {
isPrime = false;
}
}
if (isPrime && numbers[i] > 1) {
System.out.println("The Prime Numbers : " + numbers[i]);
}
}
You should also take into account that 0 and 1 are NOT primes.
You need to check isPrime in outer loop
for(int i=0;i<n;i++) { // This loops for every number
//inner both loops for check the number is prime
boolean isPrime =true;
for(int j=2;j*j<numbers[i];j++) {
if(numbers[i]%j ==0) {
isPrime =false ;
break;
}
}
if(isPrime) {
System.out.println("The Prime Numbers : " +numbers[i]);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am practicing and i need help with this code . I need to read integers from the keyboard and print how many are positive Any help in what im doing wrong in my code below?
int size = 10;
int count = 0;
int cuenta = 0;
int[] numbers = new int[size];
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter 10 digits: ");
while (count < size) {
numbers[count] = keyboard.nextInt();
count++;
}
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 0) {
cuenta++;
System.out.println("There are " + cuenta);
}
}
}
}
You have your logic to check for positive integers right. To point you in the right direction think about your print statement and whether it need to be within the for loop.
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 0) {
cuenta++;
System.out.println("There are " + cuenta);
}
}
you need to print out the count after for loop so that it has right answer
System.out.println("There are " + cuenta);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to create a lottery program that creates four random numbers, each between 0 and 9 (inclusive). This program asks user to guess four numbers and compares each user guesses to four random numbers and displays the won message as:
No matches 0 points
Any one digit matching 5 points
Any two digits matching 100 points
Any three digits matching 2,000 points
All four digits matching 1,000,000 points
My program runs but it has some logic errors. For example,the output should be:
Random numbers:2 3 3 4
Guess numbers: 1 2 5 7-->1 matching digit
Guess numbers: 3 5 7 3-->2 matching digits
Guess numbers: 3 3 3 1-->2 matching digits
Guess numbers: 3 3 3 3-->2 matching digits
public class Lottery
{
public static void main(String[] args) {
final int LIMIT=10;
int totalCount=0;
int totalPoint;
Random random=new Random(); //creating object of random class
Scanner input=new Scanner(System.in);//creating object of scanner class
//declaring two arrays
int[] guessNumber= new int[4];
int[] randomNumber=new int[4];
for(int i=0;i<4;i++)
{
randomNumber[i]=random.nextInt(LIMIT);//returns value between 0 to 9(inclusive)
}
for(int i=0;i<4;i++)
{
System.out.println("Enter your first guess number from 0 to 9:");
guessNumber[i]=input.nextInt();
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (randomNumber[i] == guessNumber[j])
{
++totalCount;
break;
}
}
}
if(totalCount == 1)
{
totalPoint=5;
}
else if(totalCount == 2)
{
totalPoint=100;
}
else if(totalCount == 3)
{
totalPoint=2000;
}
else if(totalCount == 4)
{
totalPoint=100000;
}
else
{
totalPoint=0;
}
//dispalying points
System.out.println("You have earned " +totalPoint+ "points!!");
}
}
Looks to me like the problem is that once you've matched a particular digit, you ought to be removing it from circulation so that multiple guesses of the same value don't count as matches. One solution is to use an ArrayList for the randomNumber's and remove them when there's a match. If you replace what's between your // declaring two arrays comment and your totalPoint assignment with the following it seems to do what you requested in terms of your example.
int guess;
ArrayList<Integer> randomNumber = new ArrayList<Integer>();
for (int i = 0; i < 4; i++) {
randomNumber.add(random.nextInt(LIMIT));
}
for (int i = 0; i < 4; i++) {
System.out.print("Enter your guess number from 0 to 9: ");
guess = input.nextInt();
for (int j = 0; j < randomNumber.size(); ++j) {
if (randomNumber.get(j) == guess) {
++totalCount;
randomNumber.remove(j);
break;
}
}
}
input.close();
Note that I've chosen to process each guess as it's read rather than store them in an array and process them later.
It looks like your overall logic is fine.
If I understand correctly, you just want a different output.
Use something like this for your output.
String guessNumbers = "";
String randomNumbers = "";
for (int i = 0; i < 4; i++){
randomNumbers += randomNumber[i]+" ";
guessNumbers += guessNumber[i]+" ";
}
System.out.println("Random numbers: "+randomNumbers);
System.out.println("Guess numbers: "+guessNumbers+" --> # of matching digits "+totalCount);
System.out.println("You have earned " +totalPoint+ " points!!");
This is what it now prints:
Random numbers: 2 9 7 4
Guess numbers: 7 4 5 2 --> # of matching digits 3
You have earned 2000 points!!