[RESOLVIDO] Conversor de Temperatura

Olá pessoal !!

Sou novato em java e estou tentanto fazer um conversor de temperatura, os comentarios estào em inglês porque estudo no exterior e meu professor e casca grossa com relaçao a comentários, mais até então acho que só pelo código vocês entenderão com certeza :slight_smile: .

E seguinte e um conversor de temperatura de diferentes escalas:

1 -Mostra o menu e a opç~ao na tela para o usuario escolher.
2 - pega a temperatura para ser convertida.
3 - pega a unidade da temperatura de cada temperatura a ser convertida(Celsius, Fahrenheit e Kelvin).
4 - Converte a temperatura;
5 - Mostra o resultado na tela.

Quando executo o resultado so me mostra 0.0 e nunca o valor, acho que algum erro no metodo não sei, segue o que fiz até agora.
Muito obrigado desde já.

import java.util.Scanner;


public class tempConversion {

		// Main Method
		public static void main( String[] args ){
		
						
			char   scaleFrom = ' '; // From which temperature scale to convert from
			char   scaleTo   = ' '; // To which temperature scale to convert to 
			
			double tempFrom  = 0.0; // Temperature value to be converted
			double tempTo    = 0.0; // Temperature value converted 
			double result    = 0.0; // Result of the conversion 
			
			// Loop to repeat the menu until option chosen is "x"
		do {
				
				
				/* 
					Method to display the menu and store the scale from 
						which the temperature will be converted from
				*/
				
				scaleFrom = displayMenu(tempFrom, scaleTo, scaleFrom);
				
				
				/* 
					Only asks user to input more information, 
					if scaleFrom is different than "x" ( x = Exit )
				*/
				if ( scaleFrom != 'x' ){
				
					/* 
						Method to get the temperature value to be 
							converted and store the value entered by user
					*/
					tempFrom = getTemp();
					
					
					/* 
						Method to get the scale to which the 
							temperature value will be converted to
					*/
					scaleTo = getUnitTo();
					
//					tempTo = getTemp();
					
					// Method to convert the Temperature
					result = convertTemp( scaleFrom, tempFrom, scaleTo );
					
					// Method to display the conversion to the screen
					displayResult( scaleFrom, tempFrom, scaleTo, result );
					
				}
			} while ( scaleFrom != 'x' );
		}
		

		// Method to invoke the conversion of the temperature
		public static double convertTemp( char uFrom, double temp, char uTo ){
		
			// body of the Method
			
			if(uFrom=='a'){
				tempConversion.convFromCelsius(temp, uTo);
			}else if(uFrom=='b'){
				tempConversion.convFromFahrenheit(temp, uTo);
			}else if(uFrom=='c'){
				tempConversion.convFromKelvin(temp, uTo);
			}
			return uTo;
					
		}
		
		//  Method to convert temperatures in Celsius to the other ones
		public static double convFromCelsius( double value, char unitTo ){
		
			// body of the Method
			//value = tempConversion.convFromCelsius(getTemp(), unitTo);
			//unitTo= tempConversion.convFromCelsius(getTemp(), unitTo);
			
			if(unitTo=='b'){//celsius to Fahrenheit
				double newvalue= (value * 9/5) +32;
				 return newvalue;
				 
			} else if(unitTo=='c') {//celsius to kelvin
				double newvalue=(5/9 * (value - 32) + 273.15 );
				 return newvalue;
			 	}
			return value;
			 
		}
		
		//  Method to convert temperatures in Fahrenheit to the other ones
		public static double convFromFahrenheit( double value, char unitTo ){
		
			// body of the Method
			if(unitTo=='a'){//fahrenheit to celsius
				double newvalue=((value - 32) * 5/9);
				 return newvalue;
				 
			 } else if(unitTo=='c') {//fahrenheit to kelvin
				 double newvalue=(value + 459.67) * 5/9;
				 return newvalue;
			
			 	}
			return value;
		 
		}

