I'm writing a program that adds the first ten odd numbers, and gets the sum at the end.
Here is my code so far. My code reads the odd number in a list of 10 numbers. I want my code to be able to read 10 odd numbers even if there are more than 10 numbers entered. I know the problem is i < 10, which makes the program stop after the 10th number.
import java.util.Scanner;
public class question14
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i = 0;
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
}
}
Wrap it in a while loop instead.
While oddnumbers < 10 ask for a new number.
int i = 0
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
EDIT:FULL CODE
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author stevengreen22
*/
public class NewMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int input;
int inputCount = 0;
while (i < 10){
//Having this inside the while loop prompts the user every time.
System.out.println("New number?");
input = scan.nextInt();
inputCount++;
if(input % 2 == 1){
sum += input;
i++;
}
}
System.out.println("sum: "+sum);
System.out.println("Number of odds:" + i);
System.out.println("Numbe of inputs: " +inputCount);
System.out.println("Average cos I miss typing sout tab:" + (inputCount/sum));
}
}
The principle thing is that you don't know how many numbers the user is going to enter into the program, so you want to use a while loop instead of a for loop.
One chooses a for loop when they know how many elements they want to iterate over; one chooses a while loop when they don't know how many elements they'll need to iterate over.
You'll need to define another variable called counter outside of the loop, and use this as your loop variable constraint.
while(counter < 10) {
// loop
}
You'll also need to update counter whenever you encounter an odd value.
This should work
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i=0;
while (i<10){
odd=keyboard.nextInt();
if (odd%2!=0){
sum=sum+odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is "+sum);
}
Just replace your for loop with a while loop and track the number of odd numbers in an integer:
int oddNumberCount = 0;
int inputNumber;
while(oddNumberCount<10)
{
inputNumber = keyboard.nextInt();
if(inputNumber%2!=0)
{
sum = sum+inputNumber;
oddNumberCount++;
}
}
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);
}
}
I have to do an 'instant lottery' program in my first computer science class. All semester my professor has read verbatim from the book, so now I am a little lost, truthfully. I know how to do most of it, but am just having trouble figuring out array sort and how to compare user input and the random number output. My professor refuses to answer questions about take home assignments and has banned the use of anything except: arrays, loops and math.random- so no sets or anything more complex that could help. I've seen other programs that compile, but all with sets.
I have the code for user input of the lottery numbers and to generate the output of the random numbers. I can most likely also figure out how to print the payout with if/else. I just need to know how to get the program to compare the numbers an figure out if the user is a "winner" or not.
import java.util.Scanner;
public class TheLottery {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); //user input of their lottery numbers
System.out.print("Enter number 1: ");
int num1 = keyboard.nextInt();
System.out.print("Enter number 2: ");
int num2 = keyboard.nextInt();
System.out.print("Enter number 3: ");
int num3 = keyboard.nextInt();
System.out.print("Enter number 4: ");
int num4 = keyboard.nextInt();
System.out.print("Enter number 5: ");
int num5 = keyboard.nextInt();
System.out.print("Enter number 6: ");
int num6 = keyboard.nextInt();
}
int[] lottery = new int[6];
int randomNum;
{
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 50); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " "); //print random numbers
}
}
the final program should have the user enter 6 numbers, the program compare the numbers for matches, figure out if the user is a 'winner', show the prize and an added thing is show how much they spent (each 'ticket' is $1) vs how much they won. So far all that outputs is the scanner and random numbers
It looks like you obtained six numbers then didn't use them. Your lottery array is automatically initialized to zero. I think you're trying to compare an array with inputs to a random array, so you need a loop to put your entered values into. After you do that, initialize your random array, then just compare the arrays.
public static void main(System[] args) {
Scanner in = new Scanner(System.in);
int[] lottery = new int[6];
System.out.println("Enter " + lottery.length + " numbers: ");
for (int i = 0; i < lottery.length; i++) {
lottery[i] = in.nextInt();
}
The specific question has to do with how to do the comparison and figuring a "winner". It isn't clear what makes the definition of "winner".
Based upon my comment, and as shown in the answer by #szoore, I would use an array to collect the input. I'd use a method to collect (since one can change to use a different method for the selections, which makes testing easier).
/**
* Obtain the specified number of entries from the user
*/
public static int[] getUserSelections(final int numSelections)
{
Scanner in = new Scanner(System.in);
// read N entries from the user
int[] nums = new int[numSelections];
// NOTE: no error processing in this loop; should be refined
// bad numbers (e.g., negative, too large), duplicate entries, etc.
// need to be removed
for (int i = 0; i < numSelections; ++i) {
System.out.print("Enter number " + (i + 1) + ": ");
nums[i] = in.nextInt();
}
return nums;
}
The OP has a basic generation for the lottery numbers, but again I'd use a method. This has a slight refinement to the duplicate check, by using a method, and also allows the same duplicate check method to be later used for checking matches:
public static int[] getLotteryNumbers(final int numSelections)
{
// the largest number to be selected; all numbers between
// 1 and maxNum (inclusive) will have equal(-ish) probability
// of being generated
final int maxNum = 50;
int[] lottery = new int[numSelections];
Random rnd = new Random();
// make N random selections, and ensure we don't have duplicates
for (int i = 0; i < numSelections; ++i) {
boolean generate = true;
while (generate) {
int sel = rnd.nextInt(maxNum) + 1;
generate = numberInArray(sel, lottery);
if (! generate) {
lottery[i] = sel;
}
}
}
return lottery;
}
/**
* Returns true if the specific queryNum is found in the pastSelections
* Could be slightly optimized by passing how many selections have
* already been made
*/
public static boolean numberInArray(int queryNum, int[] pastSelections)
{
// look at each element and see if already there; exit via return
// if so
for (int i = 0; i < pastSelections.length; ++i) {
if (pastSelections[i] == queryNum) {
return true;
}
}
return false;
}
The use of the method 'numberInArray' then allows for fairly easy check on how many numbers match:
// see how many match
int matches = 0;
// see if the user entry exists in the lottery; if so, we
// have a match
for (int i = 0; i < userEntries.length; ++i) {
if (numberInArray(userEntries[i], lottery)) {
++matches;
}
}
System.out.printf("Found %2d matches%n", matches);
Determining payouts, etc. is straight forwarding using if/else or (perhaps better) a switch based on the number of matches.
Also, the entries and lottery selections should probably be sorted. It isn't clear if the built-in sort may be used or not. Write the sort method as appropriate:
/**
* Sorts the array; implement sorting as needed
*/
public static void sort(int[] arr)
{
Arrays.sort(arr);
}
/*
* outputs the array if one cannot use Arrays.toString(arr)
*/
public static void outputArray(int[] arr)
{
for (int i = 0; i < arr.length; ++i) {
System.out.printf("%2d ", arr[i]);
}
System.out.println();
}
Sample main:
public static void main(String[] args)
{
// how many options for the lottery; here it is 6
final int numEntries = 6;
// this method obtains from user
int[] userEntries;
userEntries = getUserSelections(numEntries);
sort(userEntries);
// display User selections
outputArray(userEntries);
int[] lottery = getLotteryNumbers(numEntries);
sort(lottery);
// display lottery numbers
outputArray(lottery);
// see how many match
int matches = 0;
// see if the user entry exists in the lottery; if so, we
// have a match
for (int i = 0; i < userEntries.length; ++i) {
if (numberInArray(userEntries[i], lottery)) {
++matches;
}
}
System.out.printf("Found %2d matches%n", matches);
//
// TODO: calculate winnings based upon the number of matches
//
}
Having difficulty trying to write code for this problem above. Please find the code below. Have to read in 5 numbers and compute the frequency of positive numbers entered.
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive integer");
int number = input.nextInt();
for(int i = -2 ; i < 4 ; i++)
System.out.println("Positive Count is: " + i);
}
}
Your problem is that you have a task that needs to be repeated (about the user entering a value); but your loop (the perfect mean to do things repeatedly) ... doesn't cover that part!
for(int i=-2 ; i<4 ; i++)
System.out.println("Positive Count is: " +i);
Instead, do something like:
for (int loops = 0; loops < 5; loops++) {
int number = input.nextInt();
Then of course, you need to remember those 5 values, the easiest way there: use an array; Turning your code into:
int loopCount = 5;
int numbers[] = new[loopCount];
for (int loops = 0; loops < loopCount; loops++) {
numbers[loops] = input.nextInt();
And then, finally, when you asked for all numbers, then you check the data you got in your array to compute frequencies. A simple approach would work like this:
for (int number : numbers) {
if (number > 0) {
System.out.println("Frequency for " + number + " is: " + computeFrequency(number, numbers));
}
with a little helper method:
private int computeFrequency(int number, int allNumbers[]) {
...
Please note: this is meant to get you going - I don't intend to do all your homework for you. You should still sit down yourself and figure what "computing the frequency" actually means; and how to do that.
Try this one, Remember if you only want to know the frequency(not storing)
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
int i = 1;// is a counter for the loop
int positive =0;// counts positive numbers
while(i<=5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole positive number");
int number = input.nextInt();
if(number > 0){
positive ++;
}
i++;
}
System.out.println("Positive Count is: "+ positive);
This is what I have so far. I am supposed to write this code with a For loop and if/else statement, but /i am stuck on how to do it properly. It would be nice if someone can tell me how to properly use a For loop and if/else statement together instead of giving the answer:
import java.util.*;
public class SumEvenOdd
{
public static void main(String []args)
{
Scanner keyboard= new Scanner(System.in);
int counter;
int i= 0;
int num=0;
int sumOdd= 0;
int sumEven= 0;
System.out.println("Enter integers other then Zero: ");
num=keyboard.nextInt();
System.out.println("The numbers you entered are: ");
for (i =num; i !=0; i=i)
{
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
i = keyboard.nextInt();
}
System.out.println("Even sum: " + sumEven);
System.out.println("Odd sum: " + sumOdd);
}
}
Your loop never executes because your loop condition is false to begin with:
for (i =num; i !=0; i=i) // i already equals 0 so i != 0 equates to false
You also aren't incrementing or decrementing with i=i so even if your condition was true you'd be stuck in an infinite loop. Use i++ to increment the value of i by 1 in each iteration of your for loop.
Also, you're only taking in one number from the user. One simple way of handling this would be to first ask the user how many numbers they want to enter first, then use that input to loop that many times asking for the numbers to sum. For example:
System.out.println("How many numbers do you want to enter? ");
num=keyboard.nextInt();
int[] addThese = new int[num]; // create an array of size num to store numbers
for(int i = 0; i < num; i++) {
System.out.print(": ");
addThese[i] = keyboard.nextInt();
}
// now use your for loop to iterate over addThese[] and find your sums
...
EDIT
You've confused yourself (and me) with your print statements and lack thereof. Your program runs fine but I don't think you're realizing it because of this.
Add something like this inside your loop so you know it's waiting for input:
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
System.out.print(": "); // <-- let the user know you're expecting more input
i = keyboard.nextInt();
You can use an array like I used above to store the user input so you actually can tell the user what numbers they entered.
In your application you do not need a for loop as you are breaking the loop as long you dont enter 0.
for loops is used to iterate through collections (for each loop) or iteratively increment a counter till it satisfies the break(classic for loop).
A do while(i!=0) loop would be more appropriate in your scenario.
If you want the answer in while loops
import java.util.*;
/*
EXPLANATION
Question: write a program that reads a set of integers and tells the sum of the even and odd numbers
First: Initialize 4 variables(all integers)
Second: Take input and print title
Third: Take a while loop that will run when i is smaller than a
Fourth: take inputs of the numbers and check for condition od or even and add the numbers
Fifth: Break the while loop if input =
*/
public class EvenOddSum
{
public static void main(String[]args)
{
//initializing variables
int InputNums = 0, OddNums = 0, EvenNums = 0, loopingVar = 0, PrintAmount;
//initializing scanner class
Scanner scanner = new Scanner(System.in);
//Input using Scanner
System.out.print("How many numbers you want to input: ");
PrintAmount = scanner.nextInt();
//Loop to execute if PrintAmount is bigger than or equal to The loop Variable
while(loopingVar <= PrintAmount)
{
//increase Loop Variable by 1 if it is smaller than PrintAmount
loopingVar++;
//The input which will be sorted into odd or even
System.out.print("Please input a number : ");
InputNums = scanner.nextInt();
//Conditional statements to Sort Input into Odd or even
if (InputNums % 2 == 0)
{
//store input numbers into OddNums var if it is not divisible by 2
OddNums = OddNums + InputNums;
}
else
{
//store input numbers into EvenNums var if it is divisible by 2
EvenNums = EvenNums + InputNums;
}
if(loopingVar == PrintAmount)
{
//If the loop variable is equal to the print amount the break will end the loop
break;
}
}
//if the condition is true the sums are printed and the code is stopped
if (loopingVar == PrintAmount)
{
System.out.println("Sum of even numbers is : " + OddNums);
System.out.println("Sum of odd numbers is : " + EvenNums);
System.exit(0);
}
//if InputNums is smaller than 0 there has been some error in the code
if (InputNums < 0)
{
System.out.print("Invalid input");
System.exit(0);
}
}
}
Scanner input = new Scanner(System.in);
int num;
int i;
int x = 0;
int y = 0;
System.out.print("How many numbers you want to input: ");
i = input.nextInt();
for (;;) {
i--;
System.out.print("Please input a number : ");
num = input.nextInt();
if (num % 2 == 0) {
x = x + num;
} else {
y = y + num;
}
if (num < 0) {
System.out.print("Inivald input");
System.exit(0);
}
if (i == 0) {
System.out.println("Sum of even numbers is : " + x);
System.out.println("Sum of odd numbers is : " + y);
System.exit(0);
}
}
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// printing the sum of even and odd number input from the user
int evensum = 0 ;
int oddsum = 0 ;
System.out.println("Enter the number:");
for(int n1= sc.nextInt(); n1>0; n1=sc.nextInt()) {
if(n1 % 2 == 0) {
evensum+=n1 ; // evensum = evensum + n1 ;
}
else {
oddsum+=n1 ; // oddsum = oddsum + n1 ;
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
// asking for continuing y or n?
System.out.println("Do you want to continue ? yes = 1 or no = 0");
int choice = sc.nextInt();
if(choice==1) {
System.out.println("Enter the number :");
}
else {
System.out.println("End");
break;
}
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
}
}
import java.util.Scanner;
public class good
{
public static void main(String[] args) {
Scanner variable = new Scanner(System.in);
int i = 0, counter = 0, n = 0;
for (i = 0; i < 5; i++) {
n = variable.nextInt();
}
if ((0 <= n) && (n <= 9)) {
counter++;
}
System.out.println("the number of values enterd from 0-9 is " + counter);
}
}
I have no errors in my program but I'm not getting a right answer. For example :
----jGRASP exec: java good
5
6
4
the number of values enterd from 0-9 is 0
----jGRASP: operation complete.
I shoud get "3"
but I get "0"
Your code doesn't work because you are missing brackets on your for loop. You just execute n=variable.nextInt() five times without checking it, and then check it. If you include brackets this should work.
You need to use braces around your the inner for loop
import java.util.Scanner;
public class good
{
public static void main(String[] args)
{
Scanner variable=new Scanner(System.in);
int i=0,counter=0,n=0;
for(i=0;i<5;i++){
n=variable.nextInt();
if((0<=n)&&(n<=9))
counter++;
}
System.out.println("the number of values enterd from 0-9 is "+counter);
}
}
Your main problem is not understanding when your for loop ends. You should add brackets { } around loops and if statements, so that only the code inside those brackets executes when the conditions are met.
public static void main(String[] args)
{
Scanner variable = new Scanner(System.in);
int counter = 0;
for(int i = 0; i < 5; i++)
{
int n = variable.nextInt();
if(0 <= n && n <= 9)
{
counter++;
}
}
variable.close();
System.out.println("the number of values enterd from 0-9 is: " + counter);
}
You should also close your Scanner.
Short tutorial on loops.