I am currently working on a problem set for an assignment at school, and I'm really close to finishing however I'm getting a few compilation errors.
The problem set includes displaying the weeks avg. temp, highest temp., lowest temp., and the days of the week that are hottest and coldest.
Currently what I'm trying to do is display the days of the week that are hottest, and if I work that out I can easily find the coldest days of the week.
I'm getting a few compilation errors when I try to compile the code which includes
incompatible types: int[] cannot be converted to int
error: cannot find symbol
It would be great if I could get some guidance on what to do, I'm currently at lost right now.
http://ideone.com/rOqV2Z
public class test1
{
// Main method
public static void main(String[] args)
{
// Create a new scanner
Scanner input = new Scanner(System.in);
// Set array list
int[] tempList = new int[7];
// Prompt user for input and store input
System.out.println("Enter the hightest temperature of each day for a week (starting on Sunday): ");
for(int i = 0; i < tempList.length; i++)
tempList[i] = input.nextInt();
// Averages temperature - ####### ASK WHY IT THERE ARE SO MANY DECIMALS ON THE SIDE WHEN AVERAGE ALL 1's
double avgTemp = avgTemp(tempList);
System.out.printf("The average temperature of the week is: %.2f degree %n", avgTemp);
// Display hottest temperature
int maxTemp = maxTemp(tempList);
System.out.println("The highest temperature of the week is: " + maxTemp + " degree");
// Display coldest temperature
int minTemp = minTemp(tempList);
System.out.println("The coldest temperature of the week is: " + minTemp + " degree");
int[] maxTempList = searchTemp(tempList, maxTemp);
for(int i = 0; i < maxTempList.length; i++){
System.out.print("The hottest days of the week are: " +maxTempList[i]);
System.out.print(weekDay(tempList,maxTemp));
}
}
// Average the temperature
public static double avgTemp(int[] array)
{
int tempTotal = array[0];
// Total temperature values
for(int i = 0; i < array.length; i++)
tempTotal = array[i]+tempTotal;
// Return temperature average.
return ((double)tempTotal/array.length);
}
// Get hottest temperature
public static int maxTemp(int[] array)
{
int max = array[0];
// Check and replace max temp
for(int i = 1; i < array.length; i++){
if(max < array[i])
max = array[i];
}
return max;
}
// Get coldest temperature
public static int minTemp(int[] array)
{
int min = array[0];
for(int i = 1; i < array.length; i++){
if(min > array[i])
min = array[i];
}
return min;
}
// Return days
public static String weekDay(int i, int[] array)
{
int[] displayWeekDay = searchTemp(array, i);
for(i = 0; i < displayWeekDay.length; i++){
String weekDay = "";
switch(i)
{
case 0: return "Sunday";
case 1: return "Monday";
case 2: return "Tuesday";
case 3: return "Wednesdays";
case 4: return "Thursday";
case 5: return "Friday";
case 6: return "Saturday";
}
}
return weekDay;
}
// Finds the index of the hottest/coldest days
public static int[] searchTemp(int[] temp, int key)
{
int count = 0;
for(int i = 0; i < temp.length; i++){
if(temp[i] == key)
count++;
}
int[] index = new int[count];
for(int j = 0; j < index.length; j++){
for(int i = 0; i < temp.length; i++){
if(temp[i] == key){
if(j > 0 && index[j - 1] == i)
continue;
else{
index[j] = i;
break;
}
}
}
}
return index;
}
}
I went and checked the code using the website you linked.
Firstly, you should learn to use the debugger, as it will usually tell you what the error is and where to find it.
Main.java:42: error: incompatible types: int[] cannot be converted to int
System.out.print(weekDay(tempList,maxTemp));
^
Here it points to an error on the data type of tempList. It's saying that an int array cannot be converted to an int. If you look at the weekDay() function you'll see that the first argument is asking for an int, but you are passing an int array. It won't work.
public static String weekDay(int i, int[] array)
EDIT: If you want to pass a specific value into the function from the array just use
System.out.print(weekDay(tempList[IntegerPosition],maxTemp));
^
Main.java:104: error: cannot find symbol
return weekDay;
^
This simply means it can't find the variable in the current scope. There's a lot to learn about this, but I'll just get to the point.
// Return days
public static String weekDay(int i, int[] array)
{
int[] displayWeekDay = searchTemp(array, i);
String weekDay = "";
for(i = 0; i < displayWeekDay.length; i++){
//String weekDay = ""; Declare weekDay outside of the loop
switch(i)
{
//Assign a value to weekDay, simply returning won't do it
case 0: weekDay = "Sunday"; break;
case 1: weekDay = "Monday"; break;
case 2: weekDay = "Tuesday"; break;
case 3: weekDay = "Wednesdays"; break;
case 4: weekDay = "Thursday"; break;
case 5: weekDay = "Friday"; break;
case 6: weekDay = "Saturday"; break;
}
}
return weekDay;
}
EDIT 2: As per the discussion, this is what I would do in order to be able to print multiple days that had the highest temperature
//Call the function directly without putting a print statement around it
weekDay(maxTemp,tempList));
//...
// Return days
public static void weekDay(int i, int[] array) //Change the return type to void
{
int[] displayWeekDay = searchTemp(array, i);
for(i = 0; i < displayWeekDay.length; i++){
switch(displayWeekDay[i])
{
//Print each one
case 0: System.out.println("Sunday"); break;
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
}
}
}
Addressing each issue on it's own:
"incompatible types: int[] cannot be converted to int" issue
This is being caused by the line System.out.print(weekDay(tempList,maxTemp));. The method signature for the weekDay method is public static String weekDay(int i, int[] array) however the method is being called with arguments in the wrong order - tempList is of type int[] and maxTemp is of type int. Reversing the arguments in either the method call or the method signature will resolve the error.
"error: cannot find symbol"
This is an issue related to variable scope. When a variable is declared (e.g. int i; or String name = "John";), that variable can only be used within the scope that it is declared in. In the weekDay method the weekDay variable is declared inside the for loop (i.e. inside of the braces associated with the for loop). As such the weekDay variable only has the scope of the for loop, and cannot be referenced outside of that scope. Moving the declaration of weekDay outside of the for loop will fix the issue. See here for more information on variable scope rules.
Like I said, think about the API first, input later. This implementation assumes JDK 8 and lambdas:
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* Created by Michael
* Creation date 3/19/2016.
* #link https://stackoverflow.com/questions/36107614/java-displaying-the-temperature-statistics-of-the-week-using-arrays
*/
public class TemperatureHistory {
private Map<Date, Double> temperatureHistory = new TreeMap<>();
public void addDataPoint(Date date, Double temperature) {
if (date != null && temperature != null) {
this.temperatureHistory.put(date, temperature);
}
}
public Double getAverageTemperature() {
double averageTemperature = 0.0;
if (this.temperatureHistory.size() > 0) {
averageTemperature = this.temperatureHistory.values()
.stream()
.collect(Collectors.averagingDouble(value -> value));
}
return averageTemperature;
}
public Double getMaxTemperature() {
return this.temperatureHistory.entrySet()
.stream()
.max((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
.get()
.getValue();
}
public Double getMinTemperature() {
return this.temperatureHistory.entrySet()
.stream()
.min((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
.get()
.getValue();
}
public Date getFirstDateForTemperature(Double temperature) {
return this.temperatureHistory.entrySet()
.stream()
.filter(e -> e.getValue().equals(temperature))
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
}
public Date getDateMinTemperature() {
return this.getFirstDateForTemperature(this.getMinTemperature());
}
public Date getDateMaxTemperature() {
return this.getFirstDateForTemperature(this.getMaxTemperature());
}
}
In the last statement of you main method you do System.out.print(weekDay(tempList,maxTemp));
weekDay takes an int as the first argument, but tempList is of type int[]. You should swap the order of tempList and maxTemp either in your method call or definition.
public static String weekDay(int i, int[] array)
In this method, you're suppose to return a String type value
edit: change the string variable to other name. you can't have it the same as the method's name
Related
I'm trying to build a code in which the 12 months of the calendar are in an array, the code then asks for a month, and then it outputs the 10 months ahead of the inputted month.
e.g.
input: January
output: February, March,...November
I'm having trouble reverting the index back to the start once the index exceeds 12, for example, if I input August, it's supposed to output September to June, but instead it stops at December and says out of bounds. Thank you
String months[];
String choice;
months = new String[13];
months[0] = null ;
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
System.out.print("Enter Month : ");
choice = a.nextLine();
if (choice.equals("August")) {
for(int i=8; i<i+10; i++) {
String result= months[i];
System.out.println(result);
}
}
Use the modulus when choosing the month to print:
int start = 8;
if ("August".equals(choice)) {
for(int i=start; i < start+10; i++) {
String result= months[i % 12];
System.out.println(result);
}
}
This assumes you have defined your months array as:
String[] months = new String[12];
months[0] = "January";
months[1] = "February";
// ...
months[11] = "December";
The idea here is to wrap around the index used to select a month from the array. The dummy variable i, upon hitting the value 12, will wrap around to zero again.
Side note: It is always better to compare a string literal to a variable by placing the literal on the LHS of the comparison. The version I used is immune to a null pointer exception; the version you used is not.
Use modulus to reset the array index. The solution given above is correct. But if you want to continue with your own defined months array, where months[0] = null ;, just start the for loop from the next index of the input month.
if ("August".equals(choice)) {
int start = 9;
for(int i=start; i < start+11; i++) {
if(i!=13){
String result= months[i % 13];
System.out.println(result);
}
}
}
Try this,
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String months[];
String choice;
months = new String[13];
months[0] = null;
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
System.out.print("Enter Month : ");
choice = scanner.nextLine();
int startIndex = 0;
for (int i = 0; i < months.length; i++) {
if (choice.equalsIgnoreCase(months[i])) {
startIndex = i + 1;
}
}
for (int j = startIndex; j < months.length; j++) {
String result = months[j];
System.out.println(result);
}
}
I wanted to program a little Program that generates an addition task with 4 random numbers with measurements, like 45mm+34dm+ and so on....
The second function is: when the user enters the right solution, in mm measurements in the console, the program should print out: "right". But on the second function lies the problem. Something doesn't work on the if statement I wrote for this function.
Here is the Code:
package Uebungen;
import java.util.Scanner;
import sun.applet.Main;
import java.util.Random;
public class AvuG {
// Programmstart
public static void main(String[] args) {
// Declarationen
Scanner scn= new Scanner(System.in);
Random rG = new Random();
int[] numbers = new int[4];
int[] measurments = new int[4];
//Fills Array with four Random numbers for future measurment generation
for (int i = 0; i < maßEinheiten.length; i++) {
measurments[i] = rG.nextInt(4);
}
// Fills Array with four random numbers
for (int i = 0; i < numbers.length; i++) {
numbers[i] = rG.nextInt(99);
}
// Prints out 4 numbers with measurments
for (int i = 0; i < numbers.length; i++) {
if (i == numbers.length - 1) {
System.out.print(data[i] + checkInput(measurments[i]));
} else {
System.out.print(data[i] + checkInput(measurments[i]) + " + ");
}
}
//Calculates Solution of the calculation in measure mm in the Background for future use.
for (int i = 0; i < measurments.length; i++) {
switch(measurments[i]) {
case 1:
result += numbers[i];
break;
case 2:
result += numbers[i] * 10;
break;
case 3:
result += numbers[i] * 1000;
break;
case 0:
result += numbers[i] * 100;
break;
}
}
// Solution of the calculation, so you dont have to calculate when you want to investigate if its working.
System.out.println("");
System.out.println(result + "mm");
// *** Here lies the Problem. If the Solution is right, it should print out: "Right".
int nutzereingabe2 = scn.nextInt();
String nutzerEingabe = scn.next();
String nutzerEingabe3 = nutzereingabe2 + nutzerEingabe;
if ( nutzerEingabe3 == (result+"mm")){
System.out.println(result + "mm");
}
}
// Measurment Generator
private static String checkInput(int i) {
String result = "";
switch (i) {
case 1:
result = "mm";
break;
case 2:
result = "cm";
break;
case 3:
result = "m";
break;
case 0:
result = "dm";
break;
default:
result = "Error";
}
return result;
}
}
This is the code I have, but I want it to be able to roll the dice based on the number of trials the user inputs and then display the frequencies of each face.
This code isn't working as I would expect.
Also I would like to change the switch cases to if and else if statements, if anybody could help me out with that would be amazing, I've been working on this for a while now.
import java.util.Random;
import java.util.Scanner;
public class DieRoll {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random randomNumbers = new Random();
int one=0;
int two=0;
int three=0;
int four=0;
int five=0;
int six=0;
int trials;
int face;
System.out.println("Please enter the number of trials");
Scanner scan= new Scanner (System.in);
trials= scan.nextInt();
for(int rolls= 1; rolls==trials; rolls++);{
face= randomNumbers.nextInt(6) + 1;
// determine roll value 1-6 and increment appropriate counter
switch ( face )
{
case 1:
++one; // increment the 1s counter
break;
case 2:
++two; // increment the 2s counter
break;
case 3:
++three; // increment the 3s counter
break;
case 4:
++four; // increment the 4s counter
break;
case 5:
++five; // increment the 5s counter
break;
case 6:
++six; // increment the 6s counter
break; // optional at end of switch
}
}
System.out.println( "Face\tFrequency" ); // output headers
System.out.printf( "1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n",
one, two, three, four,
five, six );
scan.close();
}
}
In your for loop:
Remove the semicolon (;) just after the for(int rolls= 1; rolls==trials; rolls++) line.
Change:
for(int rolls= 1; rolls==trials; rolls++)
to:
for(int rolls= 1; rolls<=trials; rolls++)
As far as changing switch to if-else-if, not sure why you would want to do this, but simply write it as:
if(face == 1){
one++;
}
else if(face ==2){
two++;
}
and so on..
Please have a look at this:
public class Main {
private static final Random RANDOM_NUMBER_GENERATOR = new Random();
public static void main(String[] args) {
int numberOfTrials;
int[] facesFrequencies = new int[6];
System.out.println("Please enter the number of trials");
Scanner scanner = new Scanner(System.in);
numberOfTrials = scanner.nextInt();
scanner.close();
for (int numberOfRolls = 1; numberOfRolls <= numberOfTrials; numberOfRolls++) {
int face = rollDice();
if (face == 1) {
facesFrequencies[0] += 1;
} else if (face == 2) {
facesFrequencies[1] += 1;
} else if (face == 3) {
facesFrequencies[2] += 1;
} else if (face == 4) {
facesFrequencies[3] += 1;
} else if (face == 5) {
facesFrequencies[4] += 1;
} else if (face == 6) {
facesFrequencies[5] += 1;
}
}
System.out.println("Face\tFrequency");
for (int i = 0; i < facesFrequencies.length; i++) {
System.out.printf("%d\t\t%d%n", i, facesFrequencies[i]);
}
}
private static int rollDice() {
return RANDOM_NUMBER_GENERATOR.nextInt(6) + 1;
}
}
I've put the results (int one to int six) into an array. facesFrequencies[0] will be the same as int one.
The ; after for (...) is syntactically incorrect.
Switch statement is replaced with if statement.
Hy guys i will need a quick help with my asigment. I tryed to debug this code and i dont know how do i got this error but when i try to calculate gpa it is sending me 0 instead of value from switch.
If user is pressing A and credits 4 it needs to return 4 * 4 but for letter A i am receiving 0
public class Gpa{
private int sumOfCredits;
private int sumOfPoints;
private int points = 0;
public Gpa(){
sumOfPoints=0;
sumOfCredits=0;
}
public static int calcPoints(String grade) {
int points = 0;
switch (grade) {
case "A":
points = 4;
break;
case "B":
points = 3;
break;
case "C":
points = 2;
break;
case "D":
points = 1;
break;
case "F":
points = 0;
break;
case "a":
points = 4;
break;
case "b":
points = 3;
break;
case "c":
points = 2;
break;
case "d":
points = 1;
break;
case "f":
points = 0;
break;
default:
points = -1;
}
return points;
}
public int getSumOfCredits(){
return sumOfCredits;
}
public int getSumOfPoints(){
return sumOfPoints;
}
public void addToTotals(String grade,int credits){
sumOfCredits =+ credits;
calcPoints(grade);
sumOfPoints =sumOfPoints + points * credits;
}
public double calcGPA(){
double gpa = sumOfPoints /sumOfCredits;
return gpa;
}
}
and this is my tester class:
import java.util.*;
public class ComputeGpa {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Gpa gpaC = new Gpa();
for (int i = 1; i <= 3; i++) {
System.out.printf("Enter grade (one character): ");
String grade = scan.next();
System.out.printf("Enter credits: ");
int credits = scan.nextInt();
gpaC.addToTotals(grade, credits);
System.out.printf("Sum Points: %d", gpaC.getSumOfPoints());
System.out.printf("\tSum Credits: %d\n", gpaC.getSumOfCredits());
}
System.out.printf("GPA: %.2f", gpaC.calcGPA());
}
}
in your calcGPA() method you are doing integer division when you want to do floating division. You either have to cast the sumOfPoints variable or the sumOfCredits to a double.
double gpa = sumOfPoints /sumOfCredits;
Is integer division in java and will return an integer value. Chances are it is always a value between 0 and 1, which will be equivalent to 0 after being casted to an integer. See if casting them to double fixes it.
double gpa = (double)sumOfPoints / (double)sumOfCredits;
You are also redefining points on each loop here:
public static int calcPoints(String grade) {
int points = 0;
switch (grade) {
Which means that instead of changing the global variable points you are changing the local variable points. So you need to remove that local variable points so it uses the global one, also you dont need to return anything so just use void:
public void calcPoints(String grade) {
switch (grade) {
//cont
I am creating a program that converts roman numeral input to it's integer value and every time I run the program I get an error that says,
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:646)
at romannumeralconverter.RomanNumeralConverter.convert(RomanNumeralConverter.java:20)
at romannumeralconverter.RomanNumeralConverter.romanInput(RomanNumeralConverter.java:68)
at romannumeralconverter.RomanNumeralConverter.printValue(RomanNumeralConverter.java:72)
at romannumeralconverter.RomanNumeralConverter.main(RomanNumeralConverter.java:77)
Java Result: 1"
Now I am new to programming so I don't know what this means exactly. I am guessing my conversion algorithm is wrong in which the roman numeral entered is not read by the loop. Here is what I have:
public class RomanNumeralConverter {
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result;
}
public int romanInput() {
return convert(getUserInput());
}
public void printValue() {
System.out.println(romanInput());
}
public static void main (String[] args) {
new RomanNumeralConverter().printValue();
}
}
If my algorithm is wrong, does anyone know how to fix it?
change userInput.charAt(x); to userInput.charAt(x - 1);
charAt starts with index 0 to length -1
or int x = userInput.length() - 1;
#nd issue, everything coming out as 0
You are actually using uppercase characters in switch statement.
so just add below statement,in the starting of your function convert(String userInput)
userInput = userInput.toUpperCase(); // converts user input to uppercase , even if its is already or not.
code
public int convert(String userInput) {
userInput = userInput.toUpperCase();
int result = 0;
int subtractamount = 0;
int x = userInput.length() - 1;
while (x != 0) {
char romanConvert = userInput.charAt(x);
if (x >= 1) {
if (convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
output
Enter a roman numeral in uppercase: adig
Invalid character!
Invalid character!
Invalid character!
Invalid character!
501
You should start with
int x = userInput.length() - 1;
The last character in a string is at the index - (length-of-string - 1), not length-of-string.