I have problem with similar task.
Here is the task:
The sample tests are:
This is my code:
import java.text.DecimalFormat;
import java.util.Scanner;
public class MinMaxSumAverage {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#0.00");
Scanner scanner = new Scanner(System.in);
double average;
double sum = 0;
double max = Integer.MIN_VALUE;
double min = Integer.MAX_VALUE;
double numbers = scanner.nextInt();
for (int i = 0; i < numbers; ++i) {
int num = scanner.nextInt();
if (num > max) max = num;
if (num < min) min = num;
sum += num;
}
average = sum / numbers;
System.out.println("min=" + (df.format(min)));
System.out.println("max=" + (df.format(max)));
System.out.println("sum=" + (df.format(sum)));
System.out.println("avg=" + (df.format(average)));
}
}
It work correct, but in "judge system" who test my code have some errors:
Can you help me to find what's wrong with my code?
Edit:
I change sum, max & min from double to int, and test result have minimal changes:
Test 2:
Your code is failing to accept decimal inputs that's why you are receiving InputMismatchException. Change this line
int num = scanner.nextInt();
to
double num = scanner.nextDouble();
Related
Problem: Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics.
Ex: When the input is:
15 20 0 5 -1
the output is:
10 20
You can assume that at least one non-negative integer is input.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.println(avg + " " + max);
}
}
I had a lot of trouble with this problem. Is there any way I could have done this without having to do count -1 while computing the average?
Also, is this this the most efficient way I could have done it?
How about this? If you have questions from the implementation, please ask.
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
while (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
num = scnr.nextInt();
}
int avg = count == 0 ? 0 : total/count;
System.out.println(avg + " " + max);
}
If you use while loop instead of do-while loop, you don't have to count the negative number input anymore. And no, it's not the most efficient way, but it's a good start!
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userNum;
int maxNum = 0;
int totalSum = 0;
int averageNum;
int count = 0;
userNum = scnr.nextInt();
while (userNum >= 0) {
if (userNum > maxNum) {
maxNum = userNum;
}
totalSum += userNum;
++count;
userNum = scnr.nextInt();
}
averageNum = totalSum / count;
System.out.println("" + averageNum + " " + maxNum);
}
}
int Num;
int max = 0;
int total = 0;
int average;
int count = 0;
Num = scnr.nextInt();
while (Num >= 0) {
if (Num > max) {
max = Num;
}
total += Num;
++count;
Num = scnr.nextInt();
}
average = total / count;
System.out.println("" + average + " " + max);
}
}
I know this is basis problem, but I just can't solve this, so I need your help..
I am trying to find the average of digits of the number(user input) by using While Loop, like for example, the average of digits of the number 789 is (7+8+9+)/3 = 8.
Could anyone help me with this..? Thank you so much.
import java.util.Scanner;
public class AVE
{
static int digits = 0;
static int average =0;
static int sum =0;
static int number;
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
System.out.println("what is your number?");
number = kb.nextInt();
avDigits();
System.out.println("The average is " + average);
}
public static void avDigits()
{
int num = number;
while (num > 0)
{
digits += 1;
sum += digits % 10;
num/=10;
}
average = (sum/digits);
}
}
Your issue is with the mod. You can rewrite the code as follows, Modification is done not only to correct the error but to make standardized. You need to change average to float or double.
import java.util.Scanner;
public class AVE {
public static void main(String[] args) {
int number;
float average = 0;
Scanner kb = new Scanner(System.in);
System.out.println("what is your number?");
number = kb.nextInt();
average = avDigits(number);
System.out.println("The average is " + average);
}
private static float avDigits(int number) {
int digits = 0;
float sum = 0.0F;
while (number > 0) {
digits += 1;
sum += number % 10;
number /= 10;
}
return (sum / digits);
}
}
You are taking mod of digits instead of num. Change the while loop as following:
while (num > 0)
{
digits += 1;
sum += num % 10; //<< Take mod of num here
num/=10;
}
import java.util.Scanner;
class AVE
{
static int digits = 0;
static float average =0;
static int sum =0;
static int number;
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
System.out.println("what is your number?");
number = kb.nextInt();
avDigits();
System.out.println("The average is " + average);
}
public static void avDigits()
{
int num = number;
while (num > 0)
{
digits += 1;
sum += num % 10; /*Do the modulo of num instead of digit. Since doing the modulo of num will give you the last digit*/
num/=10;
}
average = ((float)sum/digits); //average can be in decimal also
}
}
I am having some issues getting my min and max values to print. Also as new
as I am to programming I don't understand why all my values are decimals. I will post the code and my results.
import java.util.Random;
import java.util.Scanner;
import java.util.*;
public class RandomArray1
extends ArrayList<Double>
{
private static final long serialVersionUID = 1L;
public RandomArray1()
{
super();
}
public static RandomArray1 getInstance(int size)
{
Random randomNumberGenerator = new Random();
RandomArray1 randomArray = new RandomArray1();
for (int i = 0; i < size; i++)
{
randomArray.add(randomNumberGenerator.nextDouble());
}
return randomArray;
}
public Double getAverage()
{
if (this.size() == 0)
{
return 0d;
}
Double sum = 0d;
for (Double element : this)
{
sum = sum + element;
}
return sum / this.size();
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many numbers you would like to Generate: ");
RandomArray1 randomArray = RandomArray1.getInstance(scan.nextInt());
System.out.println(randomArray);
System.out.println("Average" +randomArray.getAverage());
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
while (true) {
if ( !scan.hasNextDouble())
break;
Double num = scan.nextDouble();
min = Math.min(min, num);
max = Math.max(max, num);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
}
}
Here are my results...
Enter how many numbers you would like to Generate: 5
[0.8630040934474159, 0.12949667753808425, 0.5751777190226718, 0.18492672539115063, 0.7508377917335503]
Average : 0.5006886014265746
always decimal point and it doesn't even print "Max is:" or "Min is:" which makes me think something is wrong with this section. But I don't know what it is...any thoughts. Just ideas...
while (true) {
if ( !scan.hasNextDouble())
break;
Double num = scan.nextDouble();
min = Math.min(min, num);
max = Math.max(max, num);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
I think you're filling you're array with nextDouble() which as documented gives you double precision floating point numbers between 0 and 1.
All good, changed the Arraylist to an Integer and everything else. This solved my issues as discussed. here is what the code looks like now...works perfect!
import java.util.*;
public class RandomArray1
extends ArrayList<Integer>
{
private static final long serialVersionUID = 1L;
public RandomArray1()
{
super();
}
public static RandomArray1 getInstance(int size)
{
Random randomNumberGenerator = new Random();
RandomArray1 randomArray = new RandomArray1();
for (int i = 0; i < size; i++)
{
randomArray.add((int) randomNumberGenerator.nextInt());
}
return randomArray;
}
public Double getAverage()
{
if (this.size() == 0)
{
return 0d;
}
Double sum = 0d;
for (Integer element : this)
{
sum = sum + element;
}
return sum / this.size();
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many numbers you would like to Generate: ");
RandomArray1 randomArray = RandomArray1.getInstance(scan.nextInt());
System.out.println(randomArray);
System.out.println("Average : " +randomArray.getAverage());
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
for (int num : randomArray)
{
min = Math.min(min, num);
max = Math.max(max, num);
}
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
}
thank you so much!
Your program works fine:
Enter how many numbers you would like to Generate: 3
[0.26063976207509887, 0.48867331377683443, 0.3864751544223266]
Average0.37859607675808665
4
Max is: 4.0
Min is: 4.0
5
Max is: 5.0
Min is: 4.0
3
Max is: 5.0
Min is: 3.0
end
But since it expects an input, but doesn't say so, it could appear to be "dead". Just include a prompt before waiting for the next input:
System.out.print("Please enter next number: ");
if ( !scan.hasNextDouble())
break;
In case you wanted to calculate the min/max of the existing array instead of a new user input, use a for loop to iterate over the existing array:
for (double num : randomArray) {
min = Math.min(min, num);
max = Math.max(max, num);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
So I'm pretty new to this site, but you guys are my last hope. The goal here is that a user will input 10 temperatures in Fahrenheit (enter -999 to stop while entering) then the program will change those temps into Celsius. Also the user will need to type in their location. I am able to type in the location, but after I hit 'Enter' I get:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Prog1.main(Prog1.java:20)`
Here is my code:
import java.util.Scanner;
public class Prog1
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//asks the user for the location
System.out.print("Enter Location: ");
int place = in.nextInt();
System.out.print(place);
double[] temp = new double[10];
int num = 0;
//prime the loop
System.out.print("Enter temperature: ");
int input = in.nextInt();
//get up to 10 temperatures and store in array "temp"
while (input >= -998 && num < 10) {
temp[num] = input;
num++;
System.out.print("Enter temperature: ");
input = in.nextInt();
}
//print report
System.out.println();
System.out.printf("%5s %5\n", "Fahrenheit", "Celcius");
for (int x = 0; x < num; x++) {
System.out.printf("%5d %5s\n", temp[x], celsius( temp[x]));
}
System.out.printf("\nHigh: %6.2f", max( temp, num));
System.out.printf("\nLow: %6.2f", min( temp, num));
System.out.printf("\nAverage: %6.2f", average(temp, num));
}
/**
* Method to convert farenheit to celsius
* #param double farenheit temperature
* #return double celsius temperature
*/
public static double celsius(double input) {
double celcius = 5.0 / 9.0 * ( input - 32);
return celcius;
}
/**
* Method to calculate average, min and max temperatures
*
* #param double farenheit temperature
* #return average, min and max temperatures
*/
public static double average(double[] temp, int num) {
double sum = 0;
for (int x = 0; x < num; x++) {
sum += temp [x];
}
return (double) sum / num;
}
public static double max( double[] temp , int num){
double max = temp[0];
for (double x : temp) {
if (max > num) {
max = num;
}
return num;
}
return max;
}
public static double min(double[] temp, int num) {
double min = temp[0];
for (double x : temp) {
if (min < num) {
min = num;
}
return min;
}
return num;
}
}
You're getting an InputMismatchException, which means that whatever the user is submitting to you is of a different type then you have programmed for.
You ask for the user to input their location, and then call in.nextInt(). nextInt() will throw an exception if the next token in the standard input is not an integer. You must be entering something other than an integer for the location which is throwing the exception. If you want to enter a text based location (like a String) try in.nextLine()
InputMismatch Exceptions are thrown when you put a datatype somewhere that was expected to be a different datatype. Since you are working with degrees, I'm assuming you might be entering floating point values, so in.nextDouble() might be a better option than in.nextInt(). You can then cast it to an integer later if you want that to be your output.
I've run your code just to see what is going on. You were not formatting printf correctly. Replace this part it'll do.
//print report
System.out.println();
System.out.printf("%s %s\n", "Fahrenheit", "Celcius");
for (int x = 0; x < num; x++) {
System.out.println(temp[x] + "\t" +celsius(temp[x]) );
}
I find this quick guide useful : http://web.cerritos.edu/jwilson/SitePages/java_language_resources/Java_printf_method_quick_reference.pdf
The solution above is quite a simple one.You have to replace:
System.out.print("Enter Location: ");
int place = in.nextInt();
System.out.print(place);
with
System.out.print("Enter Location: ");
String place = in.nextLine();
System.out.print(place);
since location is a string,when you give something like 'India' in.nextInt() would be expecting a number instead of string.So you were getting that error.Replace it only below enter location sysout.
replace formatting too. try this :
import java.util.Scanner;
public class Prog1
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//asks the user for the location
System.out.print("Enter Location: ");
String place = in.nextLine();
System.out.print(place);
double[] temp = new double[10];
int num = 0;
//prime the loop
System.out.print("Enter temperature: ");
int input = in.nextInt();
//get up to 10 temperatures and store in array "temp"
while (input >= -998 && num < 10) {
temp[num] = input;
num++;
System.out.print("Enter temperature: ");
input = in.nextInt();
}
System.out.println();
System.out.printf("%s %s\n", "Fahrenheit", "Celcius");
for (int x = 0; x < num; x++) {
System.out.println(temp[x] + "\t" +celsius(temp[x]) );
}
System.out.printf("\nHigh: %6.2f", max( temp, num));
System.out.printf("\nLow: %6.2f", min( temp, num));
System.out.printf("\nAverage: %6.2f", average(temp, num));
}
/**
* Method to convert farenheit to celsius
* #param double farenheit temperature
* #return double celsius temperature
*/
public static double celsius(double input) {
double celcius = 5.0 / 9.0 * ( input - 32);
return celcius;
}
/**
* Method to calculate average, min and max temperatures
*
* #param double farenheit temperature
* #return average, min and max temperatures
*/
public static double average(double[] temp, int num) {
double sum = 0;
for (int x = 0; x < num; x++) {
sum += temp [x];
}
return (double) sum / num;
}
public static double max( double[] temp , int num){
double max = temp[0];
for (double x : temp) {
if (max > num) {
max = num;
}
return num;
}
return max;
}
public static double min(double[] temp, int num) {
double min = temp[0];
for (double x : temp) {
if (min < num) {
min = num;
}
return min;
}
return num;
}
}
I am working on an assignment which prompts the user to input an integer, and displays that integer with the digits separated by spaces, and provides the sum of those digits. I have this working, but my individual digit display is form the last digit to the first. How can I make it display the digits from first to last?
Here is what I have so far:
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
System.out.print(" " + temp + " ");
}while (num > 0);
System.out.println("The sum of the digits = " + sum);
}
}
One option would be to use the String#valueOf(Integer) method.
Example
int input = 12345;
String inputStr = String.valueOf(input);
for(char c : inputStr.toCharArray()) {
// Print out each letter.
}
if you use the method String.valueOf(12345)
you can easily reverse the String with the method in this library:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse(java.lang.String)
StringUtils.reverse(String.valueOf(input));
Here is the solution
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
ArrayList<Integer> values = new ArrayList<>();
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
values.add(temp);
}while (num > 0);
Collections.reverse(values);
Iterator<Integer> it = values.iterator();
while(it.hasNext()){
System.out.println(" "+it.next()+" ");
}
System.out.println("The sum of the digits = " + sum);
}
}
BTW you should have to import ArrayList etc.
I would highly recommend putting the number into a String and then reading it, parsing it, and use the number however you want. As follows,
int input = 12345;
String inputString = input + "";
int sum = 0;
for (int i = 0; i < inputString.length(); i++) {
sum += Integer.parseInt(inputString.charAt(i) + "");
}
System.out.println(sum);
However an alternative way, not as pretty is..
int input = 12345;
int sum = 0;
while (input > 0) {
int i = (input + "").length() - 1;
int n = (int) (input / Math.pow(10, i));
input -= (int) (n * Math.pow(10, i));
sum += n;
}
System.out.println(sum);