gpt4 book ai didi

java - 首次使用温度转换器的方法

转载 作者:行者123 更新时间:2023-12-01 10:16:31 27 4
gpt4 key购买 nike

我是第一次使用方法,我的程序大部分工作正常,只是它不会循环转换语句及其对应的问题...用户输入与转换语句相对应,所以会提示3次

转化 #1

...

转化#2

...

转化#3

...

华氏高度到摄氏度之间的转换也有效,但不是从摄氏度到华氏高度的转换,下面是我的代码,任何见解都会有所帮助,

import java.util.Scanner;
import java.text.DecimalFormat;

public class TempConverter {

public static void main(String[] args){


DecimalFormat df = new DecimalFormat("#,###.0");
System.out.println("Temperature Converter");
System.out.println("---------------------");
System.out.println();
Scanner input = new Scanner(System.in);

System.out.print("How many conversions would you like to make: ");
int conversions=input.nextInt();

for(int i = 1; i < conversions; i++){
System.out.println("Conversion # " + i++);
System.out.println();
System.out.println ("To convert from celsius to fahrenheit type 1 ");
System.out.print ("To convert from fahrenheit to celsius type 2: ");
int choice=input.nextInt();

switch(choice){

case 1:
System.out.println();
System.out.print ("Enter a celsius temperature: ");
double cels=input.nextDouble();
double result=celsiusToFahrenheit(choice,cels);
System.out.println();
System.out.println ("The conversion of "+cels+" from celcius to fahrenheit is "+df.format(result) );
break;
case 2:
System.out.println();
System.out.print("Enter a farenheight temperature: ");
double fahr=input.nextDouble();
double result1=fahrenheitToCelsius(choice,fahr);
System.out.println ("The conversion of "+fahr+" from fahrenheit to celcius is "+df.format(result1) );

}
}
}



public static double celsiusToFahrenheit(int choice, double cels)
{

double converted=0.0;
if (choice == 1)
converted=9.0/5.0*cels+32;

return converted;
}

public static double fahrenheitToCelsius(int choice, double fahr)
{
double converted2=0.0;
if (choice ==2)
converted2=5.0/9.0*(fahr-32);

return converted2;
}

}

最佳答案

你有两个错误:

(1) 这行是错误的:

for(int i = 1; i < conversions; i++)

表示只要i < conversions就循环。如果conversions是 3,这意味着它将以 i==1 循环和i==2 ,但它不会循环 i==3因为3<3false 。使用<=

(2) i++在上面for语句将增加 i每次循环回来。这就是你想要的。然而,你通过放置另一个 i++ 来击败它。在代码中,这会增加它的额外时间。

关于java - 首次使用温度转换器的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35859256/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com