My program wont go past my first few lines of code - java

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;
}
}

Related

Print out Average in for loop

This is my question
get to input a positive integer representing a number of weeks, loop
continuously until the value entered is positive. For each week, enter
a value for liters and a value for kilometers. For each value, should
loop until the value entered is positive. both values is a real
number. Then output the fuel economy for that week (liters divided by
kilometers). Finally, output the average fuel economy. You must make
good use of submodules in your answer.
This is my work
import java.util.*;
public class Exam8 {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (true) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum = result + (double)count;
System.out.println(result);
}
//average = getAverg(sum,count);
System.out.print("Average of fuel economy is: " + average);
}
public static double getAverg(double sum, int count) {
double average;
average = sum/count;
return average;
}
}
I get a problem when input value of lit and km, for example, I like to stop when to put either of a value of lit or km. Then I have another problem with outputting an average of the result (lit/km).
This code should work:
import java.util.*;
public class App {
public static void main(String[] args) {
int numweek = 0;
double valkms = 0;
double vallits = 0;
double average = 0;
double result = 0;
int count = 0;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of week: ");
numweek = sc.nextInt();
while (numweek < 1) {
System.out.println("Enter a positive of number week: ");
numweek = sc.nextInt();
}
while (count < numweek) {
count++;
System.out.print("Enter value of litres: : ");
vallits = sc.nextDouble();
while (vallits < 0) {
System.out.print("Positive litres: ");
vallits= sc.nextDouble();
}
System.out.print("Enter value of kilometres: : ");
valkms = sc.nextDouble();
while (valkms < 0) {
System.out.print("Positive kilometres: ");
valkms = sc.nextDouble();
}
if (vallits == 0 || valkms == 0) {
break;
}
result = vallits / valkms;
sum += result;
System.out.println(result);
}
System.out.print("Average of fuel economy is: " + getAverg(sum, numweek));
}
public static double getAverg(double sum, double numOfWeeks) {
double average;
average = sum/numOfWeeks;
return average;
}
}
Your first error was that the condition in the while loop wasn't correct. In order for the loop to stop you need to specify proper conditions. If condition is true it will loop indefinetely or until you set break.
Your second error was that you didn't calculate the average correctly. You should have just taken the sum for every week and added it to the current sum(which is zero at the beggining), and then just divide that sum by number of weeks to get the average.
You also didn't use your getAverg function anywhere.

Rainfall program not accepted in codeLab

