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.
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
So I am doing this project. And I need to
Write a program that finds the factors and number of factors for an integer.
Factors will be listed on 1 line for smallest to largest with a space separating each.
Continuously accept input until a 0 is entered, which is the sentinel. Do not factor 0.
I got the factoring part. This is the output I am currently getting.
Enter an Number
12
The factors are
1 2 3 4 6 12
It stops immediately after giving the factors. I am not sure on how to implement it to re prompt. I have tried loops but its not working. Also,How can I exclude 1 and the entered number.
This is how my output should look. It should stop once 0 is entered.
Enter a number: 12
There are 4 factors for the number 12: 2 3 4 6
Enter a number: 25
There are 1 factors for the number 25: 5
Enter a number: 100
There are 7 factors for the number 100: 2 4 5 10 20 25 50
Enter a number: 13
There are 0 factors for the number 13:
Enter a number: 0
Here is the code.
package com.FactorsProgram;
import jdk.swing.interop.SwingInterOpUtils;
import java.sql.SQLOutput;
import java.util.Scanner;
//Java Program to print all factors of a number using function
public class Main {
public static void main(String[] args) {
int N;
Scanner scanner;
scanner = new Scanner(System.in);
System.out.println("Enter an Number");
N = scanner.nextInt();
// Calling printFactors method to print all
// factors of N
printFactors(N);
}
//This method prints all factors of N
public static void printFactors(int N) {
int i;
//Check for every number between 1 to N, whether it divides N. If K
//divides N, it means K is a factor of N
System.out.println("factors for the number " );
for (i = 1; i <= N; i++) {
if (N % i == 0) {
System.out.print(i + " ");
}
}
}
}
You had the right idea with having a loop - you need to loop and check that n isn't 0. E.g.:
System.out.println("Enter an Number");
n = scanner.nextInt();
while (n != 0) {
// Calling printFactors method to print all
// factors of N
printFactors(n);
System.out.println("Enter an Number");
n = scanner.nextInt();
}
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.
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
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 8 years ago.
Improve this question
I'm totally new in Java programming , I wonder how may I write program that reads an arbitrary number of positive integers from the keyboard and then prints them in reverse order. The reading stops when the user inputs a negative number. An example of an execution:
Enter positive integers. End by giving a negative integer.
Integer 1: 5
Integer 2: 10
Integer 3: 15
Integer 4: 20
Integer 5: -7
Number of positive integers: 4
In reverse order: 20, 15, 10, 5
Get your input inside a do-while loop until the loop condition becomes false, means y is negative. Since you've got i value incremented before your loop condition is false, decrement i value by 1 outside loop.
Next, inside the decrementing for loop, print your variables in decreasing index of array, so it will be printed in reverse order of input.
import java.util.*;
/**
*
* #author Capt. Jack Sparrow, pirate lord of the seven seas
*/
public class Example {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner s1 = new Scanner(System.in);
int[] x = new int[50];
int i =0, y;
do
{
System.out.println("Enter new positive integer: ");
y = s1.nextInt();
x[i] = y;
i++;
}while( y >= 0);
i--;
System.out.println("Number of positive integers: "+i);
System.out.print("In reverse order: ");
for(int j = i; j >0; j--)
{
System.out.print(x[j-1] + " ");
}
System.out.println();
}
}
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
I am trying to write a code that asks the user to enter a 2 digit number. In case the user enters anything but a two digit number the program is supposed to ask the user to reenter the number. I came up with a code that uses a while loop. The code however does not work. Any help would be greatly appreciated. Thank you very much
This is the code I come up with :
import java.util.Scanner;
class Pelindrone {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println(" Enter 2 digit number");
num = input.nextInt();
while(num < 10) {
System.out.println("Enter 2 digit number");
num = input.nextInt();
while(num > 99) {
System.out.println("Enter 2 digit number");
num = input.nextInt();
}
}
}
}
You may try this... Just copy my entire main method and replace with yours.
You only need few lines of code to do the job.
Assuming you just want to validate an input to ensure it is only 2 digits. Without using an advance stuff in java, you may do it this way.
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int num;
do
{
System.out.print("Enter a 2 digit number");
num = nextInt();
}while (num > 99 || num <10);
}
This is good enough for the whole thing to work. Trust me.
You don't need nested loops to do that simple task. Only use nested loops when you really have the needs. You can just combine multiple conditions in one statement and place inside the loop.
As for why your codes didn't work well
That is because of the condition in your outer while-loop. It will only run when user enters a number less than 10. But if user enters anything more than 10 (2,3,4,5,6,n digits), Your outer while-loop (for validation) won't run at all.
Your code runs fine if you initially give it a value that is < 10 because then it has a chance to enter the first while loop. I've check it in Ideone here for the consecutive inputs {-5, 0, 1, 9, 100, 1001, 50}, and the code ends at 50 as expected.
The problem occurs if your first value is > 10 because then it will completely skip all of the inner while loops. This means that you are only guaranteed the first value is > 10 but not < 100. I've checked this here using input of {100, 1001, 50} the code ends on 100 even though it should end on 50.
To get this to work, you need to check both conditional statements at the same time (num < 10 || num > 99). In addition, I would suggest removing the code duplication by using a do-while structure. The do-while checks it's conditional statement after each run. This will allow you to remove your initialization statement. The code is below (see the Ideone here).
Scanner input = new Scanner(System.in);
int num;
do{
System.out.println("Enter 2 digit number");
num = input.nextInt();
} while(num < 10 || num > 99);
System.out.print("Your number is:" + num); // guaranteed that 10 <= num <= 99
The only reason this doesn't work is because when you enter a three digit number, it never gets to the inner while loop.
You can just simply have one while loop that check for either condition (less than 2 or more than 2):
import java.util.Scanner;
class Pelindrone {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println(" Enter 2 digit number");
num = input.nextInt();
while(num < 10 || num > 99) {
System.out.println("Enter 2 digit number");
num = input.nextInt();
}
}
}
If you enter more that 2 digits, which you might want to say by does not work, The first while condition does not catch and the program terminates. You need to catch that case in the first while too instead of the redundant inner one.
class Pelindrone {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println(" Enter 2 digit number");
num = input.nextInt();
while(num < 10 || num > 99) {
System.out.println("Enter 2 digit number");
num = input.nextInt();
}
input.close();
}
}