java.lang.NullPointerException form user input - java

Hey guys I'm trying to create a loop until a correct character choice is entered by the user. When I enter a wrong choice I get the error java.lang.NullPointerException. It might be with the way I'm inputing but I don't want to change that if I don't have to. choice is a private member of the class.
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.findInLine(".").charAt(0);
}
return choice;
}//end wf

Change the function as below (I have tested this code):
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
char choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.next().charAt(0);
}
return choice;
}//end wf

Check input.findInLine(".") to see if it null. If you don't have the expected input, it won't return anything..

change your code like below
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
if(input.findInLine(".") !=null){
choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.findInLine(".").charAt(0);
}
}
return choice;
}//end wf

Related

Trouble appropriately constructing do while loops with correct conditions to run

I am struggling to correctly loop the code I have written to convert integers to roman numerals.
I have tried implementing a do while loop to run the code starting at "please enter an integer" and ending after my switch statement with the while part being: while(case "y" || "Y" == true )
Any help would be greatly appreciated. I have been searching through previous posts on stack overflow for a couple hours now and haven't been able to find anything that helps.
public class project8
{
/**
* Constructor for objects of class Project4
*/
public static void main(String[] args) {
System.out.println("Welcome to my integer Roman numeral conversion program");
System.out.println("------------------------------------------------------");
System.out.println(" ");
Scanner in = new Scanner (System.in);
System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
int input = in.nextInt();
if (input < 0 || input > 3999){
System.out.println("Sorry, this number is outside the range.");
System.out.println("Do you want to try again? Press Y for yes and N for no: ");
String userInput = in.next();
switch (userInput) {
case "N":
case "n":
System.exit(0);
break;
case "Y":
case "y":
break;
}
}
else if (input > 0 && input < 3999);
{ System.out.println(Conversion.Convert(input));
}
}
}
1) Your if - else if conditions are redundant. You can use a simple if - else as input can only be in that range or not. else if makes only sence if you had two or more ranges to check, e.g.
if(input > 0 && input < 3999){
...
}
else if (input > 4000 && input < 8000){
...
}
else {
...
}
2) You don't need a switch block instead use the user input in your while condition as you want to continue looping when user input is Y/y, i.e while(userChoice.equals("Y"))
3) Use a do - while loop as you want that your application to run at least on time
public static void main(String[] args) {
System.out.println("Welcome to my integer Roman numeral conversion program");
System.out.println("------------------------------------------------------");
System.out.println(" ");
Scanner in = new Scanner (System.in);
String choice;
do{
System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
int input = in.nextInt();
if(input > 0 && input < 3999){
System.out.println(Conversion.Convert(input));
}
else{
System.out.println("Sorry, this number is outside the range.");
}
System.out.println("Do you want to try again? Press Y for yes and N for no: ");
choice = in.next();
}while(choice.equals("Y") || choice.equals("y"));
}

While loop NoSuchElementException integer input java

I'm having some trouble with a menu program I am writing for my java class. After one program is run, when the program goes to do a second loop it throws a NoSuchElementException on the line where it is supposed to take the user's input for the next program they want to run. I'm assuming it has something to do with the scanner getting messed up but I can't find the issue. Anyone have any ideas?
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String pin;
int selection = 0;
boolean valid = false;
do {
System.out.print("Please enter the password: ");
pin = console.nextLine();
valid = checkPassword(pin);
} while (!valid);
while (selection != 4 && valid == true) {
System.out.printf("%nPlease select a number from the menu below %n1: Wage "
+ "Calculator 2: Tip Calculator 3: Grocery Discount 4: Exit %n");
selection = console.nextInt();
if (selection == 1) {
calc_wages();
} else if (selection == 2) {
calc_tip();
} else if (selection == 3) {
System.out.print("We haven't gotten this far yet");
} else if (selection == 4){
System.out.print("Thank you for using the program.");
break;
} else {
System.out.print("There is no option for what you entered. Try again");
}
selection = 0;
}
}//main
Your code so far is fine.
From what you're saying the problem starts after the user makes a selection.
In calc_wages() and/or calc_tip() it's possible that you use another Scanner object to get the user's input.
This is a source of problems.
Declare 1 Scanner object at the class level and use it throughout you code and close it only when it is no longer needed.

