I have to make a program that allows the user to enter integer numbers until he press '0'. The program has to print:
1)The total number of the entered numbers
2) The number of the positive ones
3) The average of the positive ones
4) The number of the negative ones
5) The sum of the negatives
So far, all I could do is make the "enter untill '0' is pressed" and find the number of the entered numbers, which is a lot for me and my programing skills. I am having troubles trying to find out if the number is positive or negative. Probably I am not comparing them right, so I would love if I get a little help from someone advanced.
Here's my code so far:
import java.io.*;
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
} while(!str.equals("0"));
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Firstly as pointed out Integer.parseInt is used in java to convert from String to int.
Secondly you need to have a extra variable to store and accumulate the total of positive numbers too. I have added a try-catch exception block to handle errors.
Here is a code for reference.
import java.io.*;
public class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
int PositiveSum = 0; // Added extra variable
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
try{
do {
EnteredNumbers++;
str = br.readLine();
int num = Integer.parseInt(str);
if (num>0)
{
Positive++;
PositiveSum+=num;
}
else if (num<0)
{
Negative++;
NegativeSum+=num;
}
} while(!str.equals("0"));
AveragePositive = (double)PositiveSum/(double)Positive;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
catch (java.lang.NumberFormatException e)
{
System.out.println("Wrong format");
}
}
}
Output if there are no errors
Enter '0' to quit.
Enter Numbers:
1
5
5
-5
-5
0
You have have entered 5 numbers!
You have have entered 3 Positive numbers!
The Average of the Positive Numebers is 3.6666666666666665!
You have have entered 2 Negative numbers!
The Sum of the Negative numbers is -10!
check by parsing String to int
Integer.parseInt(str)>0 //positive number
Integer.parseInt(str)<0 //negative
do {
EnteredNumbers++;
str = br.readLine();
int number= Integer.parseInt(str);
if(number>0){ //do positive stuffs}
else if(number<0){//do negative stuffs}
} while(!str.equals("0"));
Hope the below code achieves what you want to do
import java.io.*;
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
double PositiveSum = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
if(Integer.parseInt(str) > 0){
Positive++;
PositiveSum = PositiveSum + Integer.parseInt(str);
AveragePositive = PositiveSum/Positive;
}
if(Integer.parseInt(str) < 0){
Negative++;
NegativeSum = NegativeSum + Integer.parseInt(str);
}
} while(!str.equals("0"));
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Create a list and keep adding the numbers into List. You should do something like:
List<Integer> numberList = new ArrayList<Integer>();
do {
str = br.readLine();
int number = Integer.parseInt(str);
} while(number != 0);
And then use for loop to do count like:
int negativeNumberSum = 0;
int positiveNumberSum = 0;
int positiveNumberCounts = 0;
for (int i =0; i<numberList.size(); i++) {
if (numberList.get(i) >= 0) {
positiveNumberSum += numberList.get(i);
positiveNumberCounts ++;
} else {
negativeNumberSum += numberList.get(i);
}
}
//print average of positive as positiveNumberSum /(double) positiveNumberCounts if positiveNumberCounts != 0
//print average of positive as negativeNumberSum / (double)(numberList.size() - positiveNumberCounts) same if (numberList.size() - positiveNumberCounts) != 0
//print positive count as positiveNumberSum and same for negative.
//
Try using Integer.parseInt() to get an int from your string str, and checking to see if the integer is < 0 (negative) or > 0 (positive)
I have added an extra variable called PositiveSum to assist with the AveragePositive calculation.
In order to perform this calculation, you need to ensure the value is an Integer so I have added the parse statement.
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
int PositiveSum = 0;
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
int number = Integer.parseInt(str);
if(number<0) {
Negative++;
NegativeSum += number;
} else if(number>0) {
Positive++;
PositiveSum += number;
}
} while(!str.equals("0"));
AveragePositive = PositiveSum / EnteredNumbers;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Change your do-while loop: it is using Strings, not integers:
do {
EnteredNumbers++;
num = sc.nextInt();
} while(num != 0);
Also, you need to import the scanner utility:
import java.util.Scanner;
Don't use a BufferedReader, but use:
static Scanner sc = new Scanner(System.in);
Also, you would want to use a checker for your positive and negative numbers inside your do-while loop:
if(Integer.parseInt(num)<0) { Negative++; }
else { Positive++; }
I've also added a try-catch statement to handle an error if someone doesn't enter an int:
try {
num = sc.nextInt();
}
catch(Exception e) {System.out.println("Invalid integer"); System.exit(0); }
I added a little bit of code that takes the 0 off when it prints the numbers, as I realise it will include 0 when you type it in to exit.
Change your class statement to public, it's just programming:
public class Nums {
Also, I add a negative-number counter in the main code, and an averager.
Here is the complete code, to avoid confusion:
import java.io.*;
import java.util.Scanner;
public class prime {
static Scanner sc = new Scanner(System.in);
public static void main(String args[])
{
int EnteredNumbers = 0;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
int num = 0;
int PosTotal = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
try {
num = sc.nextInt();
}
catch(Exception e) {System.out.println("Invalid integer!"); System.exit(0); }
if(num<0) { Negative++; NegativeSum += num; }
if(num>0){ Positive++; PosTotal += num; }
EnteredNumbers++;
} while(num != 0);
AveragePositive = PosTotal / Positive;
EnteredNumbers -= 1;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numbers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Hope it helps!
Note I have trial-tested it, and it works brilliantly. If you have any errors with this please tell me :)
Related
I'm fairly new to Java and the problem I am having is that this code compiles, but does not run after the hexadecimal conversion; it instead just ends after the method hexCharToDecimal. I can't reuse method main and I'm not sure how to call the method intreverse and actually have it run. Is there a way to get back into main or do I have to call intreverse somewhere?
import java.util.Scanner;
public class Homework4 {
public static void main(String[]args) {
// Sum and average of a set of intergers entered by the user
// First we will declare some variables
int userInput = 1;
int positives = 0;
int negatives = 0;
int sum = 0;
int numCount = 0;
Scanner input = new Scanner(System.in);
// Will start a while loop that will stop when user enters 20 integers
while ((numCount <= 20)) {
System.out.println("Please enter a nonzero integer or enter 0 to finish ");
userInput = input.nextInt();
if (userInput == 0) {
break;
} else if (userInput > 0) {
positives += 1;
numCount += 1;
sum = sum + userInput;
} else if (userInput < 0) {
negatives += 1;
numCount += 1;
sum = sum + userInput;
} else
System.out.println("Error, please enter an integer");
continue;
}
double average = (sum / numCount);
System.out.println("The sum of the entered integers is " + sum);
System.out.println("The average of the enetered integers is " + average);
System.out.println("There are " + positives + " positive integers and " + negatives + " negative integers");
// Convert Hexadecimal number to decimal
// Ask the user to input a string of 5 digits or less in hex
System.out.println("Please enter a hexadecimal number of up to 5 characters");
String hex = input.next();
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
}
// Now we will create the method to convert to decimal
public static int hexToDecimal(String hex) {
int decimal = 0;
for (int i = 0; i < hex.length(); i++) {
char hexcharacter = hex.charAt(i);
decimal = decimal * 16 + hexCharToDecimal(hexcharacter);
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') // check to see if there is any letters in the string
return 10 + ch - 'A';
else
return ch - '0';
}
// Print entered integer in reverse
public static void intreverse(String[]args) {
// Ask user for an integer to be reversed
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer to be reversed");
int number = input.nextInt();
reverse(number); // Method to be called
}
// Will now state our method
public static void reverse(int number) {
// use a while loop to get each digit
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
}
}
}
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
Will always run once because it is not enclosed in any sort of loop. If you want it to run again when the second case is called then enclose it in a while(true) loop and have a break statement in the first case where you want it to stop execution.
I have been trying to figure out why isn't my code working. If I don't do it through a method and put this code in the main method then it keeps repeating. I want to ask the user for a new number every time. And then see if the number is odd or even. If odd then increase the odd count add all the numbers that the user enters. The user should be asked to enter values until the number 0 is entered.
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("Enter number");
int oddnumbers = 0;
do {
int count = 0;
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
You should probably have the reading of a number "i = sc.nextInt();" inside the loop, and the variable count outside, like this:
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int oddnumbers = 0;
int count = 0;
int i=0;
do {
System.out.println("Enter number");
i = sc.nextInt();
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
This code gives the answer to tour spec/question
Reason for not working: You should take input inside do while loop and then check for odd.
public int numbers() {
Scanner sc = new Scanner(System.in);
int num = 0;
int oddSum = 0;
do {
System.out.println("Enter number");
num = sc.nextInt();
if(num == 0) {
break;
} else if (num % 2 != 0) {
oddSum += num;
}
} while (num != 0);
sc.close();
return oddSum;
}
public static void main(String[] args) {
Test n = new Test();
System.out.println(n.numbers());
}
In this java program you (the user) keeps entering numbers until you enter a zero, which is when the list terminates. It will compute the sum of positive even & sum of odd even and negative numbers. It will also compute the average.
I'm stuck at the part to get the average of sum of even positive numbers, sum of odd positive numbers, and sum of negative numbers.
import java.util.*;
class sumPositiveAverage {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println ("Enter numbers. List terminates when you enter a zero.
Enter a zero when you want to begin the addition.");
int a = sc.nextInt();
int esum=0;
int osum=0;
int nsum=0;
while (a !=0)
{
if (a>0)
{
if (a%2==0)
{
esum = esum+a;
}// end of 3rd innermost if statement
else
{
osum = osum+a;
}// end of 3rd else statement
}//end of 2nd middle if-else-loop
else if (a<0)
{
nsum=nsum+a;
}//end of 2nd middle else statement
}//end of while loop
System.out.println ("The sum of even positive numbers is "+esum);
System.out.println ("The sum of odd positive numbers is "+osum);
System.out.println ("The sum of negative numbers is "+nsum);
}//end of main
}//end of class2
import java.util.*;
public class sumPositiveAverage {
public static void main(String[] args)
{
int sum_even = 0;
int sum_odd = 0;
int sum_negative = 0;
int sum_positive = 0;
int count_even = 0;
int count_odd = 0;
int count_negative = 0;
int count_positive = 0;
double avg_sum_even = 0;
double avg_sum_odd = 0;
double avg_sum_negative = 0;
double avg_sum_positive = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
int data = 0;
do
{
System.out.print("Type in a positive or negative number and press enter key, if 0 is entered program stops: ");
data = input.nextInt();
if(data > 0){
if(data%2 == 0){
//even number
sum_even = sum_even + data;
count_even++;
}else{
//odd
sum_odd = sum_odd + data;
count_odd++;
}
sum_positive = sum_positive + data;
count_positive++;
}else if(data < 0) {
//negative number
sum_negative = sum_negative + data;
count_negative++;
}
}
//Stops if the value of data is ZERO(0) and continues if it's not
while(data != 0);
//here means zero has been entered
if(count_positive > 0) { avg_sum_positive = (double)sum_positive/count_positive; }
if(count_negative > 0) { avg_sum_negative = (double)sum_negative/count_negative; }
if(count_even > 0) { avg_sum_even = (double)sum_even/count_even; }
if(count_odd > 0) { avg_sum_odd = (double)sum_odd/count_odd; }
System.out.println("Sum of Positive Numbers = " + sum_positive);
System.out.println("Sum of negative Numbers = " + sum_negative);
System.out.println("Sum of odd Numbers = " + sum_odd);
System.out.println("Sum of even Numbers = " + sum_even);
System.out.println("Count of Positive Numbers = " + count_positive);
System.out.println("Count of negative Numbers = " + count_negative);
System.out.println("Count of odd Numbers = " + count_odd);
System.out.println("Count of even Numbers = " + count_even);
System.out.println("Average of Positive Numbers = " + avg_sum_positive);
System.out.println("Average of negative Numbers = " + avg_sum_negative);
System.out.println("Average of odd Numbers = " + avg_sum_odd);
System.out.println("Average of even Numbers = " + avg_sum_even);
}//closing main
} // closing class
so I'm trying to find the min, max, and average number of the numbers input. Everything works fine, although I do not want input less than 0 or greater than 100. When I input a number less than 0 or greater than 100 it still records it as the min/max. I do not want this! How would I not take input that is less than 0 or greater than 100?
Thanks!
import java.text.DecimalFormat;
import java.util.Scanner;
public class ExamGrades {
public static void main(String[]args){
Scanner scan = new Scanner(System.in );
int number = 0;
double total = 0;
int minimum;
int maximum = 0;
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
minimum=number;
total += number;
for(int i = 2; i<11; i++){
if(number<0 || number >100){
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
i--;
}
else{
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
total += number;
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + minimum);
System.out.println("The maximum is: " + maximum);
System.out.println("The average is: " + oneDecimalPlace.format((total) / 10.0 ));
}
}
Let's say you entered 5 for integer one, then 102 for the second integer. What's going to happen? Well before you entered 102, number was 5, so it will go into the else block.
It'll say:
Please enter integer 2:
then you type: 102
So then what? Well the next piece of code is:
number = scan.nextInt(); and then it goes through the if-statements right below it to determine if it's a maximum. Nothing is stopping it.
Try this code instead of your loop:
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
// keep them in a loop until they enter a valid number
while (number < 0 || number > 100) {
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
}
// after they entered a valid number, add it to the series
minimum = number;
total += number;
for(int i = 2; i < 11; i++) {
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
// keep them in a loop until they enter a valid number
while (number < 0 || number > 100) {
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
}
// after they entered a valid number, add it to the series
total += number;
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
problem:
if(number<0 || number >100)
It will return false when number is 100 or 0 thus accepting it and executing you else block.
Is 100>100 answer false because they are equal, not greater than the other
solution:
if(number<1 || number >99)
EDit:
public static void main(String[]args){
Scanner scan = new Scanner(System.in );
int number = 0;
double total = 0;
int minimum = 0;
int maximum = 0;
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
if(number>1 && number <99)
{
minimum=number;
total += number;
}
for(int i = 2; i<11; i++){
if(number<1 || number >99){
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
i--;
}
else{
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
total += number;
if(number>1 && number <99)
{
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + minimum);
System.out.println("The maximum is: " + maximum);
System.out.println("The average is: " + oneDecimalPlace.format((total) / 10.0 ));
}
Here is an Example.Exceptions are not handled so put a Try-catch to String to Integer Conversion If you want.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Numbers{
public static void main(String x[]){
Scanner scn=new Scanner(System.in);
int Total=0,Max=0,Min=Integer.MAX_VALUE;
for(int i=0;i<10;){
System.out.print("Enter Number :");
int NumberOne=Integer.parseInt(scn.nextLine());//Put a Try catch If needed
if(NumberOne>0&&NumberOne<100){
Total+=NumberOne;
Max=(Max>NumberOne)?Max:NumberOne;
Min=(Min<NumberOne)?Min:NumberOne;
i++;
}else{
System.out.print("Number Invalid");
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + Min);
System.out.println("The maximum is: " + Max);
System.out.println("The average is: " + oneDecimalPlace.format((Total) / 10.0 ));
}
}
Hi all thanks for taking the time, I am continuosly getting an infinate loop when i am inserting the variable m could anyone please take a look thanks.
public static void main program7_2(String args [])
{
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while((n%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while((m%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum =0;
for (int i = n; n<=m; i++)
{
if ((i%2) != 0)
sum = sum + i;
}
System.out.println("Sum of the numbers between "+n+ " and " +m+": " + sum);
}
The problem of the program is to enter 2 odd numbers and get the sum of the odd numbers in between
Thanks and regards
Instead of n<=m in your for loop use i<=m since you are using i as your counter and not n
This is the error :
for (int i = n; n<=m; i++) /* terminating condition "n<=m" is never met here */
{
if ((i%2) != 0)
sum = sum + i;
}
Why : this loop increments i but terminating condition is n<=m which is never met....so either do i<n Or i<m which ever suits you for terminating the condition!!
if u want to get the sum of nubers between those two use
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while ((n % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while ((m % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum= 0;
for (int i = n; i <= m; i++) {
sum = sum + i;
}
System.out.println("Sum of the numbers between " + n + " and " + m + ": " + sum);
}
}