I am new at Java and am currently trying to create a super super simple code just to test how to have a scanner input compared in an if statement to another number and then print out a response depending on the if. This is what I have and I'm getting an error on the if line and I'm getting this error:
The operator > is undefined for the argument type(s) String, int.
Any help would be great because once I figure this out I'm going to try to do some other things with it. Thanks!
import java.util.Scanner;
class damagecalc {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("How much damage did you do?");
String damage = input.nextLine();
if(damage > 50){
System.out.println("You have died!");
}else{
System.out.println("Your damage amount is:" + input);
}
}
}
You have
String damage = input.nextLine();
You want
int damage = input.nextInt();
And this
System.out.println("Your damage amount is:" + input);
Should be
System.out.println("Your damage amount is:" + damage);
You can't compare Strings using > operator. In Java you cannot define your own operator behaviour.
Instead of
String damage = input.nextLine();
use
Integer damage = input.nextInt();
If you're looking for a more robust solution, perhaps you could try something like:
public static int readInt(final String prompt){
final Scanner reader = new Scanner(System.in);
while(true){
System.out.println(prompt);
try{
return Integer.parseInt(reader.nextLine());
}catch(Exception ex){
System.err.println("Enter a valid integer: " + ex);
}
}
}
I'd probably suggest declaring your Scanner as a static class field if you plan on reading multiple user input (which presumably you do). You could invoke it like:
final int damage = readInt("How much damage did you do?");
System.out.println(damage > 50 ? "You have died!" : ("Your damage amount is: " + damage));
You cannot compare string with integer. Just parse it.
try {
if (Integer.parseInt(damage) > 50) {i
System.out.println("You have died!");
} else {
System.out.println("Your damage amount is:" + input);
}
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("You have entered a non integer number!");
}
Related
I'm looking to repeat a "game" if it is already satisfied in my case where user has to guess the random number. I can't understand where to to get back to the main game unless i have to create another "do - while" loop inside it and retype the game again in the section where it says: System.out.println("you have tried: " + count + " times. Would you like to play again? y/n"). Is there a way to just bring back to the actual guess loop rather than create another one?
Hopefully makes sense.
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
int guess;
int count;
count = 0;
int num;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
**System.out.println("you have tried: " + count + " times. Would you like to play again? y/n");**
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
}
The simplest solution would be to move the entire "guess loop" into a separate method. Then in the case when you want it to repeat, just call the method recursively.
If you want to reuse code you can make functions (or methods here, because we are inside a class). They can be used to encapsulate code and call it from anywhere to use it.
You can define a methods like that:
public static void methodName() {
// code go here
}
Then, you can call it from anywhere like that :
pass.methodName(); // It will execute the code inside methodName()
In reality, this is a lot more complex than that, you can give methods values and return others, change the scope of it to make it internal only or reachable by other classes. But I presume that you are a beginner so I keep it simple. I strongly recommend you to make a quick research about Object Oriented Programmation!
For your code, you can put the game's while loop in a method and call it at the beginning and each time the player wants to restart the game. Good luck with your game!
I manage to do this way. It seems working but one thing is letting me down at the very last when I key in "n" or other key than "y". Exception in thread "main" java.util.InputMismatchException. Is there a more softer way to finish it?
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void randomnum(){
Scanner scanner = new Scanner(System.in);
int guess;
int count;
count = 0;
int num;
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
System.out.println("you have tried: " + count + " times.");
String answer;
do{
System.out.println("Do you want to play again? y/n");
answer = scanner.next();
if (answer.equals("y")) {
System.out.println("let's play again");
randomnum();
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
}
else {
System.out.println("you are logout!");
break;
}
}while (answer.equals("Y"));
randomnum();
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
randomnum();
}
}
I am trying to prompt a user with the value they inputted and an error message if it's not an integer. When I try to prompt them, their input stays 0 when the input is a double or string.
//main method
public static void main(String[] args) {
int i = 0;
//instantiate new Scanner for user input
Scanner input = new Scanner(System.in);
//parse imput, display value
//and prompt user that their input is not a int
try {
inputNum = Integer.parseInt(input.next());
System.out.println("Value entered is " +
String.valueOf(inputNum));
} catch(NumberFormatException e) {
System.out.println("Value entered is " +
String.valueOf(inputNum));
System.out.println(String.valueOf(inputNum) + " is not an integer.");
}
}
}
If the input is a double or a string then parseInt would throw an exception and inputNum would not be assigned any new value. You could store input.next() in a string before passing it to parseInt - or you might be able to use e in the catch block to figure out the bad value
String s;
//parse imput, display value
//and prompt user that their input is not a int
try {
s = input.next();
System.out.println("Value entered is " + s);
inputNum = Integer.parseInt(s);
} catch(NumberFormatException e) {
System.out.println(s + " is not an integer.");
}
}
}
Well, it's a concept ('ask user for some input, keep asking if it is not valid') that you may want to do more than once, so it has no business being in main.
Give it its own method.
This method would take as input a 'prompt' and will return a number. The purpose is to ask the user (with that prompt) for a number, and to keep asking until they enter one.
You can use while() to loop code until a certain condition is met, or simply forever, using return to escape the loop and the entire 'ask the user for a number' method in one fell swoop.
I've modified the code to make it work according to your need:
public static void main(String[] args) {
//instantiate new Scanner for user input
Scanner input = new Scanner(System.in);
//parse imput, display value
//and prompt user that their input is not a int
String inputNum = input.next();
try {
System.out.println("Value entered is " +
Integer.parseInt(inputNum));
} catch (NumberFormatException e) {
System.out.println("Value entered is " +
inputNum);
System.out.println(inputNum + " is not an integer.");
}
}
Above is the standard approach to check if a String is an integer in java. If you want a simpler & powerful way you can leverage the Apache Commons library:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final String num = input.next();
// check to see if num is a number
if (NumberUtils.isCreatable(num)) {
System.out.println("Value entered is " + num);
} else {
System.out.println("Value entered is " + num);
System.out.println(num + " is not a number.");
}
}
Note that NumberUtils#isCreatable checks for a wide variety of number formats(integer, float, scientific...)
If you want something equivalent to Integer#parseInt, Long#parseLong, Float#parseFloat or Double#parseDouble. Use instead, NumberUtils#isParsable.
There is an another concise way to do it without throwing any exception, you can use hasNextInt() to pre-validate if the input value is a valid integer before hand, then use nextInt() to read an integer without parsing the string:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int inputNum;
if(scanner.hasNextInt()){
inputNum = scanner.nextInt();
System.out.println("Value entered is " + inputNum);
}else{
System.out.println(scanner.next() + " is not an integer.");
}
}
Asking a user to input calculator mode and operation.
then make a while loop after getting user input.
I have to do all operations once I receive the input I can't seem to get user input and calculate the code
import java.util.Scanner;
public class loopsProject {
public static void main(String[] args) {
System.out.println("Hello Codiva");
Scanner scnr = new Scanner(System.in);
String mode;
String operator;
double numOne;
double numTwo;
double numThree;
double numofdValues;
String result;
//asking user to enter mode
System.out.print("Enter the calculator mode: Standard/Scientific?");
mode = scnr.nextLine();
while (mode.equals("Standard")) {
System.out.println("Enter '+' for addition, '-' for subtractions, '*'
for multiplication, '/' for division");
operator = scnr.nextLine();
}
while (numOne != 0 && numTwo != 0 && numThree !=0)
if (operator.equals("+")) {
System.out.println("How many numbers would you like to add?");
numofdValues = scnr.nextDouble();
System.out.println("Enter + numofdValues + numbers");
numOne = scnr.nextDouble;
numTwo = scnr.nextDouble;
numThree = scnr.nextDouble;
result = numOne + numTwo + numThree;
System.out.println("Your added answer is:" + result);
}
if (operator.equals("-")) {
System.out.println("How many numbers would you like to subtract?");
numofdValues = scnr.nextDouble();
System.out.println("Enter + numofdValues + numbers");
num1 = scnr.nextDouble;
num2 = scnr.nextDouble;
num3 = scnr.nextDouble;
result = numOne - numTwo - numThree;
System.out.println("Your subtracted answer is:" + result);
}
if (operator.equals("*"))
System.our.println("Your multiplied answer is:" + result);
if (operator.equals("/"))
if (operator.equals("invalid")) {
System.out.println("Your imput is invalid, please try again");
}
You mentioned you're having trouble with
setting up the user input for the entire problem
Hopefully this will provide you with the structure to move forward. You have two while loops, but you need one outside to control the looping of the user choosing modes or quitting.
public class loopsProject {
public static void main(String[] args) {
System.out.println("Hello Codiva");
//Your variables here
//asking user to enter mode
System.out.print("Enter the calculator mode: Standard/Scientific?");
mode = scnr.nextLine();
//This loop controls the mode, user will keep on entering or they can quit
while (!mode.equals("Quit")) {
if (mode.equals("Standard")) {
//your Standard logic
}
else if (mode.equals("Scientific")) {
//your Scientific logic
}
else {
//Handle however you want or quit
break;
}
//Ask user for input again
System.out.print("Enter the calculator mode: Standard/Scientific?");
mode = scnr.nextLine();
}
}
}
if operation is invalid reprompt the user again
For the case when operations are invalid, what you can do is just tell the user the operation is invalid and continue to skip asking them for input. That way it retains the mode and will restart the logic in the next loop. This would go inside your Standard logic or Scientific logic, each time you need to validate the user's input.
if (...) { //your checks for user input invalid operation here
System.out.println("Invalid operation, please retry.");
continue;
}
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
If a user places anything else under Enter your age other than a number, how do I make it say that the input is not correct and ask again?
You can get the line provided by the user, then parse it using Integer.parseInt(String) in a do/while loop as next:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
A better approach that avoids catching an Exception based on https://stackoverflow.com/a/3059367/1997376.
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
No need to declare a variable scanner so often, simply once
care with nextLine(); for strings; presents problems with blanks, advise a .next();
use do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
use blocks try{ .. }catch(Exception){..}
to catch exceptions mismatch-input-type exception is when the input is not what I expected in the example enter a letter when a number expected
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);
I'm making a simple coin toss game, and I wrote several methods to call and make my main class short and simple. After the game is played once, the first If/Else statement to ask users for input is jumping right to the Else statement without prompting for input.
package cointoss;
import java.util.Random;
import java.util.Scanner;
public class Game {
int money;
int result;
int bet;
Random rn = new Random();
Scanner in = new Scanner(System.in);
String playerPick;
String aResult;
public void setMoney(int a)
{
money = a;
}
public int getMoney()
{
return money;
}
public void getBet()
{
System.out.println("How much would you like to bet?");
bet = in.nextInt();
do{
if(bet > money)
{
System.out.println("You cannot bet more than you have!");
System.out.println("You have bet " + (bet - money) + " too many coins.");
continue;
}
else
System.out.println("You have bet " + bet + " coins.");
}
while(bet > money);
}
public void getInput()
{
System.out.println("Pick Heads or Tails");
playerPick = in.nextLine();
playerPick.toLowerCase();
if(playerPick.contains("heads"))
playerPick ="heads";
else if(playerPick.contains("tails"))
playerPick ="tails";
else
System.out.println("Invalid Selection");
}
public void flipCoin()
{
result = rn.nextInt(2);
if(result == 0)
{
aResult = "heads";
}
else
aResult = "tails";
}
public void checkResult()
{
if(playerPick.equals(aResult))
{
System.out.println("You have won!");
money += bet;
System.out.println("You now have " + money + " coins");
}
else{
System.out.println("You have lost!");
money -= bet;
System.out.println("You now have " + money + " coins");
}
}
}
My Tester Class:
package cointoss;
public class GameTest {
public static void main(String[] args)
{
Game coinToss = new Game();
coinToss.setMoney(100);
while(coinToss.getMoney() > 0)
{
coinToss.getInput();
coinToss.getBet();
coinToss.flipCoin();
coinToss.checkResult();
}
}
}
The method toLowerCase() does not change the contents of the string; String is an immutable class in Java. The toLowerCase() method returns the result. You need to change
playerPick.toLowerCase();
to
playerPick = playerPick.toLowerCase();
Your problem is that you are not reinitializing "in" as a new Scanner every time you run the tester loop. The single scanner reads a line of input and accepts that as the full answer, without acknowledging that there could be further input.
The problem is that when the user enters a line, the input buffer will contain characters followed by a "newline" (end-of-line) character. When you use nextInt, the Scanner will find and skip over an integer. But it won't skip over the end-of-line. So when you next call nextLine in getInput(), it will then find what's left of the previous line, i.e. an empty string, and return that. Some things you'll need to do:
(1) In getBet, add in.nextLine() at the end of the method, to skip past the end-of-line. nextLine will return a string but you can ignore it. See also Scanner issue when using nextLine after nextXXX
(2) getInput needs to have a loop so that if the user enters an invalid input, you go back and ask him to enter a valid string. Otherwise, it will display "Invalid Selection" but then ask for a bet, which isn't what you want.
(3) See the other answers with regard to toLowerCase.
When you use
playerPick.toLowerCase();
It does nothing because the value is not being assigned to anything. In order to change a value of an object you must assign a value to it, as below:
playerPick = Pick.toLowerCase();
This assigns the value, rather than calling an empty method
Hope this helps :)