This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have a little bit of programming experience in web development languages such as HTML, CSS, JQuery, JavaScript, PHP, Python etc., but I am no taking an AP Computer Science class at school to learn Java. To see how similar it is to other languages in both syntax and how to go about different problems I decided to make a simple blackjack game that i have made in other languages before.
I have run into and error where I want to check to see what the user has input, and if it is a certain character, output different things such as a help sentence, welcome message, or just simply start or stop the game. For some reason it reads the input and I can log it to the console but it will not run the methods that I have created and called in the if statement inside the while loop. I am going to post the whole script since I have only been programming in Java for 2 weeks or so now and have no idea where my error could be.
import java.util.Scanner;
public class testClass {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
// Creates a scanner to get input from the keyboard
boolean gameStart = false;
// starts false, turns true when 'B' is input
welcome();
//displays the welcome message
while (true) {
// loop to play the game
String input = kbd.nextLine().toUpperCase();
// gets the next input from the user
if (input == "B") {
// checks the users input
gameStart = true;
// 'turns on' the game
double[] hand = drawCards();
// makes an array of 2 cards
System.out.print(input); //REMOVE
} else if (input == "?") {
// checks the users input
help(gameStart);
// displays the help message depending on if the game has started or not
System.out.print(input); //REMOVE
} else if (input == "Q") {
// checks the users input
System.out.print(input); // REMOVE
break;
// ends the game loop
} // ends if
} // ends while
} // end main
public static void welcome() {
// displays the welcome message
System.out.printf("Welcome to blackjack! %nEnter 'B' to begin. %nEnter '?' at any time to see help %nEnter 'Q' at any time to quit %n => ");
// the welcome message
}
public static void help(boolean gameStart) {
//displays the help message
if (gameStart) {
System.out.printf("Enter '?' at any time to see help %nEnter 'Q' at any time to quit %nEnter 'H' to hit %nEnter 'S' to stay %n => ");
// the help message when the game has already started
} else {
System.out.printf("Welcome to blackjack! %nEnter 'B' to begin. %nEnter '?' at any time to see help %nEnter 'Q' at any time to quit %nEnter 'H' to hit %nEnter 'S' to stay %n => ");
// the help message when the game hasn't started
}
} // end help
public static double randCard() {
// creates a random card
double card = Math.round(Math.random() * 10);
// number 1-10
if (card == 10 || card == 0) {
// no cards at 10 or 0
double x = Math.round(Math.random() * 10);
// variable used to choose J Q K or A when card is 0 or 10
if (x < 3) {
// Jack
card = 11;
} else if (x < 5) {
// Queen
card = 12;
} else if (x < 7) {
// King
card = 13;
} else {
// Ace
card = 10;
}
}
return card;
// returns a single card
} // end randCard
public static double[] drawCards() {
//creates 2 random cards and returns an array
double card1 = randCard();
double card2 = randCard();
// stores the 2 random cards in variables
double[] cards = {card1, card2};
// places the 2 random cards in an array
return cards;
// returns the array of cards
} // end drawCards
} // end class
There are list of things you need to correct:
As per Java Naming Conventions it's recommended to have class names starting with First letter as caps - Camel Case convention
String comparison should be done via equals() and not '==' that compares references.
That means that, change the occurrences of:
input == "B" to input.equals("B")
input == "?" to input.equals("?")
input == "Q" to input.equals("Q")
Be aware that if the inputis null, it will result in NullPointerException. Better practice would be to use "B".equals(input) in that case. Looks like these are already answered as part of comments as well.
P.S : I can't say that your program will work correct after this change, But correction of these should help you.
Use equals() method of string instead of ==. Hope that helps.
Related
this is my first time asking a question. If I'm breaking any rules let me know please :)
I want to verify that the user only types in only one character and store in a variable I have already declared initially. As well, loop back the question for user to type in again if they did not do what they are asked for
Here is a what I have done so far
import java.util.Scanner;
public class arraytesting {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int user_Choice;
int rowAndcolumns;
char[][] user_Array;
char user_Char;
do {
System.out.print("Enter your choice (1 to 9): ");
user_Choice = myKeyboard.nextInt();
if (user_Choice < 1 || user_Choice > 9)
System.out.println("Illegal choice, please try again.");
} while (user_Choice < 1 || user_Choice > 9);
switch (user_Choice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (rowAndcolumns < 1 || rowAndcolumns > 9)
System.out.println("Illegal choice, please try again.");
} while (rowAndcolumns < 4 || rowAndcolumns > 20);
do {
System.out.print("Which character do you want to fill your square with? (only one character)");
user_Char = myKeyboard.next().charAt(0);
if () // error message for user if they did not type correctly, Idk what to put in the
System.out.println("Illegal choice, please try again.");// boolean for it to compare
System.out.print(user_Char);
} while (); // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
}
I know I can put both of them in one do-while loop, but I want to focus on getting the boolean to check for user input.
edit: I would only like the user to enter only one single character
ex. '#' or 'a'
whereas "##" or "i am typing something that is not one character" is wrong
inside the spaces of if and while are how I want it to be verified
There is no need to do any check for "only 1 character entered". That makes no sense. You can't predict the future, so you cannot know if a user will enter more characters after 1 character has been entered. You will either just take the first character entered and work with it and ignore any potential additional characters - or you have to wait for more than 1 character, essentially breaking the program for users who do the right thing (enter only one character), just to be able to give them an error message when they finally do the wrong thing (enter another character).
That being said, this code:
user_Char = myKeyboard.next().charAt(0);
will actually wait for several characters to be entered until some kind of delimiter (per default some whitespace character, e.g. newline) is entered. That's exactly what you do not want.
You want to get one character from input, and one only. You don't have to care about more characters being entered after that:
user_Char = myKeyboard.next(".").charAt(0);
This tells myKeyboard to return the next String that matches the regex ".", which is any character, and only 1 character.
If you want to validate the entered character, e.g. only alphanumeric characters allowed, you can update your if and while to something like this:
if (!Pattern.matches("[a-zA-Z0-9]", new String(user_Char)))
or even better, use the String returned by myKeyboard.next("."):
String user_String = myKeyboard.next(".");
user_Char = user_String.charAt(0);
if (!Pattern.matches("[a-zA-Z0-9]", user_String))
or you could directly tell myKeyboard to only allow valid characters and skip the entire do/if/while error handling:
user_Char = myKeyboard.next("[a-zA-Z0-9]").charAt(0);
Edit
One thing your code doesn't handle right now is invalid inputs, e.g. letters when you call nextInt. This will actually throw a java.util.InputMismatchException, and you might want to wrap your nextInt() and next(...) calls in try-catch blocks to handle these exceptions.
Please check the code below, based on the discussion with Max, I used the .length() method to check the lenght of the string that the user typed.
You can check the type of the character to avoid the runtime exception in the first if statement using some methods in Character class that you use to check if the input is digit/letter or not ?
Character.isDigit(char)
Character.isLetter(char)
Character.isLetterOrDigit(char)
I also changed some variable names, Java is following the camel case style and class name has to be capitalized. I also refactored some code to check the range of the numbers to git rid of repeating same code on and on, check the method betweenExclusive
package stackoverflow.q2;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int userChoice;
int rowAndcolumns;
char[][] user_Array;
char userChar;
do {
System.out.print("Enter your choice (1 to 9): ");
userChoice = myKeyboard.nextInt();
if ( !betweenExclusive(userChoice, 1,9) )
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(userChoice, 1,9));
switch (userChoice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (!betweenExclusive(rowAndcolumns ,1 , 9))
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(rowAndcolumns ,4 , 20));
String input;
while (true){
System.out.print("Which character do you want to fill your square with? (only one character)");
input = myKeyboard.next();
// error message for user if they did not type correctly, Idk what to put in the
// boolean for it to compare
if ( input.length()>1){
System.out.print("Illegal character, try again please !!! ");
}else{
userChar = input.charAt(0);
System.out.print(userChar);
break;
}
} // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
public static boolean betweenExclusive(int x, int min, int max)
{
return x>=min && x<=max;
}
}
I'm currently working on an assignment for school and I am almost done but I just have one large problem I need to fix before I can add the final bit.
I need to create a program that prompts you to enter either 1 or 2, Afterwards it asks you to enter three words/names and saves them into an array.
Then, depending on whether you picked 1 or 2, it prints them in alphabetical order or flips around the lowercase and uppercase letters. I didn't add that part yet because I'm trying to fix a problem related to the very first input.
When you input a number other than 1 or 2, I am instructed to display an error message and ask for input again. I am pretty sure what I need to do is get the entire program to go back to the beginning because copy/pasting the entire program again would be bad, lol
A big problem is probably that I'm using if/else statements with for loops inside when I might need to put the entire thing inside a loop? But I'm not sure what condition I would use to start the loop if I put the entire code in it. I must be missing something here.
With what I have now, it gets stuck saying invalid input even if you put in a 1 or 2.
import java.util.Scanner;
public class IsabellaPiantoniLab5 {
public static void main (String[]args) {
//Ask for input
Scanner input = new Scanner(System.in);
System.out.print("Please choose either a number 1 or number 2.");
int numChoice = input.nextInt();
//if choice is 1 or 2
if (numChoice == 1 || numChoice == 2) {
System.out.println("Please enter three names: ");
String nameInput[] = new String[4];
//input loop
for (int i= 0; i < nameInput.length; i++) {
nameInput[i] = input.nextLine();
}
System.out.println("Values are:");
//display values if 1
if (numChoice == 1) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
//display values if 2
else if (numChoice == 2) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
}
//retry if invalid------i restart from the beginning if this happens
else if (numChoice != 1 || numChoice != 2) {
System.out.println("Invalid value. Please try again.");
//continue;
}
}
}
System.exit(0);
This will terminate the app, thus you can start it again using command line ( START [your app path])
Or
RunTime.getRuntime().exec(“Your app”);
System.exit(0);
Edit I misunderstood the question, I thought you wanted to restart the whole app
After discussing the approach with #csm_dev
It is way either to ask for the user input one more time by emptying the field and showing a message “please enter a valid input” with a clarification message
Here's what I'm working on: I have been working on a program in Java for a while now and I still have come to the ultimatum that I cannot do one thing, return to the start of the code - I always end up with a syntax error here or there.
I'm no pro so don't hate on me if this is an easy question!
Here's my code:
import java.util.Scanner;
public class Name {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int Name;
int Confirmation = 5;
System.out.print("What Game Would You Like To Buy? Type '9' for Help. Type '0' To View The Selection Of Games Available: ");
System.out.println("");
Name = keyboard.nextInt();
if (Name == 0) {
System.out.println("Fantasy World (0.99). Type '1' to Purchase.");
System.out.println("Sir Wags A Lot (0.99). Type '2' to Purchase.");
System.out.println("Take a Path (1.99). Type '3' to Purchase.");
// (plus a few more calls to println)
}
if (Name == 9) {
System.out.println("Help:"
+ "All games are corresponded to a single integer ranging from 1 to 8. Type 0 in the main bar too see the range of games."
+ "Too see this help message, type 9."
+ "For more information on each game, type the number followed by that number again. For example, I would type 22 too see more information on Sir Wags A Lot.");
}
if (Name == 1) {
System.out.println("Fantasy World is £0.99, are you sure you want to pay? Type '1' for Yes or '0' for No: ");
Confirmation = keyboard.nextInt();
}
if (Confirmation == 1) {
System.out.print("Thank You For Purchasing!");
}
if (Confirmation == 0) {
System.out.print("Ok, Come Again!");
}
if (Name == 11) {
System.out.println("Fantasy World:");
System.out.println("Title: Fantasy World");
System.out.println("Genre: RPG");
System.out.println("Description: Where you can live your dreams");
System.out.println("Price: £0.99");
}
if (Name == 22) {
System.out.println("Sir Wags A Lot:");
// (plus more println calls)
}
if (Name == 33) {
System.out.println("Take a Path:");
// (plus more println calls)
}
if (Name == 44) {
System.out.println("River Clear Up:");
// (plus more println calls)
}
if (Name == 55) {
System.out.println("PinBall:");
// (plus more println calls)
}
if (Name == 66) {
System.out.println("Ghost Girl:");
// (plus more println calls)
}
if (Name == 77) {
System.out.println("Dress Up:");
//(plus more println calls)
}
if (Name == 88) {
System.out.println("Where Is My Hat?:");
//(plus more println calls)
}
}
}
So basically, the variable is that the user types in a double digit integer to activate the bottom sub-classes. Say I want more info on 'Fantasy World':
I type 11 in the input console, it displays the text - maybe I want to buy the game but obviously, I don't want to restart the whole program - could I make it easier to just add some more code to the bottom of each sub-class that will return it to the integer input at the top again?
I've tried as easiest as possible to explain my situation.
You basically just need to put your code inside a do-while loop. You can read about it here. The program will keep running until the condition for the while statement is true.
You can add a loop - a do-while, or while- that will run forever (while(true)). Add another input type to your conditions which will be the exit code. If your exit code is 99, then when the user types 99 you can return; and that will end your program.
Here's the quickest fix:
Rename your main function to programLoop
Make a new main function that says this:
code:
public static void main(String args[]) {
while(true) {
programLoop(args);
}
}
The proper fix is to read up on how loops works, so you understand how the program flows.
I'm learning Java and working on some projects for fun. One issue that I have run in to is that when I use a Scanner object Eclipse warns me that:
Resource Leak: 'scan' is never closed.
So, I added a scan.close(); at the end of my code and that takes care of the warning.
The problem comes in because I have other classes in the same package that also use scanner objects and and Eclipse tells me to close scanner in those classes respectively. However, when I do that it seems like it closes ALL of the scanner objects and I get errors during run time.
Here is an example of what causes the error:
import java.util.Scanner;
public class test2 {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
int test = 0;
do {
//Do stuff
test = scan.nextInt();
System.out.println(test);
scanTest scanTest = new scanTest();
scanTest.test();
} while (test != 0);
scan.close();
}
}
import java.util.Scanner;
public class scanTest {
public void test() {
Scanner scanner = new Scanner(System.in);
int blah = scanner.nextInt();
System.out.println(blah);
scanner.close();
}
}
After scanner is closed in the scanTest class and the do loop in test2 is entered again an error occurs at the line test = scan.nextInt();
I tried moving the creation of the scanner object into the do loop just to make a new object every time as well but the error still occurs.
Not sure why this is happening or how I can make sure all my I/O objects are closed out without running into problems.
One post I came across mentioned that when System.in is closed I cannot be re-opened. If this is the case would I just need to make sure a scanner object with System.in is closed at the very end of the program and #suppress all of the other scanner warnings in other classes? Or would that still leave all those scanner objects open (bad)?
First, this is no memory leak.
Second, when you close a stream wrapper, the default implementation is for it to close the stream that it wraps. This means that the first time you close your Scanner (as it is written), yes, you close System.in.
In general, one would like to avoid closing System.in if they were meaning to read from System.in again. The best way to go about this depends on your program.
One might copy the information from System.in into a buffer of some sort and then scan the buffer. One might not close the Scanner, reusing it in other locations. One might even de-reference the Scanner for garbage collection and create multiple new Scanners on System.in.
These solutions are not all equivalent, some are considered much better than others; but, it all depends on the calling program. Experiment with a few, and if you run into a problem, open a new StackOverflow question where you show the relevant portions of your code, a description of the problem, the example input, and the wrong output (along with the desired output).
Good luck.
Yes, when you close a scanner you will be closing the underlying stream (in this case System.in). To avoid this, either create a global variable of scanner which can be used by all classes or have a central point for shutting down the scanner (just before the program exits would be ideal)
Don't name all your scanners the same. If you have multiple in one thing like this:
import java.util.Random;
import java.util.Scanner;
public class DayThree {
public static void main(String[] args) {
**Scanner textScanner = new Scanner(System.in);**
// boolean operands
// String(or objects) .equals() "this".equals("that") false
// primitive data types == 'a'=='a' -> true 5==6 false
// != 'a'!='a' -> false 5!=6 true
// ! !(true) -> false !(false) true
// > 5 > 4 -> true 'a' > 'b' false
// < 5 < 4 -> false
// <=
// >=
// && -> and 5 < 6 && 7 > 10 -> false
// if either side of and is false the outcome is false
// || -> or 5 < 6 || 7 > 10 -> true
// if either side of or is true the outcome is true
//System.out.println(!(5 < 10) && (7>3) || (true && false || true));
/* <-- this is a multi line comment
System.out.println("What is the most amazing show on tv this week? ");
String show = textScanner.nextLine().toLowerCase(); //this is case sensitive
show = show.toLowerCase(); // changes the strng to a lowercase version
show = show.toUpperCase();
if(show.equalsIgnoreCase("game of thrones")){ // .equalsIgnoreCase( ignores caps/lower)
System.out.println("Yes it is!");
}
else{
System.out.println("You are wrong.");
System.out.println(show + " is clearly inferior to Game of Thrones.");
}
System.out.println("Who is your favorite character in " + show + ".");
String character = textScanner.nextLine().toLowerCase();
if(character.contains("dragon")){
System.out.println("CGI magic is so cool!");
}
else if(character.contains("lanister")){
System.out.println("Wrong house.");
}
else{
System.out.println(character + "is pretty cool I guess...");
}
*/
// asdf alternate multi line comment use ctrl + / on highlighted text.
// doing this a second time undoes the comment
// sdaf
// asdf
// asdf
// asdf
// 1. ask about favorite something (pet)
// 2. save that into a string all lowercase
// 3. have a series of if else (x3) and else statements about the something
//NOTE: DO NOT END CONDITIONALS WITH ; example: if(boolean); IS WRONG.
**Scanner numScanner = new Scanner(System.in);** // the variable tells you what to use it for
Random rand = new Random(); // this makes a new random object
System.out.println("Pick a number.");
int num = numScanner.nextInt();
int sNum = rand.nextInt(9) + 1; // gives me a random num between 1-10
// nextInt(bound)gives you a num from 0-bound
//adding one gives you a num from 1 - bound + 1
if(num > sNum){
System.out.println("Too high");
System.out.println("The number was " + sNum);
}
else if(num < sNum){
System.out.println("Too low");
System.out.println("The number was " + sNum);
}
else{
System.out.println("Wow are you psychic? ");
}
textScanner.close();
numScanner.close();
}//main method
}
Put the *scanner name goes here*.close(); for each one of your scanners. If they all have the same name then change the ones that do something different from and other scanner.
This question already has answers here:
How to map character to numeric position in java?
(7 answers)
Closed 5 years ago.
So I'm stuck on this problem in my Java intro class. I'm a complete newbie at this stuff, so any help is appreciated. I have to design and create a program that accepts a user inputted letter (which should be either a-z or A-Z) and determine what position it holds in the alphabet. (so a would equal 0) I keep having issues with string to char and char to int conversions. Any tips or leads on how to design this program would be much appreciated. I've been working on this program literally all day and haven't had made any discernible progress.
Just subtract the char constant 'a' from your input char.
Try the following code:
char c = 'b';
System.out.println(c - 'a' + 1);
The output will be 2.
In order to get a user inputted anything use a Scanner. In this case the following code will prompt the user for a character then assign that to a variable called 'c'.
import java.util.*;
// assuming that the rest of this code is inside of the main method or wherever
// you want to put it.
System.out.print("Enter the letter: ");
Scanner input = new Scanner(System.in);
char c = Character.valueOf(input.next());
Then using this code use whatever method you like to convert to alphabetical position. Hope that helps!
I think it was answered already but putting it all together:
/**
* Gets the numerical position of the given character.
*/
private static final int convertToPosition(final char c) {
return c - 'A' + 1;
}
public static void main(String[] args) throws Exception {
System.out.print("Enter the letter: ");
Scanner input = new Scanner(System.in);
if (input.hasNext()) { // if there is an input
String inStr = input.next().toUpperCase();
if (inStr.length() != 1) {
System.out.println("Unknown letter");
return;
}
char c = inStr.charAt(0);
int pos = convertToPosition(c);
System.out.println("Position: " + pos);
} else {
System.out.println("no input");
}
}