		//  Method to convert temperatures in Kelvin to the other ones
		public static double convFromKelvin( double value, char unitTo ){
		
			// body of the Method
			if(unitTo=='a'){//kelvin to Celsius
				 value = value-273.15;
				 return value;
				 
			 } else if(unitTo=='b') {//kelvin to fahreinheit
				 value = value * 9/5 - 459.67;
				 return value;
			
			 	}
			return value;
			 
		}

		
		private static void displayResult(char scaleFrom, double tempFrom,char scaleTo, double result) {
			
			System.out.println("first option: "+scaleFrom+
								"\nTemperature:"+tempFrom+
								"\nTo be convert to:"+scaleTo+
								"\nThe result is:"+result);
			
		}

		private static double getTemp() {
			
			System.out.println("Enter the temperature: ");
			
			Scanner sc = new Scanner(System.in);
			Double.parseDouble(sc.nextLine());
			
			return 0;
		}

		private static char getUnitTo() {

				System.out.println();
				System.out.println("============================"+
						"\nTemperature Conversion"+
						"\n=========== MENU ==========="+
						"\na. To Celsius"+
						"\nb. To Fahrenheit"+
						"\nc. To Kelvin"+
						"\nx. Exit"+
						"\n============================"+
						"\nEnter an option:");
				try {
					
					Scanner sc = new Scanner(System.in);
					
					String menu;
					
					menu = sc.nextLine();
					
					switch (menu) {
					
					case "a":
						//System.out.println("Celsius");
						break;
						
					case "b": 
						//System.out.println("Fahrenheit");
						break;	
						
					case "c":
						//System.out.println("Kelvin");
						break;
						
					case "x":
						System.out.println("Good bye!!");
						System.exit(0);
						
						break;	
						
					default:
						System.out.println("Please enter a valid value");
						break;
					}
				} catch (NumberFormatException e) {
					
					e.printStackTrace();
				}
			
			return 0;
		}
	
		private static char displayMenu(double value, char unitTo, char menu) {
			
			System.out.println();
			System.out.println("============================"+
					"\nTemperature Conversion"+
					"\n=========== MENU ==========="+
					"\na. From Celsius"+
					"\nb. From Fahrenheit"+
					"\nc. From Kelvin"+
					"\nx. Exit"+
					"\n============================"+
					"\nEnter an option:");
			try {
				
				Scanner sc = new Scanner(System.in);
				
				String menu1;
				
				
				menu1 = sc.nextLine();
				
				switch (menu1) {
				case "a":
					//System.out.println("Celsius");
					tempConversion.convFromCelsius(value, unitTo);;
					
					break;
					
				case "b": 
					tempConversion.convFromFahrenheit(value, unitTo);;
					//System.out.println("Fahrenheit");
					break;	
					
				case "c":
					tempConversion.convFromKelvin(value, unitTo);
					//System.out.println("Kelvin");
					break;
					
				case "x":
					System.out.println("Good bye!!");
					System.exit(0);
					//exit = true;
					break;	
					
				default:
					System.out.println("Please enter a valid value");
					break;
				}
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return menu ;
			
		}
}

Primeiramente seja bem vindo ao fórum!

Quando você entra no case do método displayMenu você chama seus métodos e passa o value como parametro, porém o value não foi instanciado então ele não tem valor definido para efetuar as operações. No método getTemp você pede para entrar com um valor mas retorna 0? Por que isso? Não faz sentido, você deveria atribuir o resultado digitado a alguma variavel do tipo double por exemplo

System.out.println("Enter the temperature: ");
Scanner sc = new Scanner(System.in);
aux = Double.parseDouble(sc.nextLine());

        return aux;

No caso aux sendo do tipo double e uma variavel global para voce poder utilizar o valor nos metodos de suas operações.

Nos métos de calculos você faz assim