I am working on an assignment from MyProrammingLab:
Write a RainFall class that has the following field:
• an array of doubles that stores the rainfall for each of the 12 months of
the year (where the first index corresponds with January, the second with
February, etc.)
The class should also have the following methods :
• a method that returns the total rainfall for the entire year
• a method that returns the average monthly rainfall for the year
• a method that returns the month with the most rain as a string
• a method that returns the month with the least rain as a string
Demonstrate the class in a program that takes 12 doubles from the user (take the
doubles in the order of the months of the year, the first corresponding to the
rainfall in January, etc.). Do input validation: if the user inputs a negative
number, ignore it and continue asking them for input until you have 12
nonnegative doubles .
Once the user has given you all 12 doubles , create an instance of the RainFall
class and call its methods , printing out the total rainfall, the average
monthly rainfall, the month with the most rain, and the month with the least
rain, each on a separate line.
Here is my program, which is working fine with netbeans but rejected by codeLab:
import java.text.DateFormatSymbols;
import java.util.Scanner;
public class RainFall {
final private double[] rainFall;
public RainFall(double[] arr) {
rainFall = arr;
}
public double getTotalRain() {
double total = 0;
for(int i=0;i<rainFall.length;i++)
total = total + rainFall[i];
return total;
}
public double getAverageRain() {
double average = 0;
for(int i=0;i<rainFall.length;i++)
average = average + rainFall[i];
return average/rainFall.length;
}
public String getHighestRain() {
int j=0;
for(int i=0;i<12;i++)
if(rainFall[i]>rainFall[j])
j=i;
return new DateFormatSymbols().getMonths()[j];
}
public String getLowestRain() {
int j=1;
for(int i=0;i<12;i++)
if(rainFall[i]<rainFall[j])
j=i;
return new DateFormatSymbols().getMonths()[j];
}
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
double[] rainfallInput = new double[12];
for(int i=1;i<=12;i++) {
System.out.print("Enter rainfall for month " + i + ":");
rainfallInput[i-1]=myScan.nextDouble();
myScan.nextLine();
if(rainfallInput[i-1]<0) {
System.out.print("Enter rainfall for month " + i + :");
rainfallInput[i-1]=myScan.nextDouble();
myScan.nextLine();
}
}
RainFall rain = new RainFall(rainfallInput);
System.out.println(rain.getTotalRain());
System.out.println(rain.getAverageRain());
System.out.println(rain.getHighestRain());
System.out.println(rain.getLowestRain());
}
}
Any help would be appreciated!
Thank you in advance
I'm assuming your answer is rejected because you can eventually input a negative number at the second rainfallInput[i-1]=myScan.nextDouble();
Try with a do-while loop instead to continuously ask for a positive number.
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
double[] rainfallInput = new double[12];
for (int i = 0; i < 12; i++) {
double input;
do {
System.out.print("Enter rainfall for month " + (i + 1) + ":");
input = myScan.nextDouble();
myScan.nextLine();
// Optionally tell why you are repeating input
/*
if (input <= 0) {
System.out.println("You must enter a positive value");
}
*/
} while (input <= 0);
rainfallInput[i] = input;
}
RainFall rain = new RainFall(rainfallInput);
System.out.println(rain.getTotalRain());
System.out.println(rain.getAverageRain());
System.out.println(rain.getHighestRain());
System.out.println(rain.getLowestRain());
}
public double getTotalRain() {
double total = 0;
for (int i = 0; i < rainFall.length; i++) {
total += rainFall[i];
}
return total;
}
public double getAverageRain() {
return getTotalRain() / (1.0 * rainFall.length);
}
public String getHighestRain() {
double max = Double.MIN_VALUE;
int maxIndex = 0;
for (int i = 0; i < rainFall.length; i++) {
double amount = rainFall[i];
if (amount > max) {
max = amount;
maxIndex = i;
}
}
return DateFormatSymbols.getInstance().getMonths()[maxIndex];
}
public String getLowestRain() {
double min = Double.MAX_VALUE;
int minIndex = 0;
for (int i = 0; i < rainFall.length; i++) {
double amount = rainFall[i];
if (amount < min) {
min = amount;
minIndex = i;
}
}
return DateFormatSymbols.getInstance().getMonths()[minIndex];
}
Get rid of myScan.nextLine(); in the for loop and code lab will accept it.

How to sum powers of 2 with while loop

I need to calculate the sum of 2^0+2^1+2^2+...+2^n, where n is a number entered by the user. The main problem is that I don't know how to use the while loop to sum the different result of 2^n up.
Here is what I've tried:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(power <= i) {
Math.pow(number, i);
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + result);
}
}
Only you have to do is:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
double sum = Math.pow(2,power+ 1 ) - 1;
System.out.println("The sum is: " + sum);
}
}
In this link explains the math expresion
All fine, just a few changes.
Change the parts code to
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
/*Remove this --------> while(power <= i) {*/
while (i <= power) {//it should be this
/*Remove this -------> Math.pow(number, i);*/
sum = sum + Math.pow(number, i);
i = i + 1;
}
System.out.println("The sum is: " + sum);
Your conditional is backwards, it should read:
while (i <= power)
You compute the sum of powers, then completely ignore it, just printing out the result of 2^i. you should be printing out sum, something like:
while (i <= power) {
sum += Math.pow(number, i);
i++;
}
System.out.println("The sum is: " + sum);
For style points this won't handle a negative power, so you'll need to test for that.
Dont understand why do you want to loop in this case. You can do it like :
System.out.println("The sum is: "+(Math.pow(2, power+1)-1 ));
But if you really want to use loop try this :
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(i<=power) {
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + sum);
Here is a solution with comments to explain the logic. While loops need some kind of variable to control the number of iterations. That variable of course needs to be updated somewhere inside the loop.
You can compute the sum of the powers with the Math.pow() function, obviously. No import statement is needed to use it. I hope this helps. Good luck.
/* Scanner and variable to get and hold user input */
Scanner scan = new Scanner( System.in );
int userInput = 0;
/* Variable to hold the sum, initialized to 0.0 */
double sum = 0.0;
/* Prompt the user, and obtain the reply */
System.out.print( "Enter the exponent: ");
userInput = scan.nextInt();
/* The while loop and it's initialized counter */
int counter = 0;
while( counter <= userInput ){
/* Add each power to sum using Math.pow() */
sum = sum + Math.pow( 2, counter );
/* Watch the output as the loop runs */
System.out.println( "Sum: " + sum );
counter++; // Increment counter, so the loop exits properly
} // End while loop
public class SumofSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
String c = "123";
char d[] = c.toCharArray();
int a[] = new int[d.length + 1];
for (int i = 0; i < d.length; i++)
a[i] = d[i] - 48;
int r = 0;
for (int i = 0; i < c.length(); i++)
r = r + (int) Math.pow(a[i], a[i + 1]);
System.out.println(r);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int power=Integer.parseInt(reader.nextLine());
int number=2;
int i=0;
int result=0;
while (power>=i) {
result += (int)Math.pow(number, i);
i++;
}
System.out.println("The result is "+result);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
double power=Double.parseDouble(reader.nextLine());
int number=2;
int i=0;
double sum=0;
while (power>=i) {
sum=sum+Math.pow(number, i);
i++;
}
System.out.println("The sum is "+sum);
}

