This is my code...
class info{
public static void main (String[]args) throws IOException{
char gen;
while(true) { //problem occurs with this while
System.out.print("\nENTER YOUR GENDER (M/F) : ");
gen=(char)System.in.read();
if(gen=='M' || gen=='F' || gen=='m' || gen=='f'){
break;
}
}
System.out.println("\nGENDER = "+gen);
}
}
This is my output...
ENTER YOUR GENDER (M/F) : h
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) : m
GENDER = m
Could someone please help me understand why it is asking for the gender so many times.
You are probably workin' on Windows. When you give an answer and hit enter it adds two extra characters '\r' and '\n'. From stdin you receive only one character but those extra two remain in the buffer. When you give an incorrect answer you loop and automatically read from the buffer those two characters. They don't match the gender so the loop continues. The best solution would be to analyze strings instead of characters:
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String s = in.readLine();
Remember to use equals method instead of == in string comparison.
You pressed return after pressing h; you won't see the 'h' until you do so, but then you'll still see the return (and by the looks of it, that's coming out as two characters, possibly '\r' and '\n') before you see the next character.
You may want to read a line of text at a time, instead of a single character - you'll only see the input when the user presses return anyway, and it means you don't need to worry about this particular aspect.
You could use Scanner for this, or a BufferedReader wrapping System.in.
Use Scanner scan = new Scanner(System.in)
Here is the working version of your code....
public class Info{
public static void main (String[]args) throws IOException{
char gen;
Scanner scan = new Scanner(System.in); // Change made here
while(true) {
System.out.print("\nENTER YOUR GENDER (M/F) : ");
gen= scan.next().charAt(0); // Change made here
if(gen=='M' || gen=='F' || gen=='m' || gen=='f'){
break;
}
else{ // Change made here
System.out.println();
System.out.println("Your Option is not Available, pls try again");
continue;
}
}
System.out.println("\nGENDER = "+gen);
}
}
Related
In the following code why does the string inside println method shows twice.What should I do to show the message once per iteration
package practicejava;
public class Query {
public static void main(String[] args) throws java.io.IOException {
System.out.println("Guess a capital letter Character");
while ((char) System.in.read() != 'S') {
System.out.println("wrong.guess again to finish the program");
}
}
}
When a user writes in console characters, to confirm fact that his input is ready to be passed to application he presses enter key. But console doesn't pass only provided characters, it also adds to input stream (System.in) OS dependent line separator character(s) after it. Some OS use \r or \n (those are single characters, \x is just notation to represent them) others like Windows use \r\n (two characters) sequence as line separator.
Now those additional characters are also read by System.in.read() and since they are not equal to S System.out.println("wrong.guess again to finish the program"); is executed additional time.
To avoid such problems instead of working with raw data via System.in.read() consider using classes meant to make our life easier like java.util.Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Guess a capital letter Character");
String response = sc.nextLine();
while(!response.equals("S")){
System.out.print("incorrect data, please try again: ");
response = sc.nextLine();
}
Its because the first char that you read is the letter you typed, and then there is a second loop where the character is the line return.
For example on my linux machine, if I input "E" and then press enter, the first loop processes the char 69 'E', and then there is a second loop to process the carriage return (char 10).
What you can do is use a Scanner to get the user's input:
package practicejava;
import java.util.Scanner;
public class Query {
public static void main(String[] args) throws java.io.IOException {
Scanner s = new Scanner(System.in);
char c;
do {
System.out.println("Guess a capital letter Character");
c = s.next().charAt(0);
if (c != 's') {
System.out.println("Wrong! Guess again to finish the program.");
}
} while(c != 's');
}
}
s.next() will get the input from the user as a string and s.next().charAt(0) will return the first character in that string.
Basically I need to write this message:
System.out.println("Invalid grade - must enter exactly one letter");
And I don't know how to write an (if,for,while loop) which will find if letterGrade is bigger than one character, it has to be only one character if > 1 character it should follow this message.
And problem is that I know how to do it with string.length() but this is char and it doesn't work.
I tried this:
while(String.valueOf(letterGrade).length() > 1)
{
System.out.println("Invalid grade - must enter exactly one letter");
System.out.print("Enter grade (one character): ");
letterGrade = in.next().charAt(0);
}
But it doesn't print me message that I want, is there some method that finds char greater than one character? Can charAt() help me ?
I would propose to use regular expression since you might want to only allow letters a-f/A-F.
The expression to use would be
[a-fA-F]
The Java code used to check this would be:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Type");
Scanner reader = null;
try {
// Read from System.in
reader = new Scanner(System.in);
// Only work with first character
char c = reader.findInLine(".").charAt(0);
// ""+c creates a string since RegEx only works on strings
String testString = ""+c;
// Test string
if(!(""+c).matches("[a-fA-F]")) {
System.out.println("Invalid input");
return;
}
// c has a valid grade
System.out.println("Valid input");
}
catch(Exception ex) {
if(reader != null)
reader.close();
}
}
}
Test results:
a > Valid input
z > Invalid input
az > Valid input
za > Invalid input
You may use System.in.read(); if you want to read only one charactor.
So you should probably be a little more clear with your question and not in a paragraph form with the entire block of code including variable declaration and user inputlines.
In java, a char can only be one character (i am sure you know this) and so having multiple would mean that it is a string.
Assuming that you are working with letterGrade as an input from the user using Scanner, the way to check if the input is one character or not and do something in response will be
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.length==1)
{sysout("There is only 1 character in the input");
char value = input.indexOf(0);
}else
{sysout("Invalid grade");
}
I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.
I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
static String name;
static Scanner in = new Scanner(System.in);
static int choice;
public static void main(String[] args) {
while(choice != 5){
System.out.print("\nEnter Choice :> ");
choice = in.nextInt();
if(choice == 1){
try{
printName();
}
catch(IOException e){
System.out.println("IO Exception");
}
}
}
}
private static void printName()throws IOException{
System.out.print("\nEnter name :> ");
name = in.next();
//name = in.nextLine();
if (name != null){
System.out.println(name);
}
}
}
Try this instead: add name = in.nextLine(); after choice = in.nextInt();.
Then try replacing name = in.next(); with name = in.nextLine();
Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().
The second nextLine() is then used to get your string parameters.
The problem is easy: when you prompt the user to enter his/her choice, the choice will be an int followed by a new line (the user will press enter). When you use in.nextInt() to retrieve the choice, only the number will be consumed, the new line will still be in the buffer, and, so, when you call in.nextLine(), you will get whatever is between the number and the new line (usually nothing).
What you have to do, is call in.nextLine() just after reading the number to empty the buffer:
choice = in.nextInt();
if (in.hasNextLine())
in.nextLine();
before to call name = in.next(); do this in = new Scanner(System.in);
the object need rebuild itself because already has value.
good luck
Okay, so the program that I'm trying to figure out how to code (not really fix), I have to use Java to accept continuous input from the user until they enter a period. It then must calculate the total characters that the user input up to the period.
import java.io.*;
class ContinuousInput
{
public static void main(String[] args) throws IOException
{
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader userInput = new BufferedReader (inStream);
String inputValues;
int numberValue;
System.out.println("Welcome to the input calculator!");
System.out.println("Please input anything you wish: ");
inputValues = userInput.readLine();
while (inputValues != null && inputValues.indexOf('.')) {
inputValues = userInput.readLine();
}
numberValue = inputValues.length();
System.out.println("The total number of characters is " + numberValue + ".");
System.out.println("Thank you for using the input calculator!");
}
}
Please don't suggest the use of Scanner, the Java SE Platform we're stuck using is the SDK 1.4.2_19 model and we can't update it.
Explanation of empty braces: I thought that if I put in the empty braces that it would allow for continuous input until the period was put in, but clearly that wasn't the case...
Edit: Updated code
Current Error: won't end when . is inputted.
You have to switch the if/else statement with while.
Sample :
inputValues = userInput.readLine();
while (!".".equals(inputValues) {
//do your stuff
//..and after done, read the next line of the user input.
inputValues = userInput.readLine();
}
Note: Never compare the values of String objects with the == operator. Use the equals() method.
If you just want to test, whether the sentence the user inputs contains a . symbols, you just have to switch from equals() to contains(). It's a built-in method from the java.lang.String class.
Sample:
while (inputValues != null && !inputValues.contains(".")) {
//do your stuff
}
public static String getSubMenu(String submenu){
Scanner keyboard = new Scanner(System.in);
String chosen="", A="A",B="B", a="a", b="b";
do{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
}while(chosen.compareTo(A));
return chosen;
}
//This function below is fine.
public static void Menu(){
String unem="";
do{
System.out.println("Sub Menu");
System.out.println("Select an Option\n\n");
System.out.println("a.Sort by name\n" +
"b.Sort by time\n" +
"c.Exit sub-menu\n\n");
System.out.print("Input the number for the selected option: ");
unem= getSubMenu(unem);
if("a".equals(unem)|| "A".equals(unem)){
}
if("b".equals(unem)|| "B".equals(unem)){
}
}while ("a".equals(unem) ||"b".equals(unem) || "A".equals(unem) || "B".equals(unem));
}
}
Hi, I'm trying to make a sub menu. As you can see in the function Menu, when getSubMenu is called the user has to input a selected option in the function getSubMenu. I looked through my textbook and online and it doesn't seem you can use char within arguments such as
char a="a";
if(a != b);
If you can use characters instead of strings in the functions above please tell.
But moving on. What I am trying to do now is to get getSubMenu to return a String containing either 'A' || 'a' || 'b' || 'B' || 'c' || 'C' and then loop when the user does not put any of these as an input. I've tried attempting to use compareTo but I receive a Type mismatch: cannot convert from int to boolean error how can I improve on this. What syntax can I use so that this can work.
Thanks for everyone who will help and contribute to this.
EDITED: NEW WORKING FUNCTION
public static String getSubMenu(String submenu){
Scanner keyboard = new Scanner(System.in);
boolean looped = true;
String chosen="";
do{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
if("a".equals(option)|| "A".equals(option) || "b".equals(option)|| "B".equals(option) || "c".equals(option)|| "C".equals(option)){
looped = false;
}
else
System.out.println("Wrong input");
}while(looped);
return option;
It may of not been what I was aiming for but it still did it job.
while(chosen.compareTo(A)) is where you should get an error . The method compareTo(String) returns an int which you cannot use in while(boolean expression) , it requires a boolean expression which shall evaluate to true or false. I am pasting a code for reference , improvise on it :
public static String getSubMenu(String submenu) {
Scanner keyboard = new Scanner(System.in);
List<String> list = Arrays.asList(new String[]{"A","B","C"});
do {
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
} while (chosen!=null && list.contains(chosen.toUpperCase()));
return chosen;
}
compareTo() compares 2 objects and returns an int that represents which object was greater. Since it is not a boolean your do while loop fails to compile. If you're looking for a specific input from the user, use this snippet.
do
{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
}
while (!chosen.trim().equalsIgnoreCase("a"));
You'll need to trim() the string to remove characters like whitespaces and you can use equalsIgnoreCase() to match 'A' and 'a'.