  //  Method to convert temperatures in Fahrenheit to the other ones  
        public static double convFromFahrenheit( double value, char unitTo ){  
          
            // body of the Method  
            if(unitTo=='a'){//fahrenheit to celsius  
                double newvalue=((value - 32) * 5/9);  
                 return newvalue;  
                   
             } else if(unitTo=='c') {//fahrenheit to kelvin  
                 double newvalue=(value + 459.67) * 5/9;  
                 return newvalue;  
              
                }  
            return value;  

Mas o problema aqui é igual ao que citei acima a sua variavel de retorno não recebeu nenhum valor. E nos demais metodos de calculo está igual.

Obrigado Filipi pela resposta, espero ter intendido o que voce me falou sou meio lento :), fiz essas modificações e agora consigo receber resultados mais nao corretamentamente,o meu problem e esse saber o que returnar para o que.
cabeça ta fritando

valew

 public class tempConversion {  
    	
    		
    		private static double newvalue = 0;
			static char menu;
    		static double temp;
    		static char menuTo;
      

 public static double convertTemp( char uFrom, double temp, char uTo ){  
              
                // body of the Method 
            	menu = uFrom;
            	tempConversion.temp = temp;
            	menuTo = uTo;
                  
                if(uFrom=='a'){  
                    convFromCelsius(temp, uTo);  
                }else if(uFrom=='b'){  
                    convFromFahrenheit(temp, uTo);  
                }else if(uFrom=='c'){  
                    convFromKelvin(temp, uTo);  
                }  
                return menuTo;  
                          
            }  

nesse caso esta igual para os outros dois Fahrenheit e kelvin.

 public static double convFromCelsius( double value, char unitTo ){  
              
                // body of the Method  
               temp = value;
               menuTo = unitTo;
                
                if(unitTo=='b'){//celsius to Fahrenheit  
                    newvalue= (value * 9/5) +32;  
                     //return newvalue;  
                       
                } else if(unitTo=='c') {//celsius to kelvin  
                    newvalue=(5/9 * (value - 32) + 273.15 );  
                     //return newvalue;  
                    }  
                return newvalue;  
                   
            }  

Igual para o getUnitTo() mais so que o retorno e menuTo

  private static char displayMenu() {  
                  
                System.out.println();  
                System.out.println("============================"+  
                        "\nTemperature Conversion"+  
                        "\n=========== MENU ==========="+  
                        "\na. From Celsius"+  
                        "\nb. From Fahrenheit"+  
                        "\nc. From Kelvin"+  
                        "\nx. Exit"+  
                        "\n============================"+  
                        "\nEnter an option:");  
                try {  
                      
                    Scanner sc = new Scanner(System.in);
                    
                    String menu1 = sc.nextLine(); 
                                    
                    menu = menu1.charAt(0);  
                    
                    switch (menu) {  
                    case 'a':  
                       // System.out.println("Celsius");  
                        //tempConversion.convFromCelsius(menu, getUnitTo());  
                          
                        break;  
                          
                    case 'b':   
                        //tempConversion.convFromFahrenheit(menu, getUnitTo());  
                        //System.out.println("Fahrenheit");  
                        break;    
                          
                    case 'c':  
                        //tempConversion.convFromKelvin(menu, getUnitTo());  
                        //System.out.println("Kelvin");  
                        break;  
                          
                    case 'x':  
                        System.out.println("Good bye!!");  
                        System.exit(0);  
                        //exit = true;  
                        break;    
                          
                    default:  
                        System.out.println("Please enter a valid value");  
                        break;  
                    }  
                } catch (NumberFormatException e) {  
                    
                    e.printStackTrace();  
                }  
                return menu ;  
                  
            }  

Valew filipi pelas dicas o problema principal estava na conversão.


