PDA

Click to See Complete Forum and Search --> : System.in


Dillinger4
Nov 24th, 2000, 05:58 PM
Does anyone know how i can get System.in to work.
Ive done this before in C++ by just using cin <<
but i cant seem to get it to work in Java.

import java.io.*;

class menu{
public static void main(String args[]){

int choice = 0;
for(;;){
System.out.println(" ");
System.out.println("Press 1 to say Hi");
System.out.println("Press 2 to say Hello");
System.out.println(" ");
System.out.println("Enter a choice: ");
System.in(choice); // dosent seem to work
break;}



switch(choice){
case '1':
System.out.println("Your choice is 1");
break;
case '2':
System.out.println("Your choice is 2");
break;
default:
System.out.println("You must enter in a choice");
break;
}



}
}

Nov 24th, 2000, 11:44 PM
Check out my bolded type.

import java.io.*;

class menu{
public static void main(String args[]){

int choice = 0;
for(;;){
System.out.println(" ");
System.out.println("Press 1 to say Hi");
System.out.println("Press 2 to say Hello");
System.out.println(" ");
System.out.println("Enter a choice: ");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));//The "standard" input stream System.in is represented by the variable stdIn
try{
choice = Integer.parseInt(stdIn.readLine());//readLine returns a String. Integer.parseInt returns an int.
}catch(IOException e){System.out.println(e);
}
break;}



switch(choice){
case 1: //Java is Strongly typed. '1' is a character, 1 is an integer type. Notice that I removed the single quotes.
System.out.println("Your choice is 1");
break;
case 2:
System.out.println("Your choice is 2");
break;
default:
System.out.println("You must enter in a choice");
break;
}

}
}

[Edited by VirtuallyVB on 11-25-2000 at 12:46 AM]