So I just started learning Java, its literally like my 1st day and I wanted to try to make a coinflip game. I already know a decent amount of Javascript and so i was trying to apply that knowledge to java. So everything has been working so far except one thing: Prompting a user for a choice. So read online that i have to import a scanner so i did that as you can see from my code. I also tried some code where you can have the user import a string but you can see a bit later in my program i change the variable userChoice into a number. So basically i just need help with this. If there is some way to have a variable type that can store both numbers or strings that would be best. But im tottaly open to other ways of doing this! Thanks in advanced! Here is the code:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hi");
int bob;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
System.out.println("You entered "+ userChoice);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(userChoice == "Heads") {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!")
}
}
}
Use a scanner, as you said:
Scanner in = new Scanner(System.in);
Then, prompt the user to enter something in:
String userChoice = in.nextLine();
Also, when you compared strings:
if(userChoice == "Heads") {...
that's bad to do for none-primitive objects. It's best to only use the == to compare values that are ints or enums. If you compare a String like this, it won't work, because it's checking if the objects are the same. Instead, compare like this:
if(userChoice.equals("Heads")) {...
Also, to convert to an int (NOTE: You can't convert one type of object to another that aren't related in any way! You'll have to create a new object if you're wanting to do that), do this:
int myInt = Integer.parseInt(myString); // NOTE: Can throw NumberFormatException if non-number character is found.
So your program should look somewhat like:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
//System.out.println("hi");
Scanner in = new Scanner(System.in);
int bob;
int userChoice;
String input;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
input = in.nextLine(); // waits for user to press enter.
System.out.println("You entered "+ input);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(input.equals("Heads")) {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!");
}
in.close(); // IMPORTANT to prevent memory leaks
}
}
You've already imported the Scanner class so you can now create a variable of the type Scanner for taking inputs.
Scanner in = new Scanner();
userChoice = in.nextLine();
nextLine() can be used to input a character or a string from the user.
To convert the string into a integer, You can assign the integer value to the string in the following way.
if(userChoice == "Heads") {
userChoice = "" + 0;
}
else {
userChoice = "" + 1;
}
"String" datatype in Java can hold both numbers and strings (as you asked). You can get user input using Scanner utility as below:
Scanner input = new Scanner();
userChoice = input.nextLine(); // if it is a string
//userChoice = input.nextInt(); // if it's integer choice
If your string is an integer then you can also parse it to get its integer value. For parsing:
int value = Integer.parseInt(userChoice);
Also for comparing String values you should use "equals" function rather than "==".
if(userChoice.equals("Heads")){...} //rather than if(userChoice == "Heads"){...}
Having imported java.util.Scanner, to get input from the user as a String, create a Scanner object that parameterizes System.in and assign userChoice the value of nextLine() invoked by the Scanner object:
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
A few things about your code. The relational operator, ==, is used for comparing primitive data - not objects. Use string1.equals(string2) to see if two strings are equal.
Also, bob = (int) Math.floor(Math.random()*2); is really bob = (int)(Math.random() * 2);
because casting a double as an integer truncates the double to the highest integer less than or equal to it.
It might help you to get the ideas.
public static void main(String[] args) {
Random rd = new Random();
//Enter 1 0R 0
int bob = rd.nextInt(2);
String userChoice;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number");
userChoice = sc.nextLine();
System.out.println("You entered " + userChoice + " and bob is " + bob);
int uc = Integer.parseInt(userChoice);
if (uc == bob) {
System.out.println("Hehe");
} else {
System.out.println("Sorry");
}
}
Related
So, I want to receive input from the user, check if they used alphabetical values and then check if it is too long. If too long, I want to start again from the top (checking if alphabetical) by calling the method I am in. However, when I start over and I type, say "Danny", this will show:
Output: "Thank you, got Danny"
Output: (length of previous, too long input) + "is too many characters, try to keep it under 30."
So somehow, it keeps the original input (that was alphabetical, but above 30) saved and it doesn't alter it when it starts over. Anyone know what I should do instead?
public static String inputPattern() {
Scanner scanner = new Scanner(System.in);
String player;
int strLength;
System.out.println("Please enter your name:");
while (!scanner.hasNext("[A-Za-z]+")) { //Checks if alphabetical value
System.out.println("Please stick to the alphabet!");
scanner.next();
}
player = scanner.next();
player += scanner.nextLine();
System.out.println("Thank you! Got " + player);
strLength = player.length(); // Saves the length of user-inputted name
while (strLength > 30) { // Checks if not too long
System.out.println(strLength + " is too many characters, please try to keep it under 30");
inputPattern(); // Starts over again if too long
}
return player;
}
I have taken your method and modified it a bit.
It is non recursive solution.
Also in your code scanner resource was not closed at the end.
Iterative Solution
import java.util.Scanner;
public class SO66064473 {
public static void main(String[] args) {
inputPatternIterative();
}
public static String inputPatternIterative() {
Scanner scanner = new Scanner(System.in);
String player = "";
int strLength = Integer.MAX_VALUE;
while (strLength > 30) { // Checks if not too long
System.out.println("Please enter your name:");
while (!scanner.hasNext("[A-Za-z]+")) { //Checks if alphabetical value
System.out.println("Please stick to the alphabet!");
scanner.next();
}
player = scanner.next();
player += scanner.nextLine();
System.out.println("Thank you! Got " + player);
strLength = player.length(); // Saves the length of user-inputted name
if (strLength > 30)
System.out.println(strLength + " is too many characters, please try to keep it under 30");
}
scanner.close(); // Closing scanner resource after use.
return player;
}
}
Output :
Please enter your name:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Thank you! Got aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
70 is too many characters, please try to keep it under 30
Please enter your name:
aaaaaaaaaaaaaaaaaaaa12
Please stick to the alphabet!
coifvoifoivmrfvoirvoirovroijfoirjfoijroifjrwofjorwfouwrfoijwrofjworjfoiwrjf
Thank you! Got coifvoifoivmrfvoirvoirovroijfoirjfoijroifjrwofjorwfouwrfoijwrofjworjfoiwrjf
75 is too many characters, please try to keep it under 30
Please enter your name:
Danny
Thank you! Got Danny
EDIT : with the suggestion made by #Dev-vruper here is updated easy recursive code
Recursive Solution
import java.util.Scanner;
public class SO66064473 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
inputPatternRecursive(sc);
sc.close();
}
public static String inputPatternRecursive(Scanner sc) {
System.out.println("Please enter your name:");
String player = sc.nextLine();
if (!player.matches("[A-Za-z]+")) {
System.out.println("Please stick to the alphabet!");
inputPatternRecursive(sc);
} else {
System.out.println("Thank you! Got " + player);
if (player.length() > 30) {
System.out.println(player.length() + " is too many characters, please try to keep it under 30");
inputPatternRecursive(sc);
}
}
return player;
}
}
This should solve your problem in a pretty easy way:
public static String inputPattern(){
Scanner scanner = new Scanner(System.in);
String player = "";
int strLength;
boolean bShowedInstruction = true;
System.out.println("Please enter your name:");
while (true) {
if (!bShowedInstruction)
System.out.println("Please enter your name:");
bShowedInstruction = false;
player = scanner.next();
if (!player.matches("[A-Za-z]+")) {
System.out.println("Please stick to the alphabet!");
}
else if (player.length() > 30) {
System.out.println(player.length() + " is too many characters, please try to keep it under 30!");
}
else
break;
}
System.out.println("Thank you! Got " + player);
return player;
}
There's no need for a recursion. A simple while(true) loop does the trick.
It's a pretty clean solution keeping unnecessary scan-methods out of the game.
I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}
I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...
I wrote a simple if / else that is supposed to print the answer to the if else. but does not respond even with the correct input. I can't see what I'm missing.
import java.util.Scanner;
public class MarriageQuiz{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String marStat;
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.nextLine();
marStat = marStat.toUppercase();
if(marStat.equals('M')){
System.out.print("You are married");
}
else if(marStat.equals('S')){
System.out.print("You are single");
}
}
}
Your code is comparing a String object against a character literal, which I believe the JVM will box into a Character object. Well, these two objects don't belong to the same class, so "M".equals('M') will return false. To remedy this, use "M".equals("M").
change toUppercase() to toUpperCase() and marStat.equals('M') to marStat.equals("M") also marStat.equals('S') to marStat.equals("S")
import java.util.Scanner;
public class MarriageQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String marStat = "";
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.nextLine();
marStat = marStat.toUpperCase();
if (marStat.equals("M")) {
System.out.print("You are married");
} else if (marStat.equals("S")) {
System.out.print("You are single");
}
}
}
On the other hand, you can use Character type instead of 'String'. Rather using Character would be more accurate as you are dealing with only one character.
Scanner input = new Scanner(System.in);
Character marStat;
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.next().charAt(0);
marStat = Character.toUpperCase(marStat);
if (marStat.equals('M')) {
System.out.println("You are married");
} else if (marStat.equals('S')) {
System.out.println("You are single");
}
use ""
if(marStat.equals("M")){
System.out.print("You are married");
}
else if(marStat.equals("S")){
System.out.print("You are single");
}
As mentioned in a comment above, you are comparing a String object to an autoboxed Character object. One fix is obviously using double quotes, which Java will autobox to a String object your code will work.
A few tips to save a few lines of code: use String.equalsIgnoreCase() to save a line converting the incoming string to uppercase.
Next, consider using a constant for marital status:
public class MarriageQuiz{
private static final String STATUS_MARRIED = "M";
...
if (marStat.equalsIgnoreCase(STATUS_MARRIED)) {
...
That way you can use STATUS_MARRIED all over your code but can change it from, say, "M" to "Married" easily.
Here is my code that I have so far:
import java.util.Scanner;
public class Whatever{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int number = Integer.parseInt( keyboard.nextLine() );
int continueProgram = 0
while(continueProgram == 0)
{
if (number>= 0 && number <= 32767)
{ do this;
continueProgram++;
}else{
do this;
}
I have to use integer.parseInt for the rest of my code to work so I can't change that. Any ways to take only integers rather than letters? My code produces errors because if I input a letter, parseInt will produce red errors rather than output a string like "try again. input numbers please" or something like that.
You need to surround your parse.int with a try catch like this
int number = 0; // you need to initialize your variable first
while (true) {
try {
number = Integer.parseInt(keyboard.nextLine());
break; // this will escape the while loop
} catch (Exception e) {
System.out.println("That is not a number. Try again.");
}
}
Try this one :
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
if(keyboard.hasNextInt()) {
int number = keyboard.nextInt();
}else{
System.out.println("Not an integer number!");
keyboard.next();
}