Creating a sub menu using String/char? - java

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'.

Related

How can I create an interactive program that ask for user's full name and display it everytime he wants to try again?

My code looks like this; it get's an error on line 18
error: bad operand types for binary operator '==' if(answer=='y'||answer=='Y') {
import java.util.Scanner;
public class FullName {
public static void main(String[]args) {
String firstName = " ", middleName = " ", lastName = " ";
String in; // checks for input
String answer; // checks for condition, YES OR NO
boolean ask; // use as a loop switch
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please indicate your full name: ");
in = scan.nextLine();
ask = scan.hasNext(in);
String str = String.format("My name is %s %s %s ", firstName, middleName, lastName);
System.out.println("Do you want to try again? (Y/N )");
answer = scan.Next();
if(answer=='y' || answer=='Y') {
ask = true;
} else {
ask = false;
}
} while(ask == true);
}
}
Let's just focus on these lines:
String answer;
...
answer = scan.next();
if (answer == 'y' || answer == 'Y') {
You will notice that I have tweaked the the style to make it more readable and consist with common Java style rules.
You will notice that I have fixed a compilation error by changing Next() to next().
But now for the interesting part:
answer == 'y' || answer == 'Y'
What you are trying to do here is test if the user is trying to reply in the affirmative or the negative; i.e. a response to your `"(Y/N)" question.
There are both technical and logical problems in the way you are doing it. The technical problem is that answer == 'y' tries to compare a String and a char using ==. Java doesn't allow that.
This is what the compilation error about "bad operand types for ==" is saying.
String and char are different types.
'Y' and "Y" are not the same value.
Expressions of the form "string == char" or "char == string" are not allowed.
You shouldn't compare strings using == anyway; see How do I compare strings in Java?.
So if you were just going to compare (one character) String with a char, there are a few ways to do it; e.g.
answer.charAt(0) == 'y'
or
Character.toString('y').equals(answer)
(In this context charAt(0) is safe. You are using the default Scanner delimiter, so next() is going to return a String with length of at least 1.)
But it would be simpler to do a String to String comparison:
answer.equals("y")
or
"y".equals(answer)
The latter has the advantage in some contexts that "y" can never be null so you will avoid possible NPEs.
Now for the logical problem. You have asked the user to respond to a (Y/N) question. But you are actually using Scanner to read a word (loosely speaking) so you may get one character, or more than one. Also, you are assuming that if the answer is not y or Y, then that means "no". But what if the user enters "yes" ... or "fish"? There are more possible answers to consider than the ones that you are expecting.
If I was marking this exercise, I would deduct a mark or two (out of ten) for not properly validating the user's input.
Since the answer variable is not stored as a string, change its variable type to char.
Also, use the following code to get the letter entered by the user.
answer = scan.next().charAt(0);
Use the following
import java.util.Scanner;
public class FullName {
public static void main(String[]args) {
String firstName = " ", middleName = " ", lastName = " ";
String in; // checks for input
char answer; // checks for condition, YES OR NO
boolean ask; // use as a loop switch
Scanner scan = new Scanner(System.in);
do {
System.out.print("Please indicate your full name: ");
in = scan.nextLine();
//ask = scan.hasNext(in);
String str = String.format("My name is %s %s %s ", firstName, middleName, lastName);
System.out.println("Do you want to try again? (Y/N )");
answer = scan.next().charAt(0);
if(answer=='y' || answer=='Y') {
ask = true;
} else {
ask = false;
}
scan.nextLine();
} while(ask == true);
}
}

Is it possible to check if the input is an integer without hasNextLine and exit loop if it's 0?

My method works perfectly,but I want to exit the loop if 0 is entered.I know I can use getArray.hasNextInt() and then if the input was an integer put into a new variable and then check again if it's 0,then leave the loop,but I think that'd be too long of a code and needs at least two other variables(an integer and a boolean) to be created.
I have written a method like so:
public static char[] play() { //Takes a string from the user,checks if the length is 5,and converts to character array.
boolean fiveChars =false;
System.out.println("Please enter your input: ");
Scanner getArray = new Scanner (System.in);
while(!fiveChars) {
String gotArray = getArray.nextLine();
if(gotArray.length()==5) {
myInput=gotArray.toCharArray();
break;}
else
{ if(gotArray.charAt(0)==0 && gotArray.length()==1) {
a++;
menu();
break;}
else
System.out.println("Please try again!Your input should consist of 5 characters!");
System.out.println("giving a new input doesn't count as one of your choices.");
}}
return myInput;
}
But it doesn't work.I want to know why
if(gotArray.charAt(0)==0 && gotArray.length()==1)
Blockquote
doesn't work here.Also,would you please tell me if there is a shorter way that works exists?Thanks.
Either
if(gotArray.charAt(0)=='0' && gotArray.length()==1)
OR
if(Integer.parseInt(gotArray.charAt(0))==0 && gotArray.length()==1)
should work.

Bad operand types for binary operator '||' error

I've been trying to create a program where if the user types in candy or C into the Scanner then the program will execute some code although I'm having difficulty comparing the two variables.
import java.util.Scanner;
public class StringOrChar
{
public static void main(String[] args)
{
System.out.println("Guess a word or character");
Scanner keyboard = new Scanner(System.in);
String input;
input = keyboard.nextLine();
char c = input.charAt(0);
if (input.equalsIgnoreCase("candy") || c = "C")
{
System.out.println("You guessed correctly.");
}
else
{
System.out.println("Try again...");
}
}
}
Upon running the program I receive the error " bad operand types for binary operator '||' " although I'm clueless as to how to go about fixing it. I'm aware that I could use
input.equals("C")
but I would like to know how to use the charAt() method.
If your intent is to allow the user to type "candy" or "C", your code won't get the job done even after you fix the compiler errors. It's checking the first character for C, which means that it will match any user input beginning with C, including Charlie, Caddywumpus, etc. If that's not what you want, then you have to compare the entire string to "C" and forget charAt(0):
if (input.equalsIgnoreCase("candy") || input.equalsIgnoreCase("C")) {
On the other hand, if you really do want to allow any input beginning with C, you need to make that clear in your question.
Few mistakes, need to correct. Though equalsIgnoreCase is sufficient to match candy or Candy or CANDY, ** anything uppercase/lowercase in word candy
1.) c = "C" is assignment not comparison.
2.) c is char here, so need to compare char with char, not char with String. so write c == 'C'
Code should go as below.
Code
public static void main(String[] args) {
System.out.println("Guess a word or character");
Scanner keyboard = new Scanner(System.in);
String input;
input = keyboard.nextLine();
char c = input.charAt(0);
if (input.equalsIgnoreCase("candy") || c == 'C') {
System.out.println("You guessed correctly.");
} else {
System.out.println("Try again...");
}
}
Ouput
1.) User Types C
Guess a word or character
C
You guessed correctly.
2.) User Types c
Guess a word or character
c
Try again...
3.) User types candy or Candy
Guess a word or character
candy
You guessed correctly.
You just won't require any other check
if (input.equalsIgnoreCase("candy") || c == 'C' )
Edit : handling only character input

Java How do i check for an arraylist object and make it true/false?

The program does one thing, depending on the users input, it removes an arraylist object and will ask you if u you want to remove another object, however, if the same object tries to be removed, i need the program to know and output 'such object does not exist', for example, 'remove "3"', then remove "3" again, the program output's "3" does not exist, the problem is that i have no idea how to implement it, what i have does not do much either. My theory is that you have to use boolean to check if the arraylist object is there in the first place, if it is: remove it, if not: output "not there".
here's what i have:
String[] id1 = { "1", "studentA" };
ArrayList<String> jim = new ArrayList<String>(Arrays.asList(id1));
System.out.println("would you like to remove an id? if so type in "
+ "the id number, otherwise type: no");
Scanner sc = new Scanner(System.in);
String i = sc.next();
int position = -1;
position = jim.indexOf(sc) - 1;
if (position == -1) {
System.out.println("not found in list");
} else {
System.out.println("found and removed");
jim.remove(i);
}
System.out
.println("would you like to remove another id? if so type in "
+ "the id number, otherwise type: no");
Scanner sc2 = new Scanner(System.in);
String j = sc.next();
int position2 = -1;
position2 = jim.indexOf(sc) - 1;
if (position2 == -1) {
System.out.println("not found in list");
} else {
System.out.println("found and removed");
jim.remove(j);
}
If you want your program to keep on asking for user input, you need a loop, for example a while-loop, which will only terminate if the user inputs no. In addition to that, you can simply use List.remove() for removing the element, and inspect the return value (true if the item was in the list and was removed) to give the correct feedback to the user:
String[] elements = { "1", "studentA" };
ArrayList<String> list = new ArrayList<String>(Arrays.asList(elements));
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("would you like to remove an id? if so type in "
+ "the id, otherwise type: no");
String input = sc.next();
if ("no".equalsIgnoreCase(input)) {
break; // exit the loop
}
if (list.remove(input)) {
System.out.println("found and removed");
} else {
System.out.println("not found in list");
}
}
I would suggest using public boolean remove(Object o) and this will return either true or false if the element is apart of the ArrayList or not respectively. You can set some boolean variable to equal that, and use an if statement to output your desired response.
boolean contains(Object o) would check if the ArrayList contains the object, you could scan through the list and check if it is there or not. You could also use the E get(int index) to scan through and check if the strings are equal to each other using a loop.

some logical error in taking up character in java

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);
}
}

Categories

Resources