Java; looking for lowest Int [closed] - java

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 4 years ago.
Improve this question
Hi I need help with finding the the lowest income.
Here is the link for the codeCheck
http://www.codecheck.it/files/18030103413ucpa6f7ev1gbmexv0tlv2av3
the code i have written is at the bottom. I Cannot figure out why its the output doesn't show. Thank you in advance.
Companies report net income every quarter of the year. Some quarters Amazon's net income per share is positive, and some quarters it is negative. (It is always small because Amazon reinvests any profits in the business.)
Write an application (A program that has a main methods) called AmazonNetIncome to read a collection of integers, each representing a positive, negative or 0 net income for the quarter for 100 shares of Amazon stock. The input will terminate when the user enters a non-integer.
Use this prompt: System.out.print("Enter net income or Q to quit: ");
Note: you will actually quit on any string that can not be converted to an int.
Do the following:
find and print the number of profitable years (net income greater than 0.)
find and print the lowest net income
find and print the average net income
Only print the numbers if at least 1 integer was entered. Otherwise print "No values entered"
You will read the inputs one at a time and do all the processing as you go. No Arrays for this
The outputs should be on separate lines and in this order
number of profitable years
lowest net income
average net income
Do not initialize the minimum to 0 or some negative number. You can temporarily set it to 0 when you declare it but then initialize to the first input. You can use a boolean variable as a flag as discussed in the videos.
import java.util.*;
public class AmazonNetIncome
{
public static void main(String[]args)
{
Scanner in = new Scanner (System.in);
System.out.print("Enter net income or Q to quit: ");
double profit= 0;
int count = 0;
int count2 = 0;
int smalled =0;
double average = 0;
if(in.hasNextInt())
{
while(in.hasNextInt())
{
System.out.print("Enter net income or Q to quit: ");
int num = in.nextInt();
profit= profit + num;
count2++;
average = profit/count2;
if(num > 0)
{
count++;
}
if (num < smalled )
{
smalled = num;
}
}
System.out.println(count);
System.out.println(smalled);
System.out.println(average);
}
else
{
System.out.println("No values entered");
}
}
}

The problem was that you initialized some values that caused errors during the first iteration when you check for the smallest number.
I added the following condition that will set the smallest number to the current number, but only during the first iteration.
if (count2 == 1 || num < smalled ) {
smalled = num;
}

smalled starts out zero. You set smalled equal to the input number num whenever num < smalled. But if all your inputs are positive, num is never less than smalled. So smalled just stays at zero and incorrectly indicates that the smallest input was zero.
The simplest solution: initialize smalled to Integer.MAX_VALUE, the largest possible int value:
int smalled = Integer.MAX_VALUE;
That way, num < smalled will almost certainly become true at some point and thus cause smalled to be set to one the input values. And if num < smalled is never true, it can only be because all the inputs were equal to Integer.MAX_VALUE and thus the smallest value is, in fact, Integer.MAX_VALUE.

Related

Java program infinite loop in sum of even integers

