Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 'void' type not allowed here

Tags:

java

I get this error:

--------------------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());
                                                                                 ^

From this code:

// 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;
        } 
}

What's the problem?

like image 204
dalton metzler Avatar asked Aug 04 '26 13:08

dalton metzler


2 Answers

The function reduce has void return type. And void cannot be appended to a String

The function must return some value that can be represented as a String in order to append it to a string. If you return void the compiler and the runtime environment don't know what to append to the string.

like image 186
hage Avatar answered Aug 06 '26 03:08

hage


You can not append void datatype with String which is returned by the following function...

public void reduce()
{
    num = num / 2;
    den = den / 2;
}
like image 45
vidit Avatar answered Aug 06 '26 04:08

vidit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!