简体   繁体   中英

Java: How to print corresponding alphabets till a number entered by user?

I'm a beginner in Java and I'm trying to find out how to create a segment of code that can allow a user to enter a number between 1 and 26, and have the corresponding number of sequential letters to appear?

For example, if the user enters 3 then the computer would output a, b, c

Thank you in advance.

Update: I wrote the following code but there is an error message stating that the i in the integer conversion part is a duplicate of a local variable?

In another method, the user inputs the number between 1 and 26 and I'm reading that input as the String variable "num".

 public String getChar (int i){ String num; String text = mini1Num.getText(); Integer i = Integer.valueOf(text); return i > 0 && i < 27 ? String.valueOf((char)(i + 'A' - 1)) : null; } 
What am I doing wrong?

int n <---- number entered by user
for(int i=97;i<(97+n);i++)
    System.out.print((char)i+" ");

This gives you what you need.


EDIT
The error in your code lies in the return statement.

return i > 0 && i < 27 ? String.valueOf((char)(i + 'A' - 1)) : null; 

The value of (i + 'A' -1) is of type char . So the type casting basically takes the form of (char) char instead of (char) int , which is problematic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM