I am new to this site and new to programming I just started a week a go. I've been tasked with making a conversion table from degrees Fahrenheit to Celsius. the table needs to start at 0 Celsius and stop at 100 degrees Celsius and go by increments of 5.
I am really trying to make it work but I can't seem to get the for loop working correctly. Can someone explain to me what I am doing wrong and how I can finish this program to work the way I need it?
public class Table
{
public static void main(String[] args)
{
System.out.println("Conversion Table");
final int TOTAL = 100;
for (int c = 0; c <= TOTAL; c+=5)
{
System.out.println((c*9/5)+32 +"\t");
{
System.out.println();
}
}
}
https://ideone.com/llmOER
Currently you are only printing the values of the Fahrenheit to standard out. If the idea is that you want to print to standard out the table then you probably want to add the Celsius value as well.
Add something like
System.out.println(c + "\t" + ((c*9/5)+32) +"\t");
to your output and you'll be sweet.
1-You have one less closing brace.
2-For making conversion table you have to show both Fahrenheit and Celsius value. Code for this would be.
public class A
{
public static void main(String[] args)
{
System.out.println("Conversion Table");
final int TOTAL = 100;
System.out.println("Fahrenheit"+"\t Celsius");
for (int c = 0; c <= TOTAL; c+=5)
{
System.out.println((c*9/5)+32 +"\t \t" + c);
{
System.out.println();
}
}
}
}
Related
How can I combine two small programs I created?
They are conversions of Farenheit to Celsius and vice versus. When I join the two together, I clearly have double/repeating variables. Not quite sure how/what to change.
The goal is to combine the two programs so it will ask the user to choose one, (F or C) and then direct the user to input an integer to convert. Not sure if I need to create these as two objects of my class? Or how to direct a choice, maybe using Switch?
Below is one conversion used, the formula is the same just inverse.
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a degree in Fahrenheit: ");
double fahrenheit = input.nextDouble();
double celsius =(5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit + " is " + celsius + " in Celsius") ;
}
}
I think you are right that we can simplify the code using a single switch statement - or even an if statement in this case.
Try maybe this:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String convertFrom = userInput.nextLine();
double C, F, convertedDegrees;
if (convertFrom.equals("F")) {
// Convert Fahrenheit to Celsius
} else if (convertFrom.equals("C")) {
// Convert Celsius to Fahrenheit
convertedDegrees = userInput.nextDouble();
F = (convertedDegrees * 1.8) + 32;
System.out.println(F);
} else {
System.out.println("Invalid input. Please type 'C' or 'F' to indicate whether you wish to convert Celsius or Fahrenheit degrees.");
}
}
I've created this class in a separate file and the program runs. The questions I have is the for a loop. Currently, I'm using a final int. I wanted to input a variable for
ol < MAX_R
} // End input loop
// Added feature that is not part of grading
System.out.print("Press enter to see results: ");
try {
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
Well, I think that author wants to read round scores for input stream and calculate an average. This is pretty simple, I think. First, you have to split your method into required logical parts: read data from stream, data processing, output data (to make your code simple and clear).
Java is not a C++. Here you can define array size wherever you like, as well as using user's input at runtime (Java does not require to know size of array at compile time).
public class Foo {
public static void main(String... args) {
double[] scores = readRoundScores();
double avg = calcAverageScore(scores);
System.out.println("\nAverage score: " + avg);
}
private static double[] readRoundScores() {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter total rounds: ");
double[] scores = new double[scan.nextInt()];
for (int i = 0; i < scores.length; i++) {
System.out.printf("Enter your round %d score: ", i + 1);
scores[i] = scan.nextDouble();
}
return scores;
}
}
private static double calcAverageScore(double... scores) {
double sum = 0;
for (double score : scores)
sum += score;
return sum / scores.length;
}
}
I am very new to coding and not very good at it :(
I've been struggling to do a project for my class for several hours now and I have scoured the internet with little use.
I need to make it appear on my console as if a ball is bouncing back and forth, the width of the ball bounce is set by the user.
So far, my output just produces an infinite left to right diagonal spanning the width chosen by the user.
My code so far:
import java.util.Scanner;
public class Midterm1_1 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
double yourNum;
System.out.println("How many spaces wide would you like the ball to bounce?");
yourNum= scan.nextDouble();
String ballBounce = new String ("o")
int count = 0;
while (count < 50){
System.out.println(ballBounce);
String x = " ";
for (int row = 1; row < yourNum; row++) {
System.out.println(x+"o");
x+= " ";
}
}
}
}
How do I get it to return right to left? My assumption is another for statement. But so far everything I've tried does not work.
Thank you in advance.
The code below is not necessarily the shortest one, it is meant to get the OP some ideas but without providing her/him with a straight answer. If the OP will copy the code as it is and doesn't adapt it, it should be obvious to the teacher the code is copied from somewhere. In case the OP understands it, it will be easy to clean and simplify the solution.
You have 2 methods below, take your pick only after you read the code and understand it (there is another one which I eliminated on purpose: this is an exercise of learning, so the obvious one is left as an exercise).
For the first method (paintBallAt_1), go read PrintStream.printf
For the second method (paintBallAt_2), go read String.substring
public class Midterm1_1 {
static private String ballBounce = "o";
public static void paintBallAt_1(int x) {
if(x==0) {
System.out.println("o");
}
else {
// will get your format strings as "%1$1c\n", "%1$2c\n", etc
String formatString="%1$"+x+"c\n";
System.out.printf(formatString, 'o');
}
}
// 6x20=120 spaces at max. Limit or expand them how you see fit
static public final String filler=
" "+
" "+
" "+
" "+
" "+
" "
;
static public final int MAX_BOUNCE=filler.length();
public static void paintBallAt_2(int x) {
if(x>MAX_BOUNCE) {
x=MAX_BOUNCE;
}
if(x<0) {
x=0;
}
String bounceSpace=filler.substring(0, x);
System.out.println(bounceSpace+"o");
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int yourNum;
System.out.println("How many spaces wide would you like the ball to bounce?");
yourNum= scan.nextInt();
int count = 0;
while (count < 50) {
System.out.println(ballBounce);
String x = " ";
for (int row = 1; row < yourNum; row++) {
System.out.println(x+"o");
x+= " ";
}
// bounce it to the left
for (int row = yourNum-1; row >= 0; row--) {
switch(row % 2) {
case 0:
paintBallAt_1(row);
break;
default:
paintBallAt_2(row);
break;
}
}
}
}
}
I keep receiving an error in the below codetelling me that the type must be an array but its returning a double for "total[agentnumber]" in the print statement. Can anyone explain this and how I might solve it in this context?
My goal: Write code where I input the number of periods, interest rates, and number of agents (where each agent's is assigned a principal equal to its agent number i.e. agent 1 receive 100, agent 2 receives 200, etc.) and print the balances of each agent. I want to do this in a loop rather than use the compound interest formula because I am trying to learn how to use Java.
Other issue: This is a bit crazily set up because I do not know how to return the results of the for loops. Where should I place "return" and what should I be returning, supposing that I am interested in ultimately printing the equivalent of agent[agentnumber].money for each of the agents.
public class Person{
public double money; // initialize
Person(double cash){
money = cash;
}
}
public class Bank {
public static double bank(double rate, double periods, int agents){
Person[] agent = new Person[agents];
double total;
for( int agentnumber = 0; agentnumber < agents; agentnumber++) {
agent[agentnumber] = new Person((agentnumber+1)*100); // assign starting incomes and instantiate players
for(int months = 0; months < periods; months++){
agent[agentnumber].money = agent[agentnumber].money*(1.0 + rate);
total = agent[agentnumber].money;
System.out.println("The total balance of player " + agentnumber + " is " + total[agentnumber]);
}
}
}
public static void main(String[] args) {
bank(0.05,120,3);
}
}
total is a double, so just print totalout instead of total[agentnumber]
I keep receiving an error in the below code telling me that the type must be an array but its returning a double for "total[agentnumber]" in the print statement. Can anyone explain this and how I might solve it in this context?
You get this error message because total is a double, not an array. In order to use [] the type must be an array. The solution is to print total instead of total[agentnumber].
Where should I place "return" and what should I be returning, supposing that I am interested in ultimately printing the equivalent of agent[agentnumber].money for each of the agents.
As your program is written right now, you'll get an error because you have declared that bank() will return a double, but you have no return statement in bank(). It's unclear why you'd want to return anything from bank(). You probably want to change
public static double bank(double rate, double periods, int agents)
to
public static void bank(double rate, double periods, int agents)
and then you don't need to return anything.
What and where should I be returning?
You seem to just want to print out the values of an array, so nothing needs returned. In that case, you could make the method have a void return type. It also isn't really clear why you needed the array because the local agents variable isn't needed by the main method, so if you did want the array, you should return Person[] instead of double...
You could also clean up the code like so.
public class Bank {
public static Person[] bank(double rate, double periods, int agents){
Person[] agent = new Person[agents];
for( int agentnumber = 0; agentnumber < agents; agentnumber++) {
Person p = new Person((agentnumber+1)*100); // assign starting incomes and instantiate players
for(int months = 0; months < periods; months++){
p.money = p.money*(1.0 + rate);
System.out.printf("The total balance of player %d at month %d is %.2f\n", agentnumber, months, p.money);
}
agent[agentnumber] = p;
}
return agent;
}
public static void main(String[] args) {
Person[] agents = bank(0.05,120,3);
}
}
I've had a go at rewriting your code above and ensured it compiles. There are a few best practice things I would change if this wasn't just a demonstration which I've added in comments
public class Bank {
public static void main(String[] args) {
Bank bank = new Bank(0.05,120,3);
}
// For readability and simplification I would make this public and
// move it into it's own file called Person.java
private class Person {
public double money;
Person(double cash){
money = cash;
}
}
public Bank(double rate, double periods, int numberOfAgents) {
Person[] agent = new Person[numberOfAgents];
// Typical java convention is to use camel case so
// agentnumber would become agentNumber
for( int agentnumber = 0; agentnumber < numberOfAgents; agentnumber++) {
agent[agentnumber] = new Person((agentnumber+1)*100);
for(int months = 0; months < periods; months++){
agent[agentnumber].money = agent[agentnumber].money*(1.0 + rate);
}
System.out.println("The total balance of player " + agentnumber + " is " + agent [agentnumber].money);
}
}
}
I'm currently working on a program that will calculate a simple interest rate and monthly payment taken from a loan. Although, I am running into one pretty big problem. I am trying to make it so that my principal value(see in code) is re-assigned the value of my new balance(see in code). Here is my code right now, I will explain in better detail under it:
import java.util.Scanner;
public class Payments {
public static double principal; //principal
public static double annualrate; //annual interest rate
public static double p; //monthly payment
public static double mr; //monthly interest rate
public static double nb; //new balance after monthly payments
public static double i; //interest (monthly)
public static String spaces = " "; //spaces for making clean columns
public static int months = 12;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Principal: $");
principal = input.nextDouble();
System.out.println("Anual Interest Rate: ");
annualrate = input.nextDouble();
System.out.println("Monthly Payment: $");
p = input.nextDouble();
calculate();
}
public static void calculate() {
mr = annualrate / 12;
i = mr * p;
nb = principal + i - p;
System.out.print("Month Principal Amt. Interest Payment New Balance");
System.out.println();
System.out.println();
for(int x = 1; nb > 0; nb = principal + i - p){
System.out.println(x + spaces + p + spaces + i + "%" + spaces + "$" + p + spaces + "$" + nb);
p = (Double)null;
p = nb;
}
}
}
So as you can most likely see by the comments in the code, all of the variables are shown. Now, disregard the null and me casting it to a double because that was the last thing that I tried to do before asking you guys :) anyways, my final question is, how can I go about re-assigning the value of principal to my new balance (nb)? Also, a side question, would a while-loop be better for this kind of program?
This has already been said in the comments, but the most immediate problem that I can see is in
for(int x = 1; nb > 0; x++){
your condition, nb > 0 will never ever change in that loop.
This means 1 of 2 things
your loop won't execute
your loop won't exit (infinite loop)
judging by how you're calculating nb(new balance) I'm assuming that it's going to be above 0 most of the time, and that your loop will never stop.
As things are right now, I'm not entirely sure what you actually want to do in that for loop or whether you even want a for loop at all, as that part is unclear.
what is the for loop supposed to do?
it almost looks like you're attempting to do something like
for (int x = 1; principal > 0; x++)
{
principal += principal * monthlyInterestRate;
principal -= payment;
System.out.println("insert output here");
}
nb = p + i - p; ???? looks like you need to double check your code.. the for loop doesnot change the condition at any place.. if the value is greater than 0, you will always lead it to an infinite loop, or it will never enter the loop at all( if np<1) . so check you code for runtime errors..