OyeBenny OyeBenny -5 years ago 81
Java Question

I've clearly declared my variable, what's the issue?

I'm trying to build a Rock, Paper, Scissor program:
And this is the error I get when it's running:

Lab03.java:38: error: variable ComputerInput might not have been initialized
System.out.println("The Computer plays: " + ComputerInput); //Prints computer's selection.

So how do I properly make this work? Also any tips and advice would be appreciated. Thank you!

import java.util.Scanner;
import java.util.Random;
import java.util.*;

public class Lab03
public static void main (String [] args)
Scanner scan = new Scanner(System.in); //Prepares for Keyboard input

String HumanInput;
String ComputerInput; // Vars that will carry the rock, paper, scissor selection.
int ComputerChoice, HumanChoice; //

System.out.println("ROCK, PAPER, SCISSORS!\n" +
"R = Rock, P = Paper, and S = Scissors \n" + "Please enter your move:"); //Prompts user for a selection.

HumanInput = scan.nextLine(); //Stores input
HumanInput = HumanInput.toUpperCase(); //Transform input to upperclass for standardization

Random generator = new Random();
ComputerChoice = generator.nextInt(3); // Range of choice are 0, 1, and 3.

if (ComputerChoice == 0) //Nested if statement to convert randomly generated number to a rock, paper, scissor selection.
ComputerInput = "R";
else if (ComputerChoice == 1)
ComputerInput = "P";
else if (ComputerChoice == 2)
ComputerInput = "S";

System.out.println("The Computer plays: " + ComputerInput); //Prints computer's selection.

System.out.println("Coded by Benny Villegas");

Answer Source

Try first to assign a null value or an empty string to the variable ComputerInput like this :

String ComputerInput="";

or a default value is better :

String ComputerInput="R";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download