[RESOLVED] Read from System.in in multiple functions
Hello,
I probably have a very simple question, but I can't really see to get it fixed. I am new to java and have to create some application. Now I want to read things from the console. I know how to do that. I first read an integer and then I walk that number of times through a loop.
Within that loop I read a second number and then I call another function which has to read text from the console. But I can't seem to get the reading in the second function to work. Any tips/help?
This is my current code:
Code:
public class Main {
private BufferedReader in
public static String ReadInfo() {
String strone;
String strall;
strall = "";
strone = in.readLine(); //Here is the problem, can I easily read info here?
return strall;
}
public static void main(String[] args) {
int iA;
int iZ;
String strG;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
try
{
iA = Integer.parseInt(in.readLine());
for (int i = 0; i < iA; i++) {
iZ = Integer.parseInt(in.readLine());
strG = ReadInfo();
};
}
catch(java.io.IOException ioe)
}
}
Re: Read from System.in in multiple functions
Try using the Scanner it's better and easier to use:
Code:
import java.util.Scanner;
public class Test {
private static Scanner scanner;
public static void main(final String[] args) {
scanner = new Scanner(System.in);
final int loops = scanner.nextInt();
int iG;
for(int i=0;i<loops;i++){
iG = scanner.nextInt();
final String strG = readInfo();
}
}
private static String readInfo() {
return scanner.nextLine();
}
}
Re: Read from System.in in multiple functions
Hello ComputerJy, thanks for your reply. I see that the scanner works better, now I also don't have to use the Try catch option. The only problem is that this program also does not read the line from readInfo. It just ends after the two ints.
I have inserted: system.out.println( strG ); to find whether it might accidently read the second int, but that is not true. Any idea why it does not read a string in readInfo?
Re: Read from System.in in multiple functions
My bad, try scanner.next(); instead of scanner.nextLine();
Re: Read from System.in in multiple functions
thank you! Now it indeed reads the line. This was what I needed. I now have some trouble with "system.out.println( strG );" but I think I'll manage that. Thanks for your help!
Re: Read from System.in in multiple functions
perhaps because you're spelling system with a lowercase s it should be "System.out.println". And if you're done here don't forget to mark the thread resolved from the Thread Tools menu
Re: Read from System.in in multiple functions
no appearently that is not it. But thanks for thinking with me. But I will mark it solved indeed.
/update (problem also got fixed).
I edited:
final String strG = readInfo();
into
String strG;
strG = "";
strG = readInfo();
Now it works