Java多参数方法问题帮助我完成

时间:2012-11-13 03:51:51

标签: java methods

我正在尝试完成以下代码我遇到了多参数方法的问题。任何帮助表示赞赏。

import java.util.Scanner;

public class Temp {


    public static void main(String[] args) {

      Scanner input = new Scanner(System.in);       //Creates the scanner for user input
      System.out.println ("Temperature converter");
      System.out.println ("Please make a selection using 1 & 2");
      System.out.println ("1 for celsius to fahrenheit");
      System.out.println ("2 for fahrenheit to celsius");
      int choice=input.nextInt();
        if (choice < 2 || choice > 1 )
      System.out.println ("Error your choice is not valid please select option 1 or 2");
      choice=input.nextInt();    
        System.out.println ("Enter temperature");
      double temp=input.nextDouble();
      double result=tempChanger(choice,temp);
        if (choice = 1)
             System.out.println ("The conversion of "+temp+" from celcius to fahrenheit is "+result );
        else
             System.out.println ("The conversion of "+temp+" from fahrenheit to celcius is "+result );

      public static double tempChanger(int choice, double temp)
      {
       int choice;
      if (choice = 1)
            double converted=9.0/5.0*temp+32;
        else
            double converted=5.0/9.0*(temp -32);

        Return converted;
        } 

    }
}

1 个答案:

答案 0 :(得分:1)

将此方法放在main方法的外面。另请注意,我对您的方法进行了一些更改。你做了几件错事

1)  if (choice = 1)  should be  if (choice == 1)
2)  Return should be return
3)  have written a method in main method.
4) no need to define int choice; again in tempChanger method

检查纠正方法

   public static double tempChanger(int choice, double temp)
{

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

  return converted;
  } 

找到已完成的编译版

import java.util.Scanner;

public class Temp {


public static void main(String[] args) {

  Scanner input = new Scanner(System.in);       //Creates the scanner for user input
  System.out.println ("Temperature converter");
  System.out.println ("Please make a selection using 1 & 2");
  System.out.println ("1 for celsius to fahrenheit");
  System.out.println ("2 for fahrenheit to celsius");
  int choice=input.nextInt();
    if (choice < 2 || choice > 1 )
  System.out.println ("Error your choice is not valid please select option 1 or 2");
  choice=input.nextInt();    
    System.out.println ("Enter temperature");
  double temp=input.nextDouble();
  double result=tempChanger(choice,temp);
    if (choice == 1)
         System.out.println ("The conversion of "+temp+" from celcius to fahrenheit is "+result );
    else
         System.out.println ("The conversion of "+temp+" from fahrenheit to celcius is "+result );



}

public static double tempChanger(int choice, double temp)
{

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

  return converted;
  } 
}