PDA

View Full Version : Declaring string and char variables


vjsmith
Nov 3, 2013, 03:30 PM
Very new to Java. Using netbeans for this class.

Homework is to use JOptionPane to prompt a user for their first name, middle initial, and last name Code is below.

The problem is on line 16. "incompatible types: String cannot be converted into char." I understand that String cannot be converted into char. I thought by declaring "middle" as char it would be stored as one. Need to be pointed in the right direction... everything works if "middle" is declared as a string but the instructor wants the middle initial to be a char.

Import javax.swing.JOptionPane;

Public class VSmithp1 { //project 1 to gather user information

Public static void main(String[] args) {

//declare variables
String firstname,lastname;
Char middle;
Int age, lucky1, lucky2, lucky3, average;

Firstname = JOptionPane.showInputDialog(null, "Please enter your first name:");

Middle = JOptionPane.showInputDialog(null, "Please enter your middle initial");

Lastname = JOptionPane.showInputDialog (null, "Please enter your last name:");

JOptionPane.showMessageDialog(null,"Welcome " + firstname + " " + middle + " "+lastname);

Scleros
Nov 30, 2013, 06:19 AM
Love them instructors making hoops to jump where none need exist. Middle is indeed a char as declared. The problem is you are trying to stuff a string into it. If middle must be a single char vs. an array of char use charAt() (http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29) method.