How to modify the code below to become the user only can enter 2 times wrong PIN? After 2 times wrong PIN, the program will auto exit.
String user = "Melissa";
int pin = 123456;
int pin2;
// Prompt the user for input
do
{
String pin2String = JOptionPane.showInputDialog("Enter PIN");
pin2 = Integer.parseInt(pin2String);
}while(pin2 != pin);
// Display
JOptionPane.showMessageDialog(null, "User: "+ user);
You will just need to add a counter, to count how many times the user has attempted to enter a pin, then verify the condition in your while loop's condition.
For example:
String user = "Melissa";
int pin = 123456;
int pin2;
int MAX_INCORRECT_PIN_THRESHOLD = 2;
int attempts = 0;
// Prompt the user for input
do {
String pin2String = JOptionPane.showInputDialog("Enter PIN");
pin2 = Integer.parseInt(pin2String);
attempts++;
} while(pin2 != pin && attempts < MAX_INCORRECT_PIN_THRESHOLD);
if (pin2 == pin) {
// Display
JOptionPane.showMessageDialog(null, "User: "+ user);
}
int counter = 0;
do
{ if(counter++ >= 2){ break;}
String pin2String = JOptionPane.showInputDialog("Enter PIN");
pin2 = Integer.parseInt(pin2String);
}while(pin2 != pin);
Drop a simple counter in there which terminates the loop after two iterations, and then check to see if the PIN was invalid after leaving the loop:
String user = "Melissa";
int pin = 123456;
int pin2;
int count = 0;
// Prompt the user for input
do
{
String pin2String = JOptionPane.showInputDialog("Enter PIN");
pin2 = Integer.parseInt(pin2String);
}while(pin2 != pin && count++ < 2);
if(pin2 != pin)
{
// Kansas is going bye-bye - call exit logic
}
// Display
JOptionPane.showMessageDialog(null, "User: "+ user);
Try a for loop where it only loops twice. That would probably be easier.
VALID:
for(int i= 0; i < 2; i++){
if(pin==pin2){
//Valid login...
break VALID;
}else if(i == 1){
System.exit(0);
}
}
Related
I want to apply this function in java. Inside while loop, you need to input number of repetition you want to input a number. if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again. This code is not finish yet. I hope u understand what i want to achive. thank you
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
}
Let's use a temp variable to store the value of previous input. If new input is same as previous input, the iterator i should not increase, so we use i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one. I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
See the code for that:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}
I am working on a rock paper scissors homework assignment for my java class. I am done with the program and I compiled it successfully. I ran the file and it looked like it was working. It gives me the menu and I choose a variable, R for example, and when I press enter it doesn't do anything but go to the next line. I press enter again and it gives me an index out of bounds error which I assume is because the second time it didn't have a variable to use. How do I get the program to move forward? The program is supposed to play five times then return a winner. Thanks in advance.This image is what I get when I run the program and press enter twice
package Rock;
import java.util.Scanner;
public class RPSG {
public static void main(String[] args) {
String[] computerHandArray = {"R","P","S"};
String computerHand ="", thisWinner="", theFinalWinner="";
int index=0;
int timesIWon=0;
int timesComputerWon=0;
Scanner in = new Scanner(System.in);
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\nEnter Your Hand (R, P, or S): ");
for (int i=0; i<5; i++) {
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
}
else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
}
}
if(timesIWon == timesComputerWon)
theFinalWinner = "TIE";
else if(timesIWon > timesComputerWon)
theFinalWinner = "ME";
else if(timesComputerWon > timesIWon)
theFinalWinner = "COMPUTER";
System.out.println("I won :" + timesIWon);
System.out.println("I won :" + timesComputerWon);
System.out.println("The Final Winner after 5 games is:" +theFinalWinner);
}
private static String theWinnerofOneGame(String myHand, String computerHand){
String theWinner = "Tie";
if(myHand.equals(computerHand)) {
theWinner = "Tie";
}
else if(myHand.equals("R")) {
if (computerHand.equals("P")) {
theWinner = "COMPUTER";
}
}
else if(computerHand.equals("S")) {
theWinner = "ME";
}
else if(myHand.equals("P")) {
if (computerHand.equals("R")) {
theWinner = "ME";
}
else if(computerHand.equals("S")) {
theWinner = "COMPUTER";
}
}
else if(myHand.equals("S")) {
if (computerHand.equals("R")) {
theWinner = "COMPUTER";
}
else if(computerHand.equals("P")) {
theWinner = "ME";
}
}
return theWinner;
}
}
You print the prompt for input only once, i.e. before the for loop. Now when you enter your first input, the content of the loop will be executed. Because you don't print anything inside the loop, there is no prompt for the next round. After you press enter a second time, the in.nextLine() returns an empty string and subsequently, the substring method throws the exception.
You should probably do something like this (note the marked lines):
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\n");
for (int i=0; i<5; i++) {
> System.out.println("Enter Your Hand (R, P, or S): ");
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
> System.out.println("You won.");
} else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
> System.out.println("The computer won.");
}
}
And even better, check if the input of the user is valid before computing the substring.
Hello all I am trying to validate a set of inputs from a user, where it does not accept blanks, letter, letter with numbers, and numbers out of the range 0=100.
It goes fine except but when I input greater than 100, for example 150, it will catch and tell you to try again but when a letter is typed on the second prompt, it fails. And it'll only fail if the sequence of input is int is greater than 100 is input and the second input is a letter. I have a feeling it is the logic but I cant figure out exactly on which part.
It errors right on the line when arrayInt is declared (3rd set of while loop from validateUserInput method)
public static void main(String[] args) {
// Ask for user input
Scanner input = new Scanner(System.in);
//declare an array with index of 5
int array[] = new int[5];
//loop to prompt user to input 5 test scores, each of which are stored in array
for (int i = 0; i < array.length; i++){
System.out.println("Enter score " + (i+1) + ": ");
//array[i] = Integer.parseInt(input.nextLine());
String arrayInput = input.nextLine();
arrayInput = validateUserInput (arrayInput);
array[i] = Integer.parseInt(arrayInput);
}
//call method to display test scores
displayTestScores(array, array);
//exit out
System.out.println("Press any key to exit...");
input.nextLine();
System.exit(0);
}
//validate user input
public static String validateUserInput ( String arrayInput){
//variable to itirate through the string
int counter = 0;
//variable to index
int arrayInputLength = arrayInput.length();
//assign scanner for user input
Scanner input = new Scanner(System.in);
//loop to check if blank
while (arrayInputLength == 0){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
//loop to check if user inputs numbers mixed with letters, iterate using counter
while (arrayInputLength > counter){
if (!Character.isDigit(arrayInput.charAt(counter))){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
counter = 0;
}
else{
counter ++;
}
while (arrayInputLength == 0){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
}
//loop to check while there is something inputted, make sure only between 0 and 100
while (arrayInputLength > 0 ){
int arrayInt = Integer.parseInt (arrayInput);
if (arrayInt > 0 && arrayInt <= 100){
return arrayInput;
}
else {
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
while (arrayInputLength == 0 ){
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
arrayInputLength = arrayInput.length();
}
}
return arrayInput;
}
validateUserInput has too much responsibility (and duplicate code). It's trying to validate the user input and also get new input. But that new input might not be valid either (which is causing the error in your question).
Separate getting user input from validating the input. Consider changing
public static String validateUserInput ( String arrayInput)
to
public static boolean isValidInput(String arrayInput)
It only checks to see if the input is valid. It does not prompt the user for new input.
Then within the main for loop, keep prompting the user for input until it is valid.
for(...) {
....
while (!isValidInput(arrayInput)) {
System.out.println("that is not an integer X such that: 0 <= x <= 100, try again");
arrayInput = input.nextLine();
}
....
}
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.*;
public class GuessingGameGUI {
public static void main(String[] args) {
Random rand = new Random();
int value = rand.nextInt(32) + 1;
int guesses = 0, LowGuess = 0, HighGuess = 0; //ADDED LowGuess AND HighGuess
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
while (win == false) {
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
guesses++;
if (guess == value) {
win = true;
} else if (guess < value) {
JOptionPane.showInputDialog("Your guess is lower than random number");
LowGuess++; //COUNTER TO KEEP TRACK OF LOW GUESSES
} else if (guess > value) {
JOptionPane.showInputDialog("Your guess is higher than random number");
HighGuess++; //COUNTER TO KEEP TRACK OF HIGH GUESSES
}
}
JOptionPane.showMessageDialog(null, "You win! You are the worst guesser in history!");
JOptionPane.showMessageDialog(null, "The number was: " + value);
// ADDED FROM HERE (GUESSES)
JOptionPane.showMessageDialog(null, "Number of Guesses:" + guesses);
for (int x = 1; x <= guesses; x++) {
for (int a = 1; a <= guesses; a++) {
if (a == guesses) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // TO HERE FOR AMOUNT OF GUESSES
// I ADDED FROM HERE (LOW)
JOptionPane.showMessageDialog(null, "Smaller Guesses:" + LowGuess);
for (int Low_i = 1; Low_i <= LowGuess; Low_i++) {
for (int Low_e = 1; Low_e <= LowGuess; Low_e++) {
if (Low_e == LowGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // Then TO HERE FOR LOW
// I ADDED FROM HERE (HIGH)
JOptionPane.showMessageDialog(null, "Largest Guesses:" + HighGuess);
for (int High_i = 1; High_i <= HighGuess; High_i++) {
for (int High_e = 1; High_e <= HighGuess; High_e++) {
if (High_e == HighGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} //FINALLY TO HERE FOR HIGH
}
}
// when I run my program the message box pops up when i enter my guessing number, however it seems to stop and nothing else pops up to let me know if i guessed to high or to low.
Take these lines, for example:
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
A prompt displays that asks you to "Guess a number between 1 and 32". So you enter the number, and then execution stops because your Scanner is awaiting your input. You need to completely remove your Scanner so you won't have these frequent interruptions.
The showInputDialog method of JOptionPane returns a String, as shown in the example from the Javadocs:
Show a dialog asking the user to type in a String:
String inputValue = JOptionPane.showInputDialog("Please input a value");
As is, you're throwing away the value returned from the method when you should instead be assigning it to your variables. In order to assign the returned value to your int variable guess, use Integer.parseInt:
guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number between 1 and 32: "));
JOptionPane.showInputDialog returns String than you have to convert that String to int using Parse methods, every time you receive input.
String input = JOptionPane.showInputDialog();
Int number = Integer.parseInt(input);
I need help getting this program to loop within its self after it runs the first time. It asks the user if they want to encode, decode or exit. The program runs, it encodes/decodes like it should. I now need to get another Pane to pop up and ask if they user wants to code another input then loop through everything it ran through the first time. I have the pane to where it asks the user if they want to run again but cant get it to loop through the coder.
public void encoding()
{
int userChoice;
int i;
int p=1;
int counter=0;
counter++;
String fin = "";
String input = JOptionPane.showInputDialog("Want to ENCODE, DECODE or EXIT? Press
1, 2, or 3");
userChoice = Integer.parseInt(input);
if (userChoice == 1 )
{
String encode = JOptionPane.showInputDialog(null, "What Are We
Encoding? ");
char[] array = encode.toCharArray();
for(i=0; i <array.length; i++)
{
char Ecode = encode.charAt(i);
Ecode--;
Ecode--;
fin += Character.toString(Ecode);
}
JOptionPane.showMessageDialog(null, fin);
}
else if (userChoice == 2)
{
String decode =JOptionPane.showInputDialog(null, "What Are We
Decoding? ");
char[] array1 = decode.toCharArray();
for(i=0; i < array1.length; i++)
{
char Dcode = decode.charAt(i);
Dcode++;
Dcode++;
fin += Character.toString(Dcode);
}
JOptionPane.showMessageDialog(null,fin);
String again = JOptionPane.showInputDialog("Want to code another?
Press 1 or 2");
int aChoice = Integer.parseInt(again);
if (aChoice==1)
{
System.out.print("bob");
}
else
{
JOptionPane.showMessageDialog(null, "Good Bye");
System.exit(0);
}
}
Wrap you code starting int i; and include if-else block in a do-while loop as:
do{
int i;
int p=1;
.....
.....
}while(userChoice != 3);
Please Note: This will not let you exit, until you enter 3.
You may want to add another block to handle th conditions when user enters anything other that 1,2 or 3.
Alternatively, you can do like:
do{
String input = JOptionPane.showInputDialog...
.....
.....
}while(userChoice == 1 || userChoice == 2);
This will exit the loop for any choice other than 1 or 2.
EDIT: Please find below the fixed code:
public void encoding(){
int userChoice, i;
do{
String fin = "";
String input = JOptionPane
.showInputDialog("Want to ENCODE, DECODE or EXIT? Press 1, 2, or 3");
userChoice = Integer.parseInt(input);
if (userChoice == 1 ){
String encode = JOptionPane.showInputDialog(null, "What Are We Encoding?");
char[] array = encode.toCharArray();
for(i=0; i <array.length; i++){
char Ecode = encode.charAt(i);
Ecode--;
Ecode--;
fin += Character.toString(Ecode);
}
JOptionPane.showMessageDialog(null, fin);
} else if (userChoice == 2) {
String decode =JOptionPane.showInputDialog(null, "What Are We Dencoding?");
char[] array1 = decode.toCharArray();
for(i=0; i < array1.length; i++){
char Dcode = decode.charAt(i);
Dcode++;
Dcode++;
fin += Character.toString(Dcode);
}
JOptionPane.showMessageDialog(null, fin);
}
}while(userChoice != 3);
JOptionPane.showMessageDialog(null, "Good Bye");
System.exit(0);
}
You could enclose the JOptionPane inputs + the full corresponding if block in a while loop:
int userChoice = 0;
while (userChoice != 3) {
int i;
int p=1;
// the rest of the params here
String input = JOptionPane.showInputDialog(...)
...
}