Looking to do something like in C#:
bool walkable = t.Type == TileType.Green ? true : false;
but in Java
Boolean international_F = (in.next() == 'Y') ? true : false;
The above is what I've tried so far. Wondering if it's even possible.
EDIT: I just noticed .nextChar() doesn't exist. Edited snippet to reflect that.
"nextChar": Assuming in is a Scanner, your issue is that Scanner doesn't have a nextChar() method. You could read a whole word, and then take it's first char:
char theChar = in.next().charAt(0)
boolean vs ternery: If your outputs are true/false, then you don't need an if. You can just write:
bool walkable = t.Type == TileType.Green; // C#
boolean international_F = in.next().charAt(0) == 'Y'` // Java
boolean vs Boolean: Please also note that boolean is the primitive boolean type in Java. Using Boolean will force it to be wrapped as the Boolean class.
case sensitivity: If you want to allow 'y' or 'Y', force the input to a known case first. Since charAt() returns primitive char, you need to use the static Character.toUpperCase().
Solution:
boolean isY = Character.toUpperCase(in.next().charAt(0)) == 'Y'
// - OR -
boolean isY = in.next().startsWith("Y") // not case-insensitive
Boolean international_F = "Y".equals(in.next()); // next returns a string
Boolean international_F =in.next().charAt(0) == 'Y';
You do not need a ternary operator to simply assign the result (true/false) of the evaluation of the condition. You need a ternary operator if you want to do something based on the result of the evaluation of the condition e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? [Y/N]: ");
boolean yes = in.nextLine().toUpperCase().charAt(0) == 'Y';
if (yes) {
System.out.println("You have chosen to continue");
} else {
System.out.println("You have chosen to stop");
}
// Or simply
System.out.print("Do you want to continue? [Y/N]: ");
if (in.nextLine().toUpperCase().charAt(0) == 'Y') {
System.out.println("You have chosen to continue");
} else {
System.out.println("You have chosen to stop");
}
// You can use ternary operator if you want to do something based on the result
// of evaluation of the condition e.g.
System.out.print("Do you want to continue? [Y/N]: ");
String response = in.nextLine().toUpperCase().charAt(0) == 'Y' ? "Yes" : "No";
System.out.println(response);
// Without a ternary operator, you would write it as:
System.out.print("Do you want to continue? [Y/N]: ");
String res;
char ch = in.nextLine().toUpperCase().charAt(0);
if (ch == 'Y') {
res = "Yes";
} else {
res = "No";
}
System.out.println(res);
}
}
A sample run:
Do you want to continue? [Y/N]: y
You have chosen to continue
Do you want to continue? [Y/N]: n
You have chosen to stop
Do you want to continue? [Y/N]: y
Yes
Do you want to continue? [Y/N]: n
No
This is an example demonstrating what you want to do:
char a = 'a';
char b = 'b';
Boolean b1 = (a == 'a') ? true : false;
Boolean b2 = (a == b) ? true : false;
System.out.println(b1);
System.out.println(b2);
The output will be:
true
false
Related
I need to create a program that asks the user for a string value and returns a string value of "rock" "paper" or "scissors" if the input was "r" "p" or "s" If the user typed in something different.
package loopsGamesProject;
import java.util.Scanner;
public class LoopsGamesProject_RockPaperScissors {
public static void main(String[] args) {
String in="-";
Scanner input= new Scanner(System.in);
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in=input.next();
if(in=="r"||in=="p"||in=="s"){
if(in=="r"){
in="Rock";
}
if(in=="p"){
in="Paper";
}
if(in=="s"){
in="Scissors";
}
while(in!="r"||in!="p"||in!="s") {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in=input.next();
if(in=="r"||in=="p"||in=="s"){
if(in=="r"){
in="Rock";
}
if(in=="p"){
in="Paper";
}
if(in=="s"){
in="Scissors";
}
}
}
input.close();
System.out.print(in);
}
}
}
The issue is, it will ask for a variable, but the terminate itself. I've tried adding an "out" variable. When I tried to do this using a do while loop, it kept asking for an input but never returned anything. I can't find the issue.
When you compare Strings in java, you need to use the .equals() method instead of the == function. This rule applies for all objects in java, String inclusive.
EG:
if (in.equals("r"))
//Rock!
You also need to replace the != and add a break statement to exit the loop. Something like this will do:
while (!(in.equals("r") || in.equals("p") || in.equals("s"))) {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in = input.next();
if (in.equals("r") || in.equals("p") || in.equals("s")) {
if (in.equals("r"))
in = "Rock";
else if (in.equals("p"))
in = "Paper";
else
in = "Scissors";
break;
}
}
EDIT: The above prompts twice. This will fix it:
public static void main(String[] args) {
String in = "";
Scanner input = new Scanner(System.in);
while (!(in.equals("Rock") || in.equals("Paper") || in.equals("Scissors"))) {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in = input.next();
if (in.equals("r") || in.equals("p") || in.equals("s")) {
if (in.equals("r")) {
in = "Rock";
}
if (in.equals("p")) {
in = "Paper";
}
if (in.equals("s")) {
in = "Scissors";
}
break;
}
}
input.close();
System.out.print(in);
}
As has been mentioned, you need to compare String equality using the String.equals(Object anObject) - alternatively you may use others methods (compareTo), but the == operator will not suffice (See here why).
On top of this, when you match the String you overwrite the String with the full word - in = 'r'; -> in = 'Rock';. But the condition you use to loop will only terminate when in is r, p or s specifically.
Further, you have some duplicated code there that could be reduced significantly. This is not a bug, but this can become very difficult to manage very quickly.
All things considered:
while (true) {
// Get the next input
in = input.next();
// Maps the word to the character
// If a word was not mapped, try again.
if (in.equals("r"))
in = "Rock";
else if (in.equals("p"))
in = "Paper";
else if (in.equals("s"))
in = "Scissors";
else
continue;
// Terminate the loop as you can infer a match was found.
break;
}
I wrote the following method, which boolean-return type is again assigned to another boolean in another method in which I call this method.
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while(answer != "y" || answer != "n") {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer == "y") {
b = true;
}
return b;
}
But no matter what I type in (y, n, or any other letter), I always end up in the while-loop again.
It's because you have an or rather than and on your test.
As it's currently coded you are saying:
while the answer isn't "y" or it isn't "n", loop.
which will always be the case.
What you want is:
while the answer isn't "y" and it isn't "n", loop.
which is coded as:
while (answer != "y" && answer != "n") (
Change to this: while(answer != "y" && answer != "n") and your code will work as you expect it to.
I suspect your problem lies here:
while(answer != "y" || answer != "n")
When your answer = "y" it isn't = "n" so the loop continues and vice verse.
Probably you want this:
while(answer != "y" && answer != "n")
I changed your code a bit to accept a char instead.
Here is the code:
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
char answer = input.nextLine().toLowerCase().charAt(0);
while(answer != 'y' || answer != 'n' ) {
System.out.println("Answer with y (yes) or n (no)");
//lower case so that it will get y or n, no matter what the casing is
answer = input.nextLine().toLowerCase().charAt(0);
}
if (answer == 'y') {
b = true;
}
return b;
}
or if you really want a string
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while( !(answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n")) ) {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer.equalsIgnoreCase("y")) {
b = true;
}
return b;
}
Remember to use .equals() or .equalsIgnoreCase() when comparing two Strings
This code is a snippet from a Blackjack game I'm making. No matter what I enter, the program never breaks out of a loop.
boolean bool = true;
do{
Scanner kb = new Scanner(System.in);
String choice = kb.next();
if(choice == "Hit" || choice == "hit") {
String action = "hit";
bool = false;
} else if(choice == "Stay" || choice == "stay") {
String action = "stay";
bool = false;
} else {
System.out.println("Do not recognize response. Retry.");
}
} while (bool == true);
What normally happens:
http://puu.sh/87KZk.png
Any help would be appreciated. Thanks!
You are comparing strings with ==. In Java we compare strings with .equals() instead.
You can do something like this:
boolean bool = true;
do {
Scanner kb = new Scanner(System.in);
String choice = kb.next();
if(choice.equals("Hit") || choice.equals("hit")) {
String action = "hit";
bool = false;
} else if(choice.equals("Stay") || choice.equals("stay")) {
String action = "stay";
bool = false;
} else {
System.out.println("Do not recognize response. Retry.");
}
} while (bool == true);
I also formatted some parts of your code for clarity.
As suggested in the comments below, you can also use equalsIgnoreCase to compare string regardless of their capitalization.
Hope this helps!
Ello, got a minor issue that I haven't got a clue on what's going wrong... Snippet of the code:
do{
String third = JOptionPane.showInputDialog(null, "Please enter Year ["+day+"/"+month+"/YY?]");
year = Integer.parseInt (third);
validChoice = validYear(year);
}while(!validChoice);
do{
String goUS = JOptionPane.showInputDialog(null, "Do you want to switch the format to US? [Y/N]");
goUS = goUS.toUpperCase();
char conversion = goUS.charAt(0);
validChoice = validOption(conversion);
switch(conversion){
case 'Y':
if(year < 10)
{
date.append(month).append("/").append(day).append("/" + "200").append(year);
}else{
date.append(month).append("/").append(day).append("/" + "20").append(year);
}
JOptionPane.showMessageDialog(null, date);
break;
case 'N':
if(year < 10)
{
date.append(day).append("/").append(month).append("/" + "200").append(year);
}else{
date.append(day).append("/").append(month).append("/" + "20").append(year);
}
JOptionPane.showMessageDialog(null, date);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid answer! Use Y/N", "Error", JOptionPane.ERROR_MESSAGE);
}}while(!validChoice);
//// METHODS:
public static boolean validYear (int year){
boolean isValid = true;
if(year < 1 || year > 99)
{
isValid = false;
}
return isValid;
}
public static boolean validOption (char conversion){
boolean isValid = true;
if(conversion != 'y' || conversion != 'n')
{
isValid = false;
}
return isValid;
}
The first part, with regards to the year, and with it's associated method, it loops fine if the input is wrong.
The second part, 'goUS', the method's remotely the same thing, checking the char if it's y/n - it works fine with regards to the check and all, but after hitting OK with the correct display of the date, it starts the goUS loop again, and the answers start to concatenate itself from the previous display, and so on. I want the app to just end after displaying the date.
Any help pointing out my flaw would be greatly appreciated.
Well, your validOption checks for lower case characters, but you pass it upper case characters.
The most flexible solution would be to normalise the case before comparing to expected values, such as
public static boolean validOption (char conversion) {
conversion = Character.toLowerCase(conversion)
return conversion == 'y' || conversion == 'n';
}
It seems the problem is because of case of input character, you are checking with lower-case in validOption and checking with upper-case in the main method. I believe your input is upper case, and validOption returns false.
Change validOption to:
public static boolean validOption (char conversion) {
return conversion == 'Y' || conversion == 'N';
}
or even use java.lang.Character toLower or toUpper methods.
Your validOption() does not work correctly. The working of the rest of the loop is independent of that, but the termination depends on the correct return value.
You check lower case characters there, but uppercase elsewhere. You change the checked character to uppercase just before the validity check. Change the characters to uppercase in validOption() too.
I am trying to create a menu in the console and have the user select an option, for some reason when I run the application it goes straight to the else, bypassing options a-d.
import java.util.Scanner;
public class UserChoice {
public static void main(String[] args)
{
boolean status = true;
while (status == true)
{
System.out.println("");
System.out.println("MENU");
System.out.println("");
System.out.println("A : String Functions");
System.out.println("B : Simple Arithmetic Functions");
System.out.println("C : Temperature Conversion");
System.out.println("D : Sequences");
System.out.println("E : Exit Application");
System.out.println("");
System.out.println("Please make a selection.");
Scanner keyboard = new Scanner(System.in);
String choice =null;
choice = keyboard.nextLine();
if (choice == "a" || choice == "A")
{
StringFunctions();
}
else if (choice == "b" || choice == "B")
{
ArithmeticFunctions();
}
else if (choice == "c" || choice == "C")
{
TemperatureConversion();
}
else if (choice == "d" || choice == "D")
{
Sequences();
}
else if (choice == "e" || choice == "E")
{
System.exit(0);
}
else
{
System.out.println("You have entered an invalid selection, please choose again.");
}
}
}
All String/Object comparisons should use equals() method instead of == (except String literals)
if (choice.equals("a") || choice .equals( "A")){....}
Apply same change to other else/if blocks also.
== compares reference equality. equals() method checks for content equality.
You may want to make sure that at least one character is entered:
String choiceString ="";
while(choiceString.length() <1){
choiceString = keyboard.nextLine();
}
Once done, you may want to get the first character from the string as:
char choice = choiceString.charAt(0);
now since your choice is char, you may write your conditions using single quote as below:
if (choice == 'a' || choice == 'A'){
.......
......
Also if you want, you want to change the case of String entered to upper or lower case, get the char and then use simpler conditions as below:
char choice = choiceString.toUpperCase().charAt(0);
if (choice == 'A'){
.....
}else if(...