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);
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 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
}
...
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 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'm accepting an integer value for the rows and columns, then a String value for the character. If the user enters a value of 5 for the row and 2 for the column with the character "#" the output to the user should be:
##
##
##
##
##
The code I have so far is below, where the comment is, is where I can't seem to get the for loop working to create the shape with the inputs entered for the desired amount of rows and columns using the character inputted.
import java.util.*;
public class createAShape
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
String errorMessage = "Please enter an amount in the range 1 and 25", result = "";
System.out.print("Enter number of rows: ");
int r = Integer.parseInt(in.nextLine());
if(r < 1 || r > 25)
System.out.println(errorMessage);
else
{
System.out.print("Enter number of columns: ");
int c = Integer.parseInt(in.nextLine());
if(c < 1 || c > 25)
System.out.println(errorMessage);
else
{
System.out.print("Enter symbol to use: ");
String character = in.nextLine();
//continuing from here
}
}
System.out.println(result);
}
}
You need two for loops. An outer for loop to count the rows, and an inner loop to do the printing of a row using the character entered. After you print all the columns of a row, you need to print a new line.
Something like this shold do it:
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
System.out.print('#');
}
System.out.println();
}
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!!