 public static double convertTemp( char uFrom, double temp, char uTo ){  
               
                // body of the Method
        	 double tempConv = temp;// <<< o que estava faltando
                  
                if(uFrom=='a'){  
                    return convFromCelsius(tempConv, uTo);// <<adicionado o tempConv
                }else if(uFrom=='b'){  
                    return convFromFahrenheit(tempConv, uTo);  // <<adicionado o tempConv
                }else if(uFrom=='c'){  
                    return convFromKelvin(tempConv, uTo);  // <<adicionado o tempConv
               }  
                 return 0;  
                          
            }  

Aqui segue o resultado final.

    import java.util.Scanner;  
      
      
    public class tempConversion {  
    	
    		
    		//variable global
			static char menu;
    		static double tempx;
    		static char menuTo;
    		
            // Main Method  
            public static void main( String[] args ){  
              
            	            	
                char   scaleFrom = ' '; // From which temperature scale to convert from  
                char   scaleTo   = ' '; // To which temperature scale to convert to   
                  
                double tempFrom  = 0.0; // Temperature value to be converted  
//              double tempTo    = 0.0; // Temperature value converted   
                double result    = 0.0; // Result of the conversion   
                  
                // Loop to repeat the menu until option chosen is "x"  
            do {  
                      
                    /*  
                        Method to display the menu and store the scale from  
                            which the temperature will be converted from 
                    */  
                      
                    scaleFrom = displayMenu();  
                      
                      
                    /*  
                        Only asks user to input more information,  
                        if scaleFrom is different than "x" ( x = Exit ) 
                    */  
                    if ( scaleFrom != 'x' ){  
                      
                        /*  
                            Method to get the temperature value to be  
                                converted and store the value entered by user 
                        */  
                        tempFrom = getTemp();  
                          
                          
                        /*  
                            Method to get the scale to which the  
                                temperature value will be converted to 
                        */  
                        scaleTo = getUnitTo();  
                          
                        // Method to convert the Temperature  
                        result = convertTemp( scaleFrom, tempFrom, scaleTo );  
                          
                        // Method to display the conversion to the screen  
                        displayResult( scaleFrom, tempFrom, scaleTo, result );  
                          
                    }  
                } while ( scaleFrom != 'x' );  
            }  
              
			// Method to invoke the conversion of the temperature  
           public static double convertTemp( char uFrom, double temp, char uTo ){  
               
                // body of the Method
        	   	double tempConv = temp;
                  
                if(uFrom=='a'){  
                    return convFromCelsius(tempConv, uTo); 
                }else if(uFrom=='b'){  
                    return convFromFahrenheit(tempConv, uTo);  
                }else if(uFrom=='c'){  
                    return convFromKelvin(tempConv, uTo);  
               }  
                 return 0;  
                          
            }  
              
            //  Method to convert temperatures in Celsius to the other ones  
            public static double convFromCelsius( double value, char unitTo ){  
              
                
				// body of the Method 
                  
            	if(unitTo=='b') {
        			double newvalue=(1.8 * value) + 32;
        			return newvalue;
        		}
        		else if(unitTo=='a'){
        			return value;
        		}
        		else if(unitTo=='c') {
        			double newvalue = value + 273.15;
        			return newvalue;
        		}     
               
               return 0;  
                   
            }  
              
            //  Method to convert temperatures in Fahrenheit to the other ones  
            public static double convFromFahrenheit( double value, char unitTo ){  
              
                // body of the Method 
            	
            	if(unitTo=='b') {//to Fahrenheit
        			return value;
        		}
        		else if(unitTo=='a'){//to Celsius
        			double newvalue=(value - 32)*5/9;
        			return newvalue;
        		}
        		else if(unitTo=='c') {//to kelvin
        			double newvalue=(value + 459.67) * 5/9 ;
        			return newvalue;
        		}
                return 0;  
               
            }  
      
