I am currently struggling to find the reason why the code that I have created does not allow me to compile. it has been saying the same phrase over and over pokerTable.java:18: error: 'void' type not allowed here System.out.println (a1.rollDice());
here are the two files that have the code
import java.util.Scanner;
import java.util.Random;
import java.lang.Integer;
public class Dice
{
int Dice1;
int Dice2;
public Dice (int D1, int D2)
{
Dice1 = D1;
Dice2 = D2;
}
public void rollDice()
{
Random generator = new Random();
int rD1 = generator.nextInt(Dice1);
System.out.println ("Dice one rolled " rD1);
int rD2 = generator.nextInt(Dice2);
System.out.println ("Dice one rolled " rD2);
}
/*
public void addSide()
{
Scanner Sides = new Scanner (System.in);
System.out.print ("how many sides would you like to add? ");
String moreSides = Sides.nextLine ();
int s1 = int.parseint(moreSides);
System.out.println ("all of your dice have " s1 "sides.");
}
*/
}
the next file uses the methods within the previously mentioned file
import java.util.Scanner;
import java.lang.Boolean;
public class pokerTable
{
public static void main ( String [] args)
{
Dice a1 = new Dice (1,1);
Scanner scan = new Scanner (System.in);
System.out.print ("rollDice\t\t\nwhat would you like to do? ");
String Choice = scan.nextLine ();
boolean b1 = Boolean.parseBoolean(Choice);
if (b1)
{
System.out.println (a1.rollDice());
}
}
}
I am quite a beginner in this language so if anyone has a solution for this recurring compiling error, it would be of great help.
CodePudding user response:
Your rollDice()
method returns nothing (mind the void
keyword in the method signature). On the other hand System.out.println()
expects something as an argument, hence the compilation error.
Given that you want to "return both values individually so that I can show what each dice rolled, then add them together later.", you will need to change the rollDice()
method accordingly:
import java.util.List;
import java.util.Random;
public class Dice {
int Dice1;
int Dice2;
public Dice (int D1, int D2) {
Dice1 = D1;
Dice2 = D2;
}
public List<Integer> rollDice() {
Random generator = new Random();
int rD1 = generator.nextInt(Dice1);
System.out.println ("Dice one rolled " rD1);
int rD2 = generator.nextInt(Dice2);
System.out.println ("Dice one rolled " rD2);
return List.of(rD1, rD2);
}
}
CodePudding user response:
The return type of your function rollDice()
is void
. What means your method returns nothing. The System.out.println()
takes in parameter all type descending from Object
.
Your method should return a type different from void