I'm having trouble with this:

   import java.util.Scanner;
   public class triangleLoop {
      public static void main (String[] args) {
         int height, row, col, spa;
         String hyp;
         Scanner kbd = new Scanner(System.in);
         System.out.println("Enter the desired height of the triangle: ");
         height = kbd.nextInt();
         System.out.println("What side do you want the hypoteneuse on? (left/right)");
         hyp = kbd.nextLine().charAt(0).toUpperCase();
         System.out.println(hyp);
      }}

triangleLoop.java:10: error: char cannot be dereferenced

hyp = kbd.nextLine().charAt(0).toUpperCase();
                          ^

1 error

Whats the problem? I'm new to java programming but it looks ok to me. Is there something I'm missing?

Recommended Answers

All 8 Replies

hyp is a String but you are trying to set its value to a char

I'm not sure. Try breaking it up into multiple steps and print it out step by step to see where it might be going wrong. What happens when you change it to charAt(1), does it return the second character or throw an error again?

hyp is a String but you are trying to set its value to a char

yeah i realized that but its still doing it. It compiles but doesn't run

hyp is a String but you are trying to set its value to a char

this is the error that shows up when i run it:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

Then you have a String of size 0 which means the input probably isn't being read properly. Print out the read text before you do stuff with it.

"doesn't run" implies a run-time error or exception (array index out of bounds, maybe?). Next time please post the complete text of any error messages.
This one looks like the classis Scanner "gotcha" - nextInt followed by NextLine
nextLine leaves the scanner pointing just after the int, ie just before the following newline character, then nextLine takes eveything up to the newline, which is a zero-length String.

ok so I found the problem. It prints this out when ran:

System.out.println("What side do you want the hypoteneuse on? (left/right)");

But when it goes to:

hyp = kbd.nextLine().charAt(0).toUpperCase();

It will not let me imput anything. Its almost like it hits enter for me. And thats why there is no string entered for it to do '.charAt(0)'

why is that happening

Try this:
hyp = (hyp.charAt(0)+"").toUpperCase() + hyp.substring(1);
System.out.print(hyp);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.