2011-11-28 22 views
2

讓我得到這個錯誤:java的 '無效' 類型不在這裏

--------------------Configuration: <Default>-------------------- 
C:\Documents and Settings\800508\Desktop\Chpt 8\Labs08\Lab08MATH02\Lab08MATH02st.java:20: 'void' type not allowed here 
    JOptionPane.showMessageDialog(null,r.getRational() + " equals " + r.getDec() + " and reduces to " + r.reduce()); 
                       ^

從這個代碼:

// Lab08MATH02st.java 
// The Rational Class Program I 
// This is the student, starting version of the Lab08MATH02 assignment. 


import javax.swing.JOptionPane; 


public class Lab08MATH02st 
{ 
    public static void main (String args[]) 
    { 
    String strNbr1 = JOptionPane.showInputDialog("Enter Numerator 1"); 
    String strNbr2 = JOptionPane.showInputDialog("Enter Denominator 2"); 

    int num = Integer.parseInt(strNbr1); 
    int den = Integer.parseInt(strNbr2); 

    Rational r = new Rational(num,den); 
    JOptionPane.showMessageDialog(null,r.getRational() + " equals " + r.getDec() + " and reduces to " + r.reduce()); 

    System.exit(0); 
    } 
} 



class Rational 
{ 

int num; 
int den; 
int n1; 
int n2; 
int gcf; 

public Rational(int n, int d) 
{ 
num = n; 
den = d; 
} 


// Rational 

// getNum 

// getDen 

// getDecimal 
    public double getDec() 
    { 
     return (double)num/den; 
    } 
// getRational 
    public String getRational() 
    { 
     return num + "/" + den; 
    } 
// getOriginal 

// reduce 
    public void reduce() 
    { 
    num = num/2; 
    den = den/2; 
    } 



    private int getGCF(int n1,int n2) 
    { 
     int rem = 0; 
     int gcf = 0; 
     do 
     { 
      rem = n1 % n2; 
      if (rem == 0) 
       gcf = n2; 
      else 
      { 
       n1 = n2; 
       n2 = rem; 
      } 
     } 
     while (rem != 0); 
     return gcf; 
     } 
} 

什麼問題?

回答

9

功能reducevoid返回類型。而void不能添加到字符串

函數必須返回了爲了將其追加爲一個字符串被表示爲一個字符串某個值。如果返回void編譯器和運行時環境不知道什麼追加到字符串。

1

您不能追加與字符串無效的數據類型是由下面的函數返回...

public void reduce() 
{ 
    num = num/2; 
    den = den/2; 
} 
0

這是因爲你的r.reduce()函數返回void類型,所以你不能追加它到字符串。它需要返回一些價值。此外,我並不積極,但是您正在添加字符串和數字,因此您可能需要將數字返回值轉換爲showMessageDialog調用中的字符串。

0

這是因爲你在你的字符串中插入了+ r.reduce()。你不能在返回void字符串插入一些東西。