            //  Method to convert temperatures in Kelvin to the other ones  
            public static double convFromKelvin( double value, char unitTo ){  
              
                // body of the Method  
            	if(unitTo=='b') {//to Fahrenheit
        			double newvalue=value * 9/5 - 459.67;
        			return newvalue;
        		}
        		else if(unitTo=='a'){//to Celsius
        			double newvalue = value - 273.15;
        			return newvalue;
        		}
        		else if(unitTo=='c') {//kelvin
        			return value;
        			}
                return 0;  
                   
            }  
             
            
            //Method to display the result to the screen.
            private static void displayResult(char scaleFrom, double tempFrom,char scaleTo, double result) {  
                  
                System.out.println("First option: "+scaleFrom+  
                                    "\nTemperature:"+tempFrom+  
                                    "\nTo be convert to:"+scaleTo+  
                                    "\nThe result is:"+result); 
                
                System.out.println("");
                Scanner in = new Scanner(System.in);
        		System.out.println("Do you have another conversion?(Y/N): ");
        		String next = in.next();
        		next= next.toUpperCase();
        		if(next.equals("N")){
        			System.exit(0);
        		}
                  
            }  
            
            //Method to get the value from user
            private static double getTemp() {  
                  
                System.out.println("Enter the temperature: ");  
                  
                Scanner sc = new Scanner(System.in);  
                tempx = Double.parseDouble(sc.nextLine());  
                  
                return tempx;  
            }  
      
            private static char getUnitTo() {  
      
                    System.out.println();  
                    System.out.println("============================"+  
                            "\nTemperature Conversion"+  
                            "\n=========== MENU ==========="+  
                            "\na. To Celsius"+  
                            "\nb. To Fahrenheit"+  
                            "\nc. To Kelvin"+  
                            "\nx. Exit"+  
                            "\n============================"+  
                            "\nEnter an option:");  
                    try {  
                          
                    	 Scanner sc = new Scanner(System.in);
                         
                         String menu1=sc.nextLine(); 
                                         
                         menuTo = menu1.charAt(0);  
                          
                        switch (menuTo) {  
                          
                        case 'a':  
                            //System.out.println("Celsius");  
                            break;  
                              
                        case 'b':   
                            //System.out.println("Fahrenheit");  
                            break;    
                              
                        case 'c':  
                            //System.out.println("Kelvin");  
                            break;  
                              
                        case 'x':  
                            System.out.println("Good bye!!");  
                            System.exit(0);  
                              
                            break;    
                              
                        default:  
                            System.out.println("Please enter a valid value");  
                            break;  
                        }  
                    } catch (NumberFormatException e) {  
                          
                        e.printStackTrace();  
                    }  
                  
                return menuTo;  
            }  
          
            private static char displayMenu() {  
                  
                System.out.println();  
                System.out.println("============================"+  
                        "\nTemperature Conversion"+  
                        "\n=========== MENU ==========="+  
                        "\na. From Celsius"+  
                        "\nb. From Fahrenheit"+  
                        "\nc. From Kelvin"+  
                        "\nx. Exit"+  
                        "\n============================"+  
                        "\nEnter an option:");  
                try {  
                      
                    Scanner sc = new Scanner(System.in);
                    
                    String menu1 = sc.nextLine(); 
                                    
                    menu = menu1.charAt(0);  
                    
                    switch (menu) {  
                    case 'a':  
                       // System.out.println("Celsius");  
                       // convertTemp(menu, temp, menuTo);  
                          
                        break;  
                          
                    case 'b':   
                    	//convertTemp(menu, temp, menuTo);  
                        //System.out.println("Fahrenheit");  
                        break;    
                          
                    case 'c':  
                    	//convertTemp(menu, temp, menuTo);  
                        //System.out.println("Kelvin");  
                        break;  
                          
                    case 'x':  
                        System.out.println("Good bye!!");  
                        System.exit(0);  
                        //exit = true;  
                        break;    
                          
                    default:  
                        System.out.println("Please enter a valid value");  
                        break;  
                    }  
                } catch (NumberFormatException e) {  
                    
                    e.printStackTrace();  
                }  
                return menu ;  
                  
            }  
    }