I am a newbie to Java, and as an exercise wanted to WAP a simple program to print required no. of \'*\' characters according to the user. But somehow, the output of this cod
There are two mistakes in your code.
First
System.in.read()
Is reading a byte, not a integer, so, it is parsing the integer and getting the first byte of it.
Second
for (i = 0; i <= n; i++) {
will print always one star more than requested. So, it should be changed to
for (i = 0; i < n; i++) {
Suggestion: You could use Scanner to read your integer, for example
Scanner scanner = new Scanner(System.in);
no_stars = scanner.nextInt();
no_stars = (int)System.in.read();
This is using the ASCII value of whatever character the user enters. Try this instead:
no_stars = System.in.read() - '0';
Or, remove the no_stars
variable all together,
printstars(System.in.read() - '0');
Also, in your for
-loop, the condition should be i < n
, in order to perform the correct number of iterations. And there's no need to declare i
outside of the loop, you can just do for (int i = 0; i < n; i++)
.
Because you are reading ASCII code of the character from input here:
no_stars = (int)System.in.read();
It should be
no_stars = Integer.parseInt(Console.readLine());
Here is the corrected program for you: (the main problem was this line //no_stars = (int)System.in.read();)
public static void main(String[] args) {
int no_stars=0;
try{
System.out.print("Enter the number of stars:");
Scanner sc=new Scanner(System.in);
String name=sc.nextLine();
no_stars = Integer.parseInt(name);
//no_stars = (int)System.in.read();
}
catch ( Exception e) {
System.out.println("Error! Invalid argument!");
System.out.println();
}
printstars(no_stars);
}
public static void printstars(int n)
{System.out.println(n);
int i;
for(i=0;i<=n;i++)
{
System.out.println('*');
}
}
You need to parse the number received from System.in.read()
or alternatively read it as an integer, currently you just cast it, so if you enter 5, it passes 0x35 times (which is the value of the character '5')
You can do, for example:
Scanner scan = new Scanner( System.in );
printstars( scan.nextInt() );