I am creating a program that prints the sum of the even numbers from a range of 0 to the number that the user entered. For example, if the user entered the number 20, the program would calculate the sum of all of the even numbers between 0 and 20.
When I tested the program out with the number 10, it worked. But I tried using a different number, 35, and it was just stuck in an infinite loop. I would appreciate any and all help. The code will be posted below:
(Edit) Thanks for the feedback everyone! After talking with a friend, we realized that the solution is actually pretty simple. We were just making it complicated. Still, thanks for all of the suggestions.
//**************************************************************
// Prints the sum of the even numbers within a range of 0
// and the integer that the user enters.
//
// #me
// #version_1.0_11.7.17
//**************************************************************
import java.util.Scanner;
public class EvenNumbersSum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int user_num = 2; // variable that stores the user's number
int sum; // stores the sum of the needed values
System.out.print("Enter an integer greater than or equal to, 2: "); // prompt user for input
user_num = input.nextInt();
// checks to see if the value entered is valid or not.
while (user_num < 2)
{
System.out.println("Invalid entry. Must enter an integer greater than or equal to, 2.\n");
System.out.print("Enter an integer greater than or equal to, 2: ");
user_num = input.nextInt();
}
// starts adding the values
for (sum = 0; sum <= user_num;)
{
if (user_num % 2 == 0) // checks if the number is even
sum+=user_num; // add the number to sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
System.out.println(); // extra line for cleanliness
System.out.printf("The sum of the even numbers between 0 and %d is %d.", user_num, sum); // prints the result
}
}
Why are you writing loop for this, there are efficient way to do it.
Sum of numbers between 1-N = (N(N+1))/2
Sum of even numbers between 1-N = (N(N+2))/4
where N = user given input number till which you would like to add even numbers
NOTE: you can add validation on input number that it’s even by (n%2 == 0) and return error if it’s not
The variable you have used in condition (i.e. sum & user_num) no one changes in case of odd number and your code stuck in never-ending loop.
You should use counter variable ( e.g. i from 1 to user_num) and use that number in the condition. Example:
// starts adding the values
sum = 0;
for (int i = 0; i <= user_num; i++)
{
if (i % 2 == 0) // checks if the number is even
sum+=i; // add the number to sum
}
Your for loop should be like this.
int total_sum = 0;
for (int sum = 0; sum <= user_num; sum++)
{
if (sum % 2 == 0) // checks if the number is even
total_sum+=sum; // add the number to total sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
// note print total sum
System.out.println(totalsum);
your initial program just kept on checking entered number is even or odd.
And the entered number to sum.
So sum was always double of the entered number is even.
If entered number is odd it would go to infinite loop as entered_num(odd) % 2 == 0 always false and execute else statement.

Java code not adding up and giving correct output [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I am trying to get a basic java program running but it is not adding up and its giving me an infinite loop. Any help will be greatly appreciated.
Input : age of each patron (end of input denoted by a value < 0)
There are two categories of patrons:
Age 0 through 5 : Kids – no charge($0)
Age 5 through 18 : Students - $5
I am supposed to
Get the age of the patron
Determine which category that patron falls into & increase the number for that category
Keep doing steps 1 & 2 until the end of input is reached
Once end of input is reached
• Calculate the revenue generated for each category (number of patrons in a category * rate for that category)
• Total revenue for the day (sum of revenues of all 4 categories)
Generate output in the following format
• Perot Museum : Today’s Revenue
• Number of kids : *****
• Revenue from kids : $0
• Number of students : ****
• Revenue from students : $****
This is my code:
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
int kidsPrice = 0;
int studentPrice=5;
Scanner input = new Scanner(System.in);
int number = input.nextInt();
while(number > 0 ){
if (number >= 0 && number <= 5){
for(int i = 0; i < number; i++) {
int numOfKids = i;
System.out.println("Kids " + numOfKids);
}
System.out.println("Kids " + kidsPrice);
}
else if (number >= 5 && number <= 18){
for(int i = 0; i < number; i++) {
int numOfStudents = i;
}
System.out.println("Students");
}
--number;
}
}
}
It is not really doing any of the things I want, it is not adding the numbers and I need some pointers on what I am doing wrong and need to fix
Your attempt is halfway aligned but does not follow the problem statement for few reasons. Try and improve on these lines:-
Get the age of the patron
You've just read the number of patron, input their age within the while iteration and place your ifs on that age.
increase the number for that category
this can be achieved by a ++numberOfKids for example in one your if conditions
revenue generated for each category(number of patrons in a category * rate for that category)
Once you have values from (2) above. You know the rate(currently unused in your code), just to the maths as stated.
Total revenue for the day (sum of revenues...
The revenues that you would calcaulate in (3), add them to attain these.

Processing numbers program

Firstly, I'm taking AP Computer Science this year, and this question is related to an exercise we were assigned in class. I have written the code, and verified that it meets the requirements to my knowledge, so this is not a topic searching for homework answers.
What I'm looking for is to see if there's a much simpler way to do this, or if there's anything I could improve on in writing my code. Any tips would be greatly appreciated, specific questions asked below the code.
The exercise is as follows: Write a program called ProcessingNumbers that does:
Accepts a user input as a string of numbers
Prints the smallest and largest of all the numbers supplied by the user
Print the sum of all the even numbers the user typed, along with the largest even number typed.
Here is the code:
import java.util.*;
public class ProcessingNumbers {
public static void main(String[] args) {
// Initialize variables and objects
Scanner sc = new Scanner(System.in);
ArrayList<Integer> al = new ArrayList();
int sumOfEven = 0;
// Initial input
System.out.print("Please input 10 integers, separated by spaces.");
// Stores 10 values from the scanner in the ArrayList
for(int i = 0; i < 10; i++) {
al.add(sc.nextInt());
}
// Sorts in ascending order
Collections.sort(al);
// Smallest and largest values section
int smallest = al.get(0);
int largest = al.get(al.size() - 1);
System.out.println("Your smallest value is " + smallest + " and your largest value is " + largest);
// Sum of Even numbers
int arrayLength = al.size();
for (int i = 0; i < al.size(); i++) {
if (al.get(i) % 2 == 0) {
sumOfEven += al.get(i);
}
}
System.out.println("The sum of all even numbers is " + sumOfEven);
// Last section, greatest even number
if (al.get(arrayLength - 1) % 2 == 0) {
System.out.println("The greatest even number typed is " + al.get(arrayLength - 1));
} else {
System.out.println("The greatest even number typed is " + al.get(arrayLength - 2));
}
sc.close();
}
}
Here are specific questions I'd like answered, if possible:
Did I overthink this? Was there a much simpler, more streamlined way to solve the problem?
Was the use of an ArrayList mostly necessary? We haven't learned about them yet, I did get approval from my teacher to use them though.
How could I possibly code it so that there is no 10 integer limit?
This is my first time on Stackoverflow in quite some time, so let me know if anything's out of order.
Any advice is appreciated. Thanks!
Usage of the ArrayList wasn't necessary, however it does make it much simpler due to Collections.sort().
To remove the 10 integer limit you can ask the user how many numbers they want to enter:
int numbersToEnter = sc.nextInt();
for(int i = 0; i < numbersToEnter; i++) {
al.add(sc.nextInt());
}
Another note is that your last if-else to get the highest even integer doesn't work, you want to use a for loop, something like this:
for (int i = al.size() - 1; i >= 0; i--) {
if (al.get(i) % 2 == 0) {
System.out.println("The greatest even number typed is " + al.get(i));
break;
}
I wouldn't say so. Your code is pretty straightforward and simple. You could break it up into separate methods to make it cleaner and more organized, though that isn't necessary unless you have sections of code that have to be run repeatedly or if you have long sections of code cluttering up your main method. You also could have just used al.size() instead of creating arrayLength.
It wasn't entirely necessary, though it is convenient. Now, regarding your next question, you definitely do want to use an ArrayList rather than a regular array if you want it to have a variable size, since arrays are created with a fixed size which can't be changed.
Here's an example:
int number;
System.out.print("Please input some integers, separated by spaces, followed by -1.");
number = sc.nextInt();
while (number != -1) {
al.add(number);
number = sc.nextInt();
}
Here is a solution that:
Doesn't use Scanner (it's a heavyweight when all you need is a line of text)
Doesn't have a strict limit to the number of numbers
Doesn't need to ask how many numbers
Doesn't waste space/time on a List
Handles the case when no numbers are entered
Handles the case when no even numbers are entered
Fails with NumberFormatException if non-integer is entered
Moved actual logic to separate method, so it can be mass tested
public static void main(String[] args) throws Exception {
System.out.println("Enter numbers, separated by spaces:");
processNumbers(new BufferedReader(new InputStreamReader(System.in)).readLine());
}
public static void processNumbers(String numbers) {
int min = 0, max = 0, sumOfEven = 0, maxEven = 1, count = 0;
if (! numbers.trim().isEmpty())
for (String value : numbers.trim().split("\\s+")) {
int number = Integer.parseInt(value);
if (count++ == 0)
min = max = number;
else if (number < min)
min = number;
else if (number > max)
max = number;
if ((number & 1) == 0) {
sumOfEven += number;
if (maxEven == 1 || number > maxEven)
maxEven = number;
}
}
if (count == 0)
System.out.println("No numbers entered");
else {
System.out.println("Smallest number: " + min);
System.out.println("Largest number: " + max);
if (maxEven == 1)
System.out.println("No even numbers entered");
else {
System.out.println("Sum of even numbers: " + sumOfEven);
System.out.println("Largest even number: " + maxEven);
}
}
}
Tests
Enter numbers, separated by spaces:
1 2 3 4 5 6 7 8 9 9
Smallest number: 1
Largest number: 9
Sum of even numbers: 20
Largest even number: 8
Enter numbers, separated by spaces:
1 3 5 7 9
Smallest number: 1
Largest number: 9
No even numbers entered
Enter numbers, separated by spaces:
-9 -8 -7 -6 -5 -4
Smallest number: -9
Largest number: -4
Sum of even numbers: -18
Largest even number: -4
Enter numbers, separated by spaces:
No numbers entered

check a list how many is positive number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Write a program called PositiveNegative that reads an unspecified number of integers, determines how many positive and negative values have been entered, and computes the sum and average of the input values (not counting zeros). The reading of input ends when the user enters 0 (zero). Display the number of positive and negative inputs, the sum and the average. The average should be computed as a floating-point number. Design the program such that it asks the user if they want to continue with new inputs after each set of entries, ending the program only when they do not respond to the question with "yes".
Here is a sample run:
Input a list of integers (end with 0): 1 2 -1 3 0
# of positive inputs: 3
# of negative inputs: 1
The total: 5.0
The average: 1.25
Would you like to continue with new inputs? yes
Input a list of integers (end with 0): 0
No numbers were entered except 0
Would you like to continue with new inputs? no
and here is my code:
import java.util.*;
public class PositiveNegative
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String answer;
int countpositive = 0;
int countnegative = 0;
int total = 0;
int num = 0;
System.out.print("Input a list of integers (end with 0): ");
do{
String list = input.nextLine();
for(int i = 0; ; i=i+2 ){
num = Integer.parseInt(list.substring(i,i+1));
if( num == 0)
break;
else if ( num > 0)
countpositive++;
else if ( num < 0)
countnegative--;
total = total + num;
}
double average = total/(countpositive + countnegative);
System.out.println("# of positive inputs: "+countpositive);
System.out.println("# of negative inputs: "+countnegative);
System.out.println("The total: "+total);
System.out.println("The average"+average);
System.out.println("\n ");
System.out.print("Would you like to continue with new inputs? ");
answer = input.next();
}while(answer.equalsIgnoreCase("Yes"));
}
}
I can compile file, but when i run it, i can't get result like sample run.
You are decrementing (countnegative--;) the count of negative integers instead of incrementing it (countnegative++;) when a negative integer is encountered.

Java - Using for loop to average set of grades read in from keyboard

First time poster here. I'm aware of the negative stigma carried with asking for help on homework assignments, however I believe this would be an exception as this is an intro course and the professor stated specifically to use Google to find examples of for loops in Java (of which we have yet to even cover in class). I have absolutely no Java experience and would really appreciate any feedback:
Program asks user how many grades there are.
Program asks user for each grade (for loop needed and should sum grades within loop).
Take sum of all grades, compute average and store in a float variable grade.
Print grade value to console and append a number to a string such as "Grade Average is: " + grade
Example should read as:
Enter number of grades: 2
Enter grade: 90
Enter grade: 81
Grade Average is: 85.5
My code so far (not much here):
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
}
}
Edit:
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; ++i)
System.out.print("Enter grade " + (i + 1) + ": ");
grade = scan.nextFloat();
sum += grade;
System.out.println("The average of the grades is: " + sum/count);
}
}
This is what I have now, however a test displays incorrect results (example):
Enter number of grades: 2
Enter grade 1: Enter grade 2: 50 50
The average of the grades is: 25.0
Each grade needs to be entered on separate lines so the averaging is skewed as a result.
import java.util.Scanner;
public static void main(String[] args) {
int count = 0;
float sum = 0;
float grade = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; i++) {
System.out.print("Enter grade no " + (i + 1) + " : ");
grade = scan.nextFloat();
sum += grade;
}
System.out.println("Sum = " + sum);
System.out.println("Average = " + sum / (float) count);
}
Break the big task into smaller tasks , like #user2864740 said , write the algorithm (not code) on a paper then start translating that to code
u reached the part where u created a scanner to read input , now read the input and ....figure out the rest .
To learn how to read user input read this.
To learn how to make an integer out of Strings ur scanning read this
the rest is basic math really , read your textbook , and good luck ;)
edit : at least come out with some algorithm then maybe we'll help with the code
I won't solve the homework for you, I will help you however:
How to use a for loop:
for (int i = #startValue#; #booleanCondition#; #runTheFollowingCodeAtEachIteration#)
{
//code
}
ex:
for(int i = 0; i<10; i++)
{
System.out.println(i);
}
will display:
0
1
2
3
4
5
6
7
8
9
Your homework:
Program asks how many grades there are:
Scan a value called NumberOfGrades (called count in your code) inputted by the user.
Program asks user for each grade + sums the grades:
Use a for loop, with a starting value of i, and a upper limit of NumberOfGrades. Scan each grade and add it to a value called GradeSum, which initially should be 0 before entering the for loop.
Print value to console... :
Divide GradeSum by NumberofGrades, and display it how you would like it to be displayed.
Tips:
-Use System.out.print("\nEnter grade: "); in your for loop before each scan.
To avoid directly answering your homework question (which both won't help you get it and is probably not allowed), let's start with "what is a for loop?"
A for loop is a fancy loop that does the following things for you:
Initializes one (or more) variables to initial values the first time the loop statement is executed
Each iteration, checks a boolean condition to determine if it should loop again. If the expression evaluates to true, iterate again. Otherwise, break the loop and continue with the code following the loop.
A statement that is run each time the loop finishes iterating.
For example, the following loop would print the numbers 1 .. 10.
for(int i = 1; i <= 10; i++){
System.out.println(i);
}
The first part of the loop statement int i = 1 is the initialization block. i is initialized to an int with value 1 when the for loop is executed for the first time.
The second part of the loop statement i <= 10 is the boolean condition to check to determine if another iteration is required. In this case, i <= 10 evaluates to true if i is less than or equal to 10, and false once i hits 11 (or any larger number).
Finally, the third part i++ is the statement run when the for loop finishes an iteration. i++ adds 1 to the current value of i, thus i will increase in value by 1 each iteration.

Categories