What is the bug in my "find median" implementation?

I found someone who had a similar problem (How to calculate the median of an array?), but I couldn't figure out how to incororate it in to my own code since I am rather new to java. Right now, my findmedian method is returning 0 instead of the actual median and I can't seem to figure it out. Thanks!
import java.util.Scanner;
import java.util.Arrays;
public class Original
{
public static void main(String[] args)
{
Scanner inputNumber = new Scanner(System.in);
Scanner dataItem = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("This stores a list of contirbutions to a charity drive.\n ");
System.out.print("How many contributors will be entered? ");
double contributors = inputNumber.nextDouble();
double contributions[ ] = new double[50];
double contributions_check[] = findData (contributors, contributions);
System.out.print("See if the contributions are correct. ");
// Displays the contributions, loop allows numbers to be displayed correctly
for (int count = 0; count < contributors; count++) {
System.out.print(contributions_check[count] + " ");
}
double median = findmedian(contributors,contributions_check);
System.out.print("\n The median contribution is: " + median);
}
public static double[] findData(double n, double[] contributions2)
{
Scanner dataItem = new Scanner(System.in);
// x must be 0 and x must be < than n
for (int x = 0; x < n; x++) {
System.out.print("Please enter the next contribution: ");
contributions2[x] = dataItem.nextDouble();
}
return contributions2;
}
public static double findmedian(double n, double data[])
{
Arrays.sort(data);
double median;
if (data.length % 2 == 0) {
median = ((double) data[data.length / 2] +
(double) data[data.length / 2 - 1]) / 2;
} else {
median = (double) data[data.length/2];
}
return median;
}
}
I think the issue is you are using data.length in findmedian, where you should be using n. data.length is always going to be 50, even if you only entered 5 items....
Use the number of contributors n to know the valid contributors in your array.
public static double findmedian(double n, double data[])
{
Arrays.sort(data);
double median;
if (data.length % 2 == 0) {
median = ((double) data[n / 2] +
(double) data[n / 2 - 1]) / 2;
} else {
median = (double) data[n/2];
}
return median;
}

cos(x) program confusion with function input

How would I finish this program?
I know it is wrong where I have inputed the calculation into the code. What do I need to change to get the program to work the way the assignment asks (see image)? Also where would I loop it to recalculate if the user chooses to at the end?
package cosx;
import java.util.Scanner;
public class cosx2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the degree: ");
double degree = input.nextDouble();
double radian = getRadian(degree);
calculateCos(input, radian,degree);
}
public static double getRadian(double x) {
return x = (Math.PI/180)*x;
}
private static void calculateCos(Scanner std, double rad, double deg) {
System.out.print("How many terms do you want to calculate the cos: ");
int terms = std.nextInt();
double top;
double bottom;
double sum=0;
for(int i = 0; i<= terms; ++i){
top = Math.pow(-1, i);
bottom =1;
int repeat = 2*i+1;
for(int j = 1; j <= repeat; ++j){
bottom *= j;
}
if(i%2 == 0)
sum += (top/bottom);
else
sum -= (top/bottom);
}
System.out.printf("The sin (%.1f", deg);
System.out.printf(") is %.6f", sum);
}
}

Categories