2015-05-10 141 views
0

当我运行代码时,我得到提示输入数字,然后输入数字,但之后没有任何反应!我试图在这里实现方法重载。任何帮助,将不胜感激。我的代码出错了?我试图实现方法重载

import java.util.Scanner; 
public class MethodOverload { 
public static void main(String [] args){ 
    Scanner input = new Scanner(System.in); 
    Scanner inputDoub = new Scanner (System.in); 
    System.out.println ("Enter the int or double number"); 
    int x = input.nextInt(); 
    double y = inputDoub.nextDouble(); 
    //int x; 
    //double y; 
    System.out.printf("Square of integer value %d", x, "is", square(x)); 
    System.out.printf("Square of double value %f", y, "is", square(y)); 
     } 

    public static int square(int intValue){ 
     System.out.printf ("\nCalled square method with int argument: %d", intValue); 

     return intValue*intValue; 
    } 

    public static double square (double doubleValue){ 
     System.out.printf ("\nCalled sqauer method with double argument: %d", doubleValue); 
     return doubleValue*doubleValue; 
    } 

} 
+3

尝试使用一个'扫描仪'。此外,请参阅[这个线程](http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid-int-as-input)的例子使用'扫描仪'输入多个号码。 –

回答

1
import java.util.Scanner; 
public class MethodOverload { 
public static void main(String [] args){ 
    Scanner input = new Scanner(System.in); 
    System.out.println ("Enter the int or double number"); 
    double y = input.nextDouble(); 

    if(y % 1 == 0) { 
     int x = (int) y; 
     System.out.printf("Square of integer value %d is %d", x, square(x)); 
    }else{ 
     System.out.printf("Square of double value %f is %f", y, square(y)); 
    } 

} 

public static int square(int intValue){ 
    System.out.printf ("\nCalled square method with int argument: %d", intValue); 

    return intValue*intValue; 
} 

public static double square (double doubleValue){ 
    System.out.printf ("\nCalled sqauer method with double argument: %f", doubleValue); 
    return doubleValue*doubleValue; 
} 

} 

如果我理解正确的话,你只是想获得用户的输入,如果用户进入双用一个重载的方法,如果他进入整数用其他的。上面的代码是这样做的。

它只是将用户输入存储为double,如果用户输入模1 = 0(表示它是一个整数),则将其转换为整数并调用重载方法传递整数参数。另外,在上一次重载的方形方法中,您在printf函数中使用了%d而不是%f,如果要使用double,则使用%f。

您的前两个printf语句也是错误的,语法只允许显示一个字符串,其他参数用于替换所有的%符号。

+0

感谢兄弟..我很感激。我现在明白了。 – vib321

0

您尝试使用%d进行格式设置不正确。 PFB需要更改:

public static double square (double doubleValue){ 
    System.out.printf ("\nCalled sqauer method with double argument: %f", doubleValue); 
    return doubleValue*doubleValue; 
} 

一个观察:使用2个独立的扫描器实例没有意义。没用。 修正你的代码是这样的:

Scanner input = new Scanner(System.in); 
//Scanner inputDoub = new Scanner (System.in); 
System.out.println ("Enter the int or double number"); 
int x = input.nextInt(); 
double y = input.nextDouble(); 
+0

@ vib321更改您的代码并提供反馈。 – Rajesh

+0

我尝试了你提到的整改,但它不起作用。同样的事情发生在我上面提到的。但与其他提到的答案,它工作正常。我认为通过使用if语句,它可以工作.. – vib321

+0

@ vib321当问题陈述不明确时,会发生这种情况。我只是试图让你的代码工作。它以其他方式工作。我会说你应该去理查德建议的解决方案......如果这符合你的要求。 – Rajesh

相关问题