I've written an extremely basic program with 3 options. While executing the "Quit" section of the code I get a InputMismatchError. I know that this is because the program is expecting an integer when me/User is giving it a String.
I was just wondering how I would go about setting something like this up.
I've also tried a string to char method but that's also gave me the same error.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
static Scanner S = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
int DisJ, ISJ, User;
ISJ = 1;
DisJ = 2;
String input = "";
// change print outs to appropriate names::::
System.out.println("--Main Menu--");
System.out.println("Display Journeys:" + ISJ);
System.out.println("Suitable Journeys:" + DisJ);
System.out.println("Quit: " );
//User = S.next().charAt(0);
User = S.nextInt();
if (User == 1)
{
System.out.println("You have selected Display Journeys");
try
(BufferedReader ReadFile = new BufferedReader(new FileReader("E:\\input.txt")))
{
String line = null;
while ((line = ReadFile.readLine()) != null)
{
System.out.println(line);
}
}
}
else if (User ==2)
{
System.out.println("You have selected Suitable Journeys");
}
System.out.println("Specify Destination: ");
String destination = S.next();
System.out.println("Specify Max Time (HH:MM): ");
String specificTime = S.next();
// This assigns the first two integers to the string hours
String hours = specificTime.substring(0,2);
//This assigns the last two integers to the string minutes
String minutes = specificTime.substring(3,5);
//integer.parseInt converts the string into an integer
int hours1 = Integer.parseInt(hours);
//integer.parseInt converts the string into an integer
int minutes1 = Integer.parseInt(minutes);
int Time;
// Equation to convert the hh:mm into minutes
Time = (60 * hours1) + minutes1;
System.out.println("Specify number of changes");
int Changes = S.nextInt();
System.out.println( "Destination selected: " + input + "Minutes specified: " + Time + "," + "Number of changes: " + Changes);
int quit;
String Quit = S.next();
if (Quit.equals("Quit")) {
System.out.println("Goodbye!");
System.exit(0);
}
try {
quit = Integer.parseInt(Quit);
}
catch (Exception e)
{
System.out.println("Type Quit to leave");
}
}
}
Is your question that you are not able to make the argument in the if statement true?
Try setting it as a boolean instead of an int / string, and throughout your code just have it changing quit to true/false instead of a number/string.
EDIT: Oh i see. So you just want to make it so that the user can press a key and it will quit, like a "Please enter Y to exit the program"
Do you have a scanner set up?
Wrap yor coe with a try and catch errors to handle them
int quit;
try {
quit = Integer.parseInt(Quit);
} catch (Exception e) {
// handle error...
}
http://beginnersbook.com/2013/04/try-catch-in-java/
To simply check what the user entered just accept a string and check its value like so:
Scanner scanner = new Scanner(System.in);
System.out.print("Quit?");
String text = scanner.nextLine();
if (text.equals("Quit") or text.equals("q")) {
//...
}
Related
Hi guys please is there anyone can help me out with this program?
write a program that asks the user to enter a postcode and returns the city for that
postcode. If the postcode in not in the list then it should return city not found.
The find city code must be in a separate method findCity()
The user should be able to continue entering postcodes until they enter 9999 to indicate they
are complete (9999 should not appear as “city not found”)
================================================
in the txt file:
Dandenong 3175
Frankstone 3199
Berwick 3816
Cranbourne 3977
Rosebud 3939
Thats what i've done so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) throws FileNotFoundException
{
try
{
File f = new File("Files\\cities.txt");
Scanner input = new Scanner(f);
String text;
while(input.hasNextLine())
{
text = input.nextLine();
process(text);
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void process(String text)
{ String name = null;
int id;
Scanner code = new Scanner(System.in);
System.out.println("enter the postcode");
id = code.nextInt();
Scanner data = new Scanner(text);
if(code.equals(0))System.out.println(name);
name = data.next();
id = data.nextInt();
while(data.hasNextDouble())
{
}
System.out.println(name+ " ");
// System.out.println(id+ " ");
}
}
File f = new File("d:\\cities.txt");
Scanner input = new Scanner(f);
Map<Integer,String> cityCode = new HashMap<Integer,String>();
String text;
while(input.hasNextLine())
{
text = input.nextLine();
Scanner data = new Scanner(text);
String name = data.next();
int id2 = data.nextInt();
cityCode.put(id2, name);
}
System.out.println("enter the postcode");
Scanner code = new Scanner(System.in);
int id = code.nextInt();
if(cityCode.containsKey(id)) {
System.out.println(cityCode.get(id));
} else {
System.out.println("City Not found");
}
Here's a straight forward approach:
First, you want user to enter a passcode. If passcode is lesser than 9999, you want to search the text file to find a city with that passcode. This thing can be implemented as:
int passcode = 5; // Suppose passcode is 5. You may suppose any value lesser than 9999
Scanner input = new Scanner(System.in);
// Ask user to enter a passcode. If user enters 9999 the while loop is exited
while(passcode < 9999)
{
System.out.println("Enter passcode: ");
passcode = input.nextInt();
// donot search if passcode is greater than or equal to 9999
if(passcode < 9999)
searchCity(passcode);
}
searchCity() method works like:
public static String searchCity(int passcode) {
Scanner citiesScanner = new Scanner(new File("Files\\cities.txt"));
while(citiesScanner.hasNext()) {
String city = citiesScanner.next();
String pass = citiesScanner.next();
if(Integer.parseInt(pass) == passcode) {
return city;
}
}
return "City not found";
}
Just try to break your problem into sub problems. Do some paper work before starting typing code. Things become a lot simpler this way.
import javax.swing.*;
import java.awt.*;
public class JCD {
public static void main(String[] args) {
String input, inputs;
int input1, input2;
input = JOptionPane.showInputDialog("Enter first number");
inputs = JOptionPane.showInputDialog("Enter second number");
input1 = Integer.parseInt(input);
input2 = Integer.parseInt(inputs);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}// close void
private static int findGCD(int number1, int number2) {
// base case
if (number2 == 0) {
return number1;
}// end if
return findGCD(number2, number1 % number2);
}// end static
} // close class
What can I add so that it will only accept integers? If not given an integer then it will go back to ask again.....
Put your input request in a while statement, check if it's an int, if not repeat the loop, otherwise exit. Do it for both your inputs.
Something like this
public static void main(String[] args) {
String input=null, inputs=null;
int input1 = 0, input2=0;
boolean err=true;
do{
try{
input = JOptionPane.showInputDialog("Enter first number");
input1 = Integer.parseInt(input);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
err=true;
do{
try{
inputs = JOptionPane.showInputDialog("Enter second number");
input2 = Integer.parseInt(inputs);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}
Note that this solution requires you to initialize your variables when you declare them
String input = null, inputs = null;
int input1=0, input2=0;
You should try with "try and catch".
input = JOptionPane.showInputDialog("Enter first number");
inputs=JOptionPane.showInputDialog("Enter second number");
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
// establish and use the variables if the characters inserted are numbers
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, e+ "is not a number");
//display a warning to le the user know
}
You could use something like this :-
boolean inputAccepted = false;
while(!inputAccepted) {
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
inputAccepted = true;
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog("Please input a number only");
}
... do stuff with good input value
}
What I want to do is make it so that when the program runs it will run the ordinary way but if the user selects that they want the display to be in html then it will run what the ordinary program would do but rather than display it in the console it will write what was going to appear in the console into a html file that the user specifies. Is this possible? I have code to accept the user input and have them specify what format they want it in as well as open the browser but I'm not sure if this could work. The code I have already is below:
import java.awt.Desktop;
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
// Used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
// Checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
// Also checks to make sure that there are no results that are just whitespace
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
}
catch (Exception e) {
return false;
}
}
// Checks to make sure that the data is an integer
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while (true) { // Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if (!file.exists()) {
continue;
}
if (UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("H")) {
Desktop.getDesktop().browse(file.toURI());
} else if (input.equalsIgnoreCase("T")) {
processFile(UserFile);
} else {
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
// Checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
// Splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
// Output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
// Displays the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
//This is where we'll write the HTML to if the user's chooses so
private static final String OUTPUT_FILENAME = "output.html";
public static void main(String[] args) throws IOException
{
final Scanner scanner = new Scanner(System.in);
final String content = "Foobar";
final boolean toHtml;
String input;
//Get the user's input
do
{
System.out.print("Do you want messages "
+ "written to (P)lain text, or (H)TML? ");
input = scanner.nextLine();
} while (!(input.equalsIgnoreCase("p")
|| input.equalsIgnoreCase("h")));
toHtml = input.equalsIgnoreCase("h");
if (toHtml)
{
//Redirect the standard output stream to the HTML file
final FileOutputStream fileOut //False indicates we're not appending
= new FileOutputStream(OUTPUT_FILENAME, false);
final PrintStream outStream = new PrintStream(fileOut);
System.setOut(outStream);
}
System.out.println(toHtml
? String.format("<p>%s</p>", content) //Write HTML to file
: content); //We're not writing to an HTML file: plain text
}
I have this basic enough Java program that asks the user to input songs to a music library array list. From there the user can shuffle their songs, delete a song, delete all etc. It's nearly finished, I just have one issue I can't resolve. It happens when I try export the array list to a text file. Instead of the content of the array list, my output would look like this, as opposed to the details the user submitted:
"1: MainClass.SongClass#c137bc9
MainClass.SongClass#c137bc9"
I'll post my code below, I'd really appreciate if someone could point me in the right direction!
My Final Project class which serves as my main class:
package MainClass;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalProject extends UserInput {
public String nextInt;
public static void main(String[] args) {
// SongLibrary iTunes; //Object stores the file cars.txt
// iTunes = new SongLibrary("MUSIC LIBRARY.txt");
// songData CLO = iTunes.readFileIntoList();
UserInput ui;
ui = new UserInput();
Scanner input = new Scanner(System.in);
int opt;
//Calls Methods Class so methods can be used below
Menu menuFunctions = new Menu();
//Calls FileReaderTest Class so file can be read
SongLibrary Reader = new SongLibrary();
//initial prompt only displayed when program is first ran
System.out.println("Welcome to your music library!");
do {
//Menu Prompts printed to the screen for the user to select from
System.out.println(" ");
System.out.println("Main Menu:");
System.out.println("........ \n");
System.out.println("Press 0 to Exit");
System.out.println("Press 1 to Add a Song");
System.out.println("Press 2 to View All Songs");
System.out.println("Press 3 to Remove a Song");
System.out.println("Press 4 to Shuffle Library");
System.out.println("Press 5 to Play a Random song");
System.out.println("Press 6 to Remove ALL Songs");
System.out.println("Press 7 to Save Library\n");
//Monitors the next Int the user types
opt = input.nextInt();
//"if" statements
if (opt == 0) {
//This corresponds to the condition of the while loop,
//The program will exit and print "Goodbye!" for the user.
System.out.println(" ");
System.out.println("Goodbye!");
} else if (opt == 1) {
//This method allows the user to add a song to the library.
//With the format being Title, Artist, Year.
System.out.println(" ");
menuFunctions.addEntry();
} else if (opt == 2) {
//This method prints the contents of the Array List to the screen
System.out.println("\n");
menuFunctions.viewAll();
} else if (opt == 3) {
//This method allows the user to remove an indiviual song from
//their music library
System.out.println("\n");
menuFunctions.removeOne();
} else if (opt == 4) {
//This method uses the Collections.shuffle method
//to re-arrange the track list
//song to simulate a music player's shuffle effect.
System.out.println("\n");
menuFunctions.shuffleSongs();
} else if (opt == 5) {
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
System.out.println("\n");
menuFunctions.randomSong();
} else if (opt == 6) {
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
System.out.println("\n");
menuFunctions.clearLibrary();
}
else if (opt == 7) {
try {
menuFunctions.saveLibrary();
} catch (FileNotFoundException x) {
System.out.println("File not found. " + x);
}
}
else {
//If the user selects an incorrect number, the console will
//tell the user to try again and the main menu will print again
System.out.println("\n");
System.out.println("Incorrect Entry, please try again");
}
} //do-while loop
while (opt > 0);
}
}
My SongClass class which holds the constructor and Get/Set methods
package MainClass;
public class SongClass {
private int songMinutes;
private int songSeconds;
private String songTitle;
private String songArtist;
private String songAlbum;
private int songYear;
public SongClass(int m, int ss, String t, String art, String al, int y){
songMinutes = m;
songSeconds = ss;
songTitle = t;
songArtist = art;
songAlbum = al;
songYear = y;
}
//GET METHODS
public int getMinutes() {
return songMinutes;
}
public int getSeconds() {
return songMinutes;
}
public String getTitle() { //
return songTitle;
}
public String getArtist() {
return songArtist;
}
public String getAlbum() {
return songAlbum;
}
public int getYear() {
return songYear;
}
//SET METHODS
public void setMinutes(int m){
songMinutes = m;
}
public void setDuration(int ss){
songSeconds = ss;
}
public void setTitle(String t){
songTitle = t;
}
public void setArtist(String art){
songArtist = art;
}
public void setAlbum(String al){
songAlbum = al;
}
public void printSong(){
System.out.println(songMinutes+":"+ songSeconds + " - " + songTitle + " - " + songArtist + " - " +songAlbum + " - "+ "("+songYear+")");
}
}
My menu class which holds most of the methods used in the program
package MainClass;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class Menu {
public void add(SongClass s) throws NumberFormatException {
try {
songLibrary.add(s);
} catch (NumberFormatException x) {
}
}
Scanner input = new Scanner(System.in);
UserInput ui = new UserInput();
public ArrayList<SongClass> songLibrary;
public Menu() {
songLibrary = new ArrayList<SongClass>();
}
public void removeOne() throws ArrayIndexOutOfBoundsException {
try {
System.out.println("Which song would you like to delete? (1 of " + songLibrary.size() + ")");
viewAll();
//calls the viewAll method to print current library to screen
int remove = input.nextInt();
//creates an int that corresponds to the nextInt typed.
if (remove > songLibrary.size()) {
System.out.println("Invalid ");
//if the user types a number higher than the highest index of the
//array list, they will be shown an error and return to the menu
}
else {
remove --;
SongClass s = songLibrary.get(remove);
System.out.println("Are you sure you would like to delete the following track from your music library? ");
s.printSong();
//confirms user wants to delete the selected track
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete = input.nextInt();
//Asks the user to input 1 or 2,
if (confirmDelete == 1) {
songLibrary.remove(remove);
//removes the index of the 4 array lists
System.out.println( "Removed.");
viewAll();
} else if (confirmDelete == 2) {
System.out.println("\n" + "Okay, the song won't be removed");
} else {
System.out.println("\n" + "Invalid option.");
}
}
}
catch (ArrayIndexOutOfBoundsException x) {
System.out.println("Please select an valid entry");
}
}
public void clearLibrary() {
System.out.println("Confirm?");
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete = input.nextInt();
//if the user types one, this triggers the clear method.
if (confirmDelete == 1) {
songLibrary.clear();
System.out.println("\n" + "Your music library has been cleared" + "/n");
}
}
public void shuffleSongs() {
//The shuffle function shifts the location of all the elements of an
//array list. This mimics the shuffle effect of a Music player
//The attributes of the song all get shuffled together because they
//are all linked by the same seed.
long seed = System.nanoTime();
Collections.shuffle(songLibrary, new Random(seed));
System.out.println("Your library is now shuffled" + "\n");
viewAll();
//Shuffles library, then outputs the new library list.
}
public void viewAll() {
if (songLibrary.isEmpty()) {
System.out.println("Your library is currently empty!");
} else {
System.out.println("Your Music Library" + "\n" + "Duration - Artist - Song - Album -(Year) " + "\n");
for (int i = 0; i < songLibrary.size(); i++) {
SongClass s = songLibrary.get(i);
s.printSong();
}
}
System.out.println("\n");
}
public void randomSong() {
int randomSong = (int) (Math.random() * (songLibrary.size() - 1));
//uses Math.random to generate a random double between 0.0 and 1.0
//it then multiplies it by the size of the array list - 1
//The end result is that a random index of the array list is selected
System.out.println("Now Playing:");
//the selected song randomSong is then outputted
//this changes each time the randomSong method is called
SongClass s = songLibrary.get(randomSong);
s.printSong();
}
public void saveLibrary() throws FileNotFoundException {
try (PrintWriter pw1 = new PrintWriter("MUSIC LIBRARY.txt")) {
File inFile = new File("MUSIC LIBRARY.txt");
Scanner in = new Scanner(inFile);
System.out.println("Your music library has been successfully exported!\n");
pw1.println("Your Music Library");
pw1.println(" ");
pw1.println("Duration - Artist - Song - Album (Year) " + "\n");
pw1.println(" ");
for (int i = 0; i < songLibrary.size(); i++) {
System.out.println("The loop ran this many times");
System.out.println(i);
int counter = i + 1;
pw1.println(counter + ": " + songLibrary.get(i));
}
System.out.println("Loop is over, PrintWriter should close.");
pw1.close();
}
}
public void addEntry() throws NumberFormatException {
try {
int minutes = ui.getInt("How many minutes does this song last?");
int seconds = ui.getInt("How many seconds does this song last?");
String title = ui.getString("What is the title of the track?");
String artist = ui.getString("Who performs the track?");
String album = ui.getString("What album is the track from?");
int year = ui.getInt("What year was the track released?");
System.out.println("Please enter a number:");
System.out.println("\n");
SongClass s = new SongClass(minutes, seconds, title, artist, album, year);
songLibrary.add(s);
System.out.println("Thank you!" + " " + title + " " + "was added to your library:");
} catch (NumberFormatException x) {
System.out.println(" ");
System.out.println("Year/Duration can use numbers only, please try again.");
System.out.println(" ");
}
}
}
And my user input class
package MainClass;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class UserInput{
private Scanner keyboard;
public UserInput() {
this.keyboard = new Scanner(System.in);
}
public String getString(String prompt) {
String line;
System.out.print(prompt + ": ");
line = this.keyboard.nextLine();
return line;
}
public int getInt(String prompt) {
String line;
int num;
System.out.print(prompt + ": ");
line = this.keyboard.nextLine();
num = Integer.parseInt(line);
return num;
}
public Date getDate(String prompt) {
String line;
SimpleDateFormat formatter;
Date date;
System.out.print(prompt + " (dd/MM/yyyy): ");
line = this.keyboard.nextLine();
formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
date = formatter.parse(line);
}
catch (ParseException ex) {
date = null;
}
return date;
}
public boolean getBoolean(String prompt) {
String line;
System.out.print(prompt + "? (Y|N)");
line = this.keyboard.nextLine();
return line.equalsIgnoreCase("Y");
}
}
"1: MainClass.SongClass#c137bc9 MainClass.SongClass#c137bc9"
This is what the default implementation of toString outputs.
You need to override toString in your SongClass:
#Override
public String toString(){
return String.format("%d:%d - %s - %s - %s - (%d)",
songMinutes,songSeconds, songTitle, songArtist , songAlbum, songYear);
}
An alternative (which may be better if you don't want to override toString, because that method is used elsewhere) is to loop over all elements of your list and explicitly format the output by calling appropriate getters (or another method similar to your printSong method).
This is a school project:
Objective:
Ask the user to input 2 number
A random number will be print to the user.
Must catch if input isn't Integer.
I have check online source, which i copied the code and use it.
Min + (int)(Math.random() * ((Max - Min) + 1))
The code work fine except if I input any integer less than 10. The Program will consider it as a letter and says "ERROR"
My Program:
import java.lang.StringBuffer;
import java.io.IOException;
import java.util.Random;
class RandomInput2
{
public static void main(String args[])
{
System.out.println("Programe Begins");
Random seed = new Random();
int n1 , n2, rand ;
System.out.println("What is your name?");
String InputString = GCS();
while(true)
{
try
{
System.out.println("What is your First number?");
n1 = Integer.parseInt(GCS());
System.out.println("What is your second number");
n2 = Integer.parseInt(GCS());
rand = n2+ (int)(seed.nextDouble()*((n1-n2)+1));
System.out.println(InputString+" Your number is "+rand);
}
catch(NumberFormatException NFE) //catch if integer's not number
{
System.err.println("ERROR");
System.err.println("Type in Integer only");
}
catch(Exception E) //catch General Error
{
System.err.println("ERROR");
}
;
}
}
public static String GCS() //Get Console String
{
int noMoreInput =-1; //set int
char enterKeyHit= '\n'; //set char
int InputChar;
StringBuffer InputBuffer = new StringBuffer(100);
try
{
InputChar=System.in.read();
while(InputChar != noMoreInput)
{
if((char)InputChar!=enterKeyHit)
{
InputBuffer.append((char)InputChar);
}
else
{
InputBuffer.setLength(InputBuffer.length()-1);
break;
}
InputChar = System.in.read();
}//ends while loop
}
catch(IOException IOX)
{
System.err.println(IOX);
}
return InputBuffer.toString();
}
}
Look at the GSC code -- if I enter 1 character and then hit enter, what's the length of the InputBuffer when I do hit enter?
Since you want to read a whole line, consider using an InputStreamReader to read System.in, and then a BufferedReader to wrap that reader (so that you can call readLine).