public class Hello {
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
}
I would like to get the expected output given below. But, the Scanner class is reading only the first number. How do I correct this without creating multiple objects?
Output:
2
-1
-5
-3
9
8
0
The largest integer is 2
The number of negative integers in the sequence is 0
The largest even integer in the sequence is 2
The sum of numbers divisible by 3 is 0
Process finished with exit code 0
expected Output:
The largest integer is 9
The number of negative integers in the sequence is 3
The largest even integer in the sequence is 8
The sum of numbers divisible by 3 is 6
Thank you!
You only call console.nextInt() once, so only one number is read. If you want to call you need to loop over calls to console.hasNext(). Since you're using System.in. E.g.:
while (console.hasNextInt()) {
number = console.nextInt();
// calculations
}
You are only reading input once. I don't see a loop in your code, so number = console.nextInt(); only runs once. What you should do is put it inside a loop, exit the loop when you have all the numbers (how you check that can be done in multiple ways), and while you're inside the loop put whatever input you receive into an array or another data structure. After you're done collecting input, do your checks over all the numbers on your data structure.
1- You must first receive the data from the user and then calculate it and generate the output. You can do this using the arrays and after finishing put your data, calculate on them.
for example :
private static final int DATA_SIZE = 5;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> data = new ArrayList<>();
// put data in array
while (data.size() == DATA_SIZE){
data.add(scanner.nextInt());
}
// calculate data from array ...
}
2- When you call a field like nextInt() Scanner class , it is done only once, then you put it in a loop to be repeated several times ...
Of course, I have other suggestions for doing this
For example, you can use the array available in the main method (with knowledge, of course)
OR
First ask the user for the amount of data you have, then take it and then calculate
OR....
If you want to type all number at once ,you should set a terminal number. when you input all you number,you shoud add the terminal number to indicate input is over.
For example:
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
int endNumber = -1; //set the terminal number
do {
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
}while (number!=endNumber);
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
The line if code is only being executed once. Thus, the Scanner is only taking in the first in put. Use a while loop to take in multiple inputs.
Related
I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.
The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
int sumOfNumbers = 0;
double averagePositive = 0;
while (true) {
System.out.println("Give a number: ");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0)
break;
if (number > 0)
sumOfNumbers = number + sumOfNumbers;
if (number > 0)
numbers = numbers + 1;
if (number > 0)
averagePositive = (double)sumOfNumbers / (double)numbers;
}
System.out.println(averagePositive);
}
Try it as follows...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Give a number: ");
int num=input.nextInt();
int tot=0; //total
int count=0; // counting the positive numbers
if(num>0){
while(num!=0){
tot+=num;
count++;
System.out.print("Give a number: ");
num=input.nextInt();
if(num<0){
System.out.print("Not possible");
return;
}
}
double avg =(double)tot/n;
System.out.print("Average: "+avg);
}else{
System.out.println("Cannot calculate the average.");
}
}
I'd probably do it like this to keep it simple. Also in general, try not to cramp code together. Most formal project demand a certain degree of styling and usually spaces between operators and braces, etc... is required. In the long run it makes the code more readable and easier to maintain.
In your code there was no need to repeat the same if test for number > 0 multiple times, they could have all been bundled together. If the program was bigger and more complex I may have named the variable names with more qualification but for a short program like this, brief names were sufficient for clarity.
continue and break are important keywords to control loop behavior and can be used to increase brevity and clarity. continue goes back to the top of the loop immediately and break exits the innermost loop immediately. Dividing a double by an int yields a double so I was able to eliminate a cast. And the += operator makes it a little easier to read the line.
Also in Java and C any if() or else clause that contains one line doesn't require braces and unless a program is nested in such a way that adding the braces anyway adds to the clarity, it is often clearer to omit the braces in that case. The if statement illustrates both ways in a single statement.
import java.util.Scanner;
public class avg
{
static int count = 0;
static double sum = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter a sequence of positive numbers (0 to calculate average):\n");
while (true) {
System.out.print("Number? ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Negative numbers not allowed.");
continue;
} else if (n == 0)
break;
sum += (double)n;
++count;
}
System.out.println("Average of " + count + " numbers = " +
(double)(sum / count) + "\n");
System.exit(1);
}
}
Sample output:
$ java avg
Enter a sequence of positive numbers (0 to calculate average)
Number? 1
Number? 2
Number? 3
Number? 4
Number? 5
Number? -6
Negative numbers not allowed.
Number? 0
Average of 5 numbers = 3.0
The project is to create a program that takes input from the user in JOption Pane and checks if a number is prime or not. The program is supposed to loop until the user enters 0, which triggers the program to calculate max, min, sum, count, and average.
Ive completed 99% of the assignment, except the first number that I enter does not get printed out like the others but it still gets included in calculations
import javax.swing.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// Main Method
userInput();
}
public static void userInput() {
int number;
int sum;
int count; // declaring variables
int max= 0;
int min= 1;
float average;
String userNumber; // Number typed by user
sum = 0; // start at 0 for sum
count = 0; // start at 0 for counter
// prompt user to enter a positive number
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
// convert to int
number = Integer.parseInt(userNumber);
// if the number entered is positive and not 0, the loop repeats
while ( number != 0 && number > 0) {
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
// checking if number entered is prime or not
int i,m=0,flag=0;
m=number/2;
if(number==0||number==1){
System.out.println(number+" is not a prime number");
}else{
for(i=2;i<=m;i++){
if(number%i==0){
System.out.println(number+" is not a prime number");
flag=1;
break;
}
}
if(flag==0){ System.out.println(number+" is a prime number"); }
}
}
if ( count != 0 ) {
// as long as one number is entered, calculations are done below
// calculate average of all numbers entered
average = (float) sum / count;
// printing out the results
System.out.printf("The average is : %.3f\n", average);
System.out.println("The sum is : "+sum);
System.out.println("The count is : "+count);
System.out.println("The max is : "+max);
System.out.println("The min is : "+min);
}
}
}
i need the first entry to print like the rest, please help me find where to put in the loop
Can you explain more what you need? What input do you give it and what output do you see?
I noticed that you're adding numbers before the call to JOptionPane, is it possible that you have count larger by one than your actual count of numbers? Your indentation is terrible, you should clean it up, I'm having trouble reading the code period.
// 1 START OF LOOP
while ( number != 0 && number > 0) {
// 2 ADD NUMBER TO SUM
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
// 3 THEN GET INPUT. WHAT???
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
You have several issues in your program. The reason why the first number is never considered is that you have
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
two times in your code (before the while loop and in the while loop).
I would suggest to initialize number with Integer.MAX_VALUE: number = Integer.MAX_VALUE;
Then remove
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
before the while loop.
There is a & missing in if (number < min & number != 0)min=number;
=>
if (number < min && number != 0) {
min=number;
}
The condition in the while loop can be simplified by writing while ( number > 0) { because > 0 means != 0 too.
I would also suggest to write your code a little better for readability. Always use curly braces for conditions (if), even when you only execute one line if the condition is true.
I hope this helps. Let me know if you need more help but you should be able to solve this assignment now on your own :)
Good afternoon everyone,
I'm currently trying to create a program that does the following:
Develop a code that will print all prime numbers up to the user's entered
number. An example of the output:
Enter an integer (2 or above): 19
The prime numbers up to you integer are:
2
3
5
7
11
13
17
19
Unfortunately, there is also a list of "requirements" that need to be met as well:
If the user enters a number below 2, your program should print a message that the number is not valid, and then stop.
A number is a prime number if it is not divisible by any number except 1 and itself.
For this program, in order to test a number to see if it is prime, you should try to divide the number by every value from 2 up to the number-1, to see if it divides evenly or not. For example:
--To see if 5 is a prime number:
5 does not divide evenly by 2
5 does not divide evenly by 3
5 does not divide evenly by 4
therefore 5 is a prime number
--To see if 9 is a prime number:
9 does not divide evenly by 2
9 divides evenly by 3
therefore 9 is not a prime number
This program requires you to write nested loops (that is, a loop inside a loop). One loop will be used to count from 2 up to the user's number so that you can test each of these numbers to see it it is prime. For each of these numbers, x:
A nested loop will check all values from 2 up to x-1 to see if x divides evenly by any of them.
You will need to use a Boolean variable (also referred to as a flag variable) to help you determine whether or not to print a number to the screen
The question above is in regards to my code so far below:
import java.util.*;
public class Something3 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
//Variable declaration.
int limit, number;
//get input till which prime number to be printed
System.out.print("Enter an integer (2 or above): ");
limit = kbd.nextInt();
kbd.close();
//Will print prime numbers till the limit (user entered integer).
number = 2;
if (limit >=2) {
System.out.println("The prim numbers up to your interger are: " + limit+"\n");
for(int i = 0; i <= limit;){
//print prime numbers only
if(isPrime(number)){
System.out.println(number +"\n");
i++;
}
number = number + 1;
}
}
else
System.out.println("Number is not vaild");
}
//Prime number is not divisible by any number other than 1 and itself
//return true if number is prime.
public static boolean isPrime(int number){
for(int i=2; i==number; i++){
if(number%i == 0){
return false; //Number is divisible, thus not prime.
}
}
return true;//The number is prime.
}
}
Is the limit variable I'm using the issue? Any help would be much appreciated.
your isPrime() method is returning wrong result. for loop condition is wrong i==number it should be i < number
public static boolean isPrime(int number){
for(int i=2; i*i <= number; i++){
if( number % i == 0){
return false; // Number is divisible, thus not prime.
}
}
return true; //The number is prime.
}
To check a number prime or not you don't have to check divisbility from 2 to N, all you need to check upto sqrt(N).
To find prime numbers in a range(N) use Sieve of Eratosthenes
Your actual problem was number variable. Here's your solution. There's no need of variable number. Below is your solution
import java.util.*;
public class Something3 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
// Variable declaration.
int limit;
// get input till which prime number to be printed
System.out.print("Enter an integer (2 or above): ");
limit = kbd.nextInt();
kbd.close();
if (limit >= 2) {
System.out.println("The prim numbers up to your interger are: "
+ limit + "\n");
for (int i = 1; i <= limit; i++) {
// print prime numbers only
if (isPrime(i)) {
System.out.println(i);
}
}
} else
System.out.println("Number is not vaild");
}
// Prime number is not divisible by any number other than 1 and itself
// return true if number is prime.
public static boolean isPrime(int n) {
if (n % 2 == 0)
// The only even prime is 2.
return (n == 2);
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return false;
}
return true;
}
}
import java.util.Scanner;
class prime
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the value of n");
int n=sc.nextInt();
for(int i=2;i<=n;i++)
{
int count=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
System.out.println(i+" ");
}
}
}
}
Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4.
Design the program such it allows the user to re-run the
program with a different inputs in the same run.
public void findLargestInteger(){
//create Scanner object
Scanner input = new Scanner(System.in);
int x;
do {
//prompt user input
System.out.print("Enter an integer, the input ends if it is 0:");
//declare variables
int n, countNeg = 0, countPos = 0;
float sum = 0;
//calculate how many positive and negative values, total, and average
while ((n = input.nextInt()) != 0) {
sum = sum + n;
if (n > 0) {
countPos++;
}
else if (n < 0) {
countNeg++;
}
}
//display results
if (countPos + countNeg == 0) {
System.out.println("No numbers are entered except 0");
System.exit(0);
}
System.out.println("The number of positives is " + countPos);
System.out.println("The number of negatives is " + countNeg);
System.out.println("The total is " + sum);
System.out.println("The average is " + (sum / (countPos + countNeg)));
}while ((x = input.nextInt()) != 0);
}
How can I get the prompt to display correctly at the end and keep it
running?
Output:
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0 The average is 3.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0
The average is 3.0
You could change while((x = input.nextInt()) != 0); to while(true); if you really want to keep repeating your program.
That IS an infinite loop though which is not really a good way to go.
So instead of looking for the next integer and compare with 0, maybe you should write something like
System.out.print("Do you want to quit? (y/n): ");
at the end of your loop (right before the while((x = input.nextInt()) != 0) line).
And then not check for 0 but for the y. At least then you don't have the program waiting for the user to input something without knowing what's happening.
Edit: Or you can just use a counter if you want to run it like twice or three times before it terminates ;)
Have you tried just calling your function inside a while loop?
public void findLargestInteger() {
// Your code
}
public static void main(String[] args) {
do {
findLargestInteger();
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Would you like to continue? (0/1) ");
int n = reader.nextInt();
} while(n == 1);
}
I am trying to find the even sum and even max from numbers inputted by the user. For example, if they answered "How many integers?" with 4 and inputted the integers: 2, 9, 18, 4 it should output:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 24
even max = 18
Here is my code:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
//prompt user to enter the first integer
System.out.print("next integer? ");
int firstNum = console.nextInt();
//set the even max to the firstNum
int evenMax = firstNum;
//set the evenSum to zero
int evenSum = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 2; i <= numbers; i++) {
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the first number is even
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
//check to see if the numbers entered are even
if (num % 2 == 0) {
//if they are even add them to the evenSum
evenSum += num;
}
//check to see if the number entered is bigger than the first number
if (num > firstNum) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
But here is what is my output is:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 28
even max = 4
Could someone help me figure out what the problem is?
You were doing some really weird stuff where the first time a number was entered it was treated as special. This was causing the first even number entered (2, in this case) to be added multiple times to the total.
Put all of your input in the same loop so you can treat everything equally:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
int evenSum = 0;
int evenMax = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 0; i < numbers; i++) {
//input new number
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the number is even. if it is not even,
//we don't care about it at all and just go to the next one
if (num % 2 == 0){
//add it to the sum
evenSum += num;
//if it's larger than the maximum, set the new maximum
if (num > evenMax) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
As you can see, this code also only checks to see if a number is even once. There is no need to be continuously checking if num is even every time you use it: its value is not changing during the duration of a single run of the loop.
Move the following code inside the for loop to just before the for loop-
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
This will prevent the repeated addition of the first number in the evenSum
You also want
if (num > evenMax) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
or, alternatively
if (num > evenMax && num % 2 == 0) {
evenMax = num;
}
In your scenario, firstNum is 2 so every number after it is technically larger, so you will (theoretically) not get the largest even number entered after the first number.
Either move the first if condition inside the for loop upwards (outside of the for loop)
or store all of the user inputs in a data structure i.e. Array before processing them.
Storing them in Array would make it easier to manipulate the data.
Working code:-
Scanner console = new Scanner(System.in);
int numbers =0, firstNum =0, num =0 ;
System.out.print("how many integers? ");
numbers = console.nextInt();
System.out.print("next integer? ");
firstNum = console.nextInt();
int evenMax = 0;
int evenSum = 0;
if(firstNum%2==0)
{
evenSum = firstNum;
evenMax = firstNum;
}
for (int i = 1; i < numbers; i++) {
System.out.print("next integer? ");
num = console.nextInt();
if (num % 2 == 0) {
//don't add firstNum multiple times to the evenSum, earlier it was added every time you entered an even number
evenSum += num;
//check if the number you entered, i.e. num greater than the already existing greatest number i.e. evenMax and if so update it
evenMax = num > evenMax: num?evenMax;
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
Hope this helps. There are three major problems in your code:-
The firstNum(if it's even) gets added to the sum every time you enter a even number. i.e. if first number is 4 and the loop runs 10 times and encounter 6 even numbers, then along with the even number 4 also gets added six times. If you want to use it as a special number and get it's value separately then you'll have to add it to the sum before the loop.
You should compare every new even number to the previous greatest even number and hence set the value of evenMax. You are comparing them to the firstNum so if the first number is 2 and the last even number is anything greater than two, it would be set as the value of evenMax. Compare every even number to the current maximum even number i.e current value of evenMax.
You don't check if the first number is evenor not and assign it to even max. So if it is 999999 it still get's assigned, but it is not even.
Please check it as correct answer and vote up if you find it useful.