help please

T

teshmee

hello,

in fact i need to write a program, that accepts an input from the user
and 1 is being added to the value inputted 5 times.. i know i should
use FOR.

import java.io.*;
import java.util.*;

public class Test2
{
public static void main(String[] args) throws Exception
{
int userInput;
System.out.println("Please enter a Number:");
userInput = (int)System.in.read();
for (int i =1; i<6; i++)
System.out.println(userInput + i);
}
}

this is the code i wrote, but the result is wrong as i tried the
pseudocode and when tested with this pseudocode:
1. START
2. PRINT ‘Enter number’
3. INPUT Number
4. Result = Number
5. FOR I=1; I<6; I= ++
Result = Result + 1
PRINT Result
ENDFOR
6. STOP

when i tested using 10 as the value inputted,
i got: 11,12,13,14,15 as the result
but with the java code it is not the case..

Can anybody please help me find my error.

regards,
teshmee.
 
J

Joshua Cranmer

public class Test2
{
public static void main(String[] args) throws Exception
{
int userInput;
System.out.println("Please enter a Number:");
userInput = (int)System.in.read();
for (int i =1; i<6; i++)
System.out.println(userInput + i);
}
}

1. Don't use tabs on Usenet. Preferred indentation is 2, 3, or 4 spaces.
2. Your for loop isn't indented properly, which makes it hard to read.
when i tested using 10 as the value inputted,
i got: 11,12,13,14,15 as the result
but with the java code it is not the case..

I'm going to guess that the output you got was as if you typed in 49
without bothering to run the code.

InputStream.read() reads in one byte of input. So it reads the `1' you
typed in whose representation (since you're inputting in ASCII) is 49.
Certainly not what you want to do.

Possible options for reading in input:
1. Wrap in a BufferedReader, readLine(), and convert to integer.
2. Wrap in a Scanner and use nextInt().
3. Manually compose the characters yourself (not recommended).

The Java API documentation will help you with the first two methods.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,828
Latest member
LauraCastr

Latest Threads

Top