java (eclipse) code for rock paper scissors, choosing an input that is simple, and generating an output of rock paper or scissors

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

User input to repeat program in Java

I am writing a simple guessing game program where the user will input a number to try and guess a randomly generated number.
If they get the number right I want to give them the option to play again.
Here is my code:
public class GuessingGame {
private Random num = new Random();
private int answer = num.nextInt(10);
private int guess;
private String playAgain;
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
}while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
if(playAgain == "Y" || playAgain == "y"){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
}
}
}
The game plays through but when the user is prompted to play again nothing happens?
Any suggestions?
Here is the completed code, fully working and tested... without using recursion.. and everything fixed.
public static void main(String[] args)
{
String playAgain = "";
Scanner scan = new Scanner(System.in);
do
{
ClassName.inputGuess();
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = scan.nextLine();
}
while(playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for playing!");
}
public void inputGuess()
{
Random num = new Random();
int answer = num.nextInt(10)+1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
do
{
if (guess < 1 || guess > 10)
{
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}
else
if (guess > answer)
{
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}
else
if (guess < answer)
{
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
input.nextLine();
}
while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
}
Do the following and your code will work :
Replace all input.nextInt(); with Integer.parseInt(input.nextLine());
Replace (playAgain == "Y" || playAgain == "y") with (playAgain.equalsIgnoreCase("Y"))
Initialise answer inside inputGuess() in starting instead.
Replace the body of if(playAgain.equalIgnoreCase("Y")) with inputGuess();
When you enter integer value through console it also contain a \n(next line) in it. But when you use nextInt(), it doesn't read this \n, but then when you tried to get next line with input.nextLine(), it looks for \n(next line) which is already there from integer entry and having nothing after that. Code look for "Y" or "y" and breaks because it doesn't found any of them.
That is why Integer.parseInt(input.nextLine()); works here
Here is the code:
private Random num = new Random();
private int answer = num.nextInt(10) +1;
private int guess;
private String playAgain;
Scanner input = new Scanner(System.in);
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
if(guess == answer) {
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
}
}while (!playAgain.equals("Y") && !playAgain.equals("y"));
}
You just need to introduce the winning/losing logic inside the while, and the condition will be the ending/continue flag.
Another thing is always remember when comparing strings to use the equals method, since the == will compare the object reference and not the String value, in some cases == will return true for equal string since how JVM stores the Strings, but to be sure always use equals.
Try something like this:
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
playAgain = "Y";
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
if(guess == answer)
{
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or N to quit: ");
input.nextLine();
playAgain = input.next();
answer = num.nextInt(10);
guess = -1;
if(!playAgain.equalsIgnoreCase("N"))
{
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
}
}
}while (!playAgain.equalsIgnoreCase("N"));
}
You need your code for checking if they want to play again inside the loop. This way you wait until they have guessed the number correctly then ask if they want to play again. If they do you restart the process if they don't you exit the loop.
Some of the solution I see above aren't correct. The random number, you need to add 1 to get between 1 and 10, also you need to compare with equals. I use case insensitive here.
The following code works as you need it.
import java.util.Random;
import java.util.Scanner;
public class Test2 {
private static Random num = new Random();
private static int answer = 0;
private static int guess;
private static String playAgain;
public static void main(String[] args) {
inputGuess();
}
// Guess Method.
public static void inputGuess(){
// create answer.
answer = 1+ num.nextInt(10);
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
}while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
if( playAgain.equalsIgnoreCase("Y") ){
inputGuess();
}
}
}
By now, you would have already guessed the right way to do it. Here is how I will approach it
public class Test {
public static void main (String...a) {
inputGuess();
}
public static void inputGuess() {
Scanner input = new Scanner(System.in);
String playAgain = "Y";
int guess;
Random ran = new Random();
int answer = ran.nextInt(10) + 1;
while (playAgain.equalsIgnoreCase("Y")) {
System.out.println("Enter a number between 1 and 10 as your first guess: " + answer);
guess = input.nextInt();
do {
if (guess < 1 || guess > 10) {
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
} else if (guess > answer) {
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
} else if (guess < answer) {
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
} while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
input.nextLine();
playAgain = input.nextLine();
answer = ran.nextInt(10) + 1
}
}
}
This code can serve your purpose...
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
private Random num = new Random();
private int answer ;
private int guess;
private String playAgain;
public void inputGuess()
{
answer = num.nextInt(11);
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do {
if (guess < 1 || guess > 10) {
System.out
.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
} else if (guess > answer) {
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
} else if (guess < answer) {
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
} while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
do
{
playAgain = input.nextLine();
}while(playAgain.length()<1);
if (playAgain.trim().equalsIgnoreCase("y"))
{
inputGuess();
}
else
{
System.out.println("Good Bye!!!");
}
}
public static void main(String[] args) {
new GuessingGame().inputGuess();
}
}
one issue :
Do not compare the content of two strings by == which just
you should use equals()
Imagine the right answer is one in this case
Follow this as your blue print sample
int answer = 0;
String yes = "";
Scanner input = new Scanner(System.in);
do{
do{
System.out.println("Enter your number");
answer = input.nextInt();
} while ( answer != 1);
System.out.println("Would you like to play again?");
yes = input.next();
} while ( yes.equalsIgnoreCase("yes"));
output:

Infinite looping; do not understand how

In the code below, when I input anything other than an integer value the code does not ask for my input again and just loops the string outputs infinitely. A little help...
int choice = 0;
while(choice == 0)
{
try
{
System.out.println("Start by typing the choice number from above and hitting enter: ");
choice = input.nextInt();
}
catch(Exception e)
{
}
if ((choice == 1) || (choice == 2) || (choice == 3))
{
break;
}
else
{
System.out.println("Invalid choice number. Please carefully type correct option.");
choice = 0;
}
}
When you input a non-integer it will not be consumed. You need to scan past it. This can be done by, for example, adding a input.nextLine() statement to your catch block. This will consume the invalid input and allow your program to read new data.
This will solve your problem:
catch(Exception e)
{
input.nextLine(); // Consume the invalid line
System.out.println("Invalid choice number. Please carefully type correct option.");
}
You could also read the line as a string and try to parse it as a number using Scanner.nextLine and Integer.parseInt, but I prefer using nextInt for integers. It makes the purpose of the code more clear (in my opinion).
When nextInt is used and the next input is not an int, it will throw an exception but not consume the data, i.e. the next call will return immediately because the data is still present.
You can fix this by calling the skip method with a pattern like [^0-9]* to skip all invalid input. Then an input like "aaa3" would work. If you want to ignore everything, use .* as pattern.
The trouble is that you are not consuming the remaining data in the stream. I solved it with the following code, although you will want to document you code better before you use it in a program:
int choice = 0;
while(choice == 0)
{
try
{
System.out.print("Start by typing the choice number from above and hitting enter: ");
choice = input.nextInt();
}
catch(Exception e)
{
input.next();
System.out.println("Invalid choice number. Please carefully type correct option.");
}
if ((choice == 1) || (choice == 2) || (choice == 3))
{
break;
}
choice = 0;
}
You can simplify and reduce your code as follows:
int choice;
System.out.println("Start by typing the choice number from above and hitting enter: ");
while(true)
{
try {
choice = input.nextInt();
if ((choice == 1) || (choice == 2) || (choice == 3))
break;
} catch(InputMismatchException e) { // handle only the specific exception
input.nextLine(); // clear the input
}
System.out.println("Invalid choice number. Please carefully type correct option.");
}
Are you using Scanner(system.in); from the import java.util.Scanner; package?
Try adding input.nextLine(); in the catch to clear the value to stop the infinite loop.
public static void main(String[] args) {
int choice = 0;
Scanner input = new Scanner(System.in);
while(choice == 0)
{
try
{
System.out.println("Start by typing the choice number from above and hitting enter: ");
choice = input.nextInt();
}
catch(Exception e)
{
input.nextLine();
System.out.println("Invalid choice number. Please carefully type correct option.");
}
if ((choice == 1) || (choice == 2) || (choice == 3))
{
break;
}
else
{
System.out.println("Invalid choice number. Please carefully type correct option.");
choice = 0;
}
}
}
Looks like in the line choice = input.nextInt();
choice value is always 0. Print choice soon after that.
Also for non integer value add a condition to break from the loop.

Categories

Resources