Program problem 1: Write a program that uses one loop to process the integers from 300 down to 200, inclusive. The program should detect multiples of 11 or 13, but not both. The multiples should be printed left-aligned in columns 8 characters wide, 5 multiples per line (See Example Output). When all multiples have been displayed, the program should display the number of multiples found and their sum.
Example Output:
299 297 275 273 264
260 253 247 242 234
231 221 220 209 208
Found ?? integers totaling ??
My code:
public class Program3_1 {
private static int line;
private static int column;
public static void main(String[] args){
line = 0;
column = 0;
int sum = 300;
while (sum >= 200 && sum <= 300 ) {
/*
* You can also use "!=" instead of "^"
*/
if((sum % 11 == 0) ^ (sum % 13 == 0)){
if (column == 5){
System.out.println();
column = 0 ;
}
System.out.printf("%-8d",sum);
line += sum;
column++;
}
sum = sum-1;}
//System.out.println("");
System.out.println("\nFound " + (column * 3) + " multiples and integers totaling: " + line);
}
}
Code Issue: The output is remarkably similar to the example output and I am not sure if its correct or not. I figured it would be the same output considering that it is not random and that its a set number between 200-300. Can someone tell me if this code is correct and if the last line is correct as well. I feel like the output of line stating "found ?? integers totaling ??" should state the amount of multiples found and the total sum of them all. My main concern is having the output display the correct multiples. Last output is easy to just add them all together and displaying how many found.
Program problem 2: Write a program that generates a two-column table showing Fahrenheit temperatures from -40F to 120F and their equivalent Celsius temperatures. Each line in the table should be 5 degrees F more than the previous one. Both the Fahrenheit and Celsius temperatures should be accurate to 1 decimal place.
My code: public class Program3_2 {
public static void main(String[] args) {
System.out.println("Fahrenheit\tCelsius");
System.out.println("=======================");
for(int temp = -45; temp <= 120; temp += 5)
{
System.out.printf("%1d ",+temp);
double sum = (5.0/9.0) * (temp - 32);
System.out.printf("%1d", (int)sum );
System.out.println();
}
}
}
Code Issue: The program does display accurate results, but it doesn't seem to output the correct decimal format. I would like the output to display in a straight column for both and show the output in one decimal place. If any one can advise what I did wrong and how to improve, please advise. I am trying to become a better programmer and understand Java. Any advise will help, thank you so much!
Aucun commentaire:
Enregistrer un commentaire