Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Java How to get the weekly sum value from user input in java?

Ghiralt

New Coder
Java:
import java.util.*; // Scanner, Locale
class TempTest {
public static void main(String[] args) {
System.out.println("TEMPERATURES\n");


Scanner in = new Scanner(System.in);
in.useLocale(Locale.US);

System.out.print("hoe many weeks: ");
int amountWeeks = in.nextInt();
System.out.print("how many temperatures per week: ");
int amountTemp = in.nextInt();

double[][] t = new double[amountWeeks + 1][amountTemp + 1];

for (int week = 1; week <= amountWeeks; week++) {
System.out.println("temperatures - weekly " + week + ":");
for (int inp = 1; inp <= amountTemp; inp++)
t[week][inp] = in.nextDouble();
}
System.out.println();

System.out.println("temperatures:");
for (int week = 1; week <= amountWeeks; week++) {
for (int inp = 1; inp <= amountTemp; inp++)
System.out.print(t[week][inp] + " ");
System.out.println();
}
System.out.println();


double[] sumT = new double[amountWeeks + 1];

double sumTempWeek = 0;
{
System.out.println("Weekly temp sum: ");
for (int week = 1; week <= amountWeeks; week++)
{
for (int inp = 1; inp <= amountTemp; inp++)
sumTempWeek += t[week][inp];

System.out.println(sumTempWeek + " ");
System.out.println();
}
}
}
}

What I have tried:

I have tried the following code to get the weekly sum of temperatures from the program and the first return is always correct and gives me week no.1 sum temp but week 2 gives me week no.1 and week no.2 sum temperatures combined. what is wrong with my code?

Java:
double[] sumT = new double[amountWeeks + 1];

double sumTempWeek = 0;
{
System.out.println("Weekly temp sum: ");
for (int week = 1; week <= amountWeeks; week++)
{
for (int inp = 1; inp <= amountTemp; inp++)
sumTempWeek += t[week][inp];

System.out.println(sumTempWeek + " ");
System.out.println();
}
}
 
Last edited by a moderator:
Are you trying for only after first, because arrays start at 0 index, not 1.
I think you need to set sum temps to 0 again after each inner for loop in that outer for loop or introduce another variable set like that.
X E.
 
Back
Top Bottom