Getting a program to loop within its self - java

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(...)
...
}

Related

Trying to iterate certain interval using "do -while"

Hi this code is part of my code that is supposed to check if the number string is palindrome.
I want to iterate from top to botoom of my code but it doesn't iterate at all , what is wrong ??
I searched in youtube and realized this kind of things , people usually use do-while loop so I was trying to follow the instruction but it doesn't give me what I want .
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
Here is my full code.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
char choice;
long firstNum = 0;
firstNum = getLong(" Enter the first number: ", '-');
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
public static long getLong(String prompt, char exitChar)
{
long retVal = 0;
boolean validInput = false;
String userInput = "";
Scanner kbd = new Scanner(System.in);
while (!validInput) {
System.out.println(prompt);
try
{
userInput = kbd.nextLine().trim();
if (userInput.length() > 0 && userInput.charAt(0) == exitChar)
{
System.out.println("Ending the program at the user's request");
System.exit(1);
}
retVal = Long.parseLong(userInput);
validInput = true;
}
catch (Exception ex)
{
System.out.println("That is not numeric. Try again or press " + exitChar + "to Quit");
}
}
return retVal;
}
}
Change this:
String str = kbd.nextLine().trim();
to this
String str = kbd.next();
When read choice, using nextLine() intead of next():
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.nextLine().charAt(0); // <---here, change to nextLine()
}while(choice=='y'||choice =='Y');
}
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. so in next loop it reads last input line that will be empty string.

Program won't continue when pressing enter. How do I fix this error?

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.

Caesar Cipher in Java - printing blank line

I'm currently trying to write a Caesar Cipher in Java with key 18.
The code I have so far is as follows, but for some reason I cannot work out, it isn't working.
import java.util.Objects;
import java.util.Scanner;
class MainApplication {
private static final Scanner input = new Scanner(System.in);
private static String CryptMessage(int key, String message) {
StringBuilder temp = new StringBuilder();
for (int i = 0; i == message.length(); i++) {
if (Character.isLetter(message.charAt(i))) {
int num = (int) message.charAt(i);
num = num + key;
if (Character.isUpperCase(message.charAt(i))) {
if (num > (int) ('Z')) {
num = num - 26;
} else if (num < (int) ('A')) {
num = num + 26;
}
}
if (Character.isLowerCase(message.charAt(i))) {
if (num > (int) ('z')) {
num = num - 26;
} else if (num < (int) ('a')) {
num = num + 26;
}
}
temp.append((char) num);
} else {
temp.append(message.charAt(i));
}
}
message = temp.toString();
return message;
}
private static void encrypt(){
int key = 18;
System.out.println("Please enter a message to encrypt: ");
String message = input.nextLine();
System.out.println(CryptMessage(key, message));
}
private static void decrypt(){
int key = -18;
System.out.println("Please enter a message to decrypt: ");
String message = input.nextLine();
System.out.println(CryptMessage(key, message));
}
public static void main(String args[]){
System.out.println("Message Encryption System 3.0");
System.out.println("Please select an option:");
System.out.println("[1] - Encrypt Message");
System.out.println("[2] - Decrypt Message");
String opt = input.nextLine();
if(Objects.equals(opt, "1")){
encrypt();
}
else if(Objects.equals(opt, "2")){
decrypt();
}
else{
System.out.println("Invalid input.");
}
}
}
The program runs, however, it prints a blank line where the encrypted (or decrypted) message should be.
The loop condition i == message.length() should be i < message.length().
The condition in a for loop determines when to continue to the next iteration. Your condition is false on the first iteration and the loop terminates immediately (after the first iteration).
This is a problem that can be solved with a debugger. If you go through your code one line at a time it is easier to catch the fact that the loop conditon nimrodm pointed out doesn't execute the way you expect it to. In addition you can check the values of the variables during execution and make sure they are correct at each step.

Program doesn't prompt for string input but does for other data types

In this program i needed the user to input yes / no to be set in another array class. But the string input doesnt work. I tried it with an integer and it worked but not with a string.
package airliner.boarding.system;
import java.util.Scanner;
public class BoardPlane {
private boolean firstClass[];
private boolean economyClass[];
private static Scanner input ;
public BoardPlane(){
firstClass = new boolean[5];
economyClass = new boolean[5];
input = new Scanner(System.in);
}
public void setSeat(int seatClass){
if(seatClass == 1){
fillFirstClass();
}else if(seatClass == 2){
fillEconomyClass();
}
}
private void fillEconomyClass(){
for(int counter = 0; counter < economyClass.length; counter++){
if(economyClass[counter] == false){
economyClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the economy class");
break;
}else if(counter == 4){
System.out.println("Economy class is filled. is it okay to place you in first class? YES/NO: ");
String choice = input.nextLine();
choice = choice.toUpperCase();
if(choice.equals("YES")){
switchSeats(2);
}else{
System.out.println("Next flight leaves in three hours.");
}
}
}
}
private void fillFirstClass(){
for(int counter = 0; counter < firstClass.length; counter++){
if(firstClass[counter] == false){
firstClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the first class");
break;
}else if(counter == 4 ){
System.out.println("First class is filled. is it okay to place you in economy class? YES/NO:");
String choice = input.nextLine();
choice = choice.toUpperCase();
if(choice.equals("YES")){
switchSeats(1);
}else{
System.out.println("Next flight leaves in three hours.");
}
}
}
}
private void switchSeats(int i){
if(i == 1){
for(int counter = 0; counter < economyClass.length; counter++){
if(economyClass[counter] == false){
economyClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the economy class");
break;
}else if(counter == 4){
System.out.println("Economy class is filled");
}
}
}else if(i == 2){
for(int counter = 0; counter < firstClass.length; counter++){
if(firstClass[counter] == false){
firstClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the first class");
break;
}else if(counter == 4){
System.out.println("First class is filled");
}
}
}
}
public static void main(String [] args){
BoardPlane plane = new BoardPlane();
for(int i = 0; i <= 10; i++){
System.out.println("Enter 1 for first class and 2 for economy class: ");
int userInput = input.nextInt();
plane.setSeat(userInput);
}
}
}
When you call nextInt() it only reads the number, not the rest of the line and not the new line you typed.
This means if you later call nextLine() it will read what ever was after the number i.e. most likely nothing.
A simple work around is to ignore the rest of the line after the number.
int userInput = input.nextInt();
input.nextLine(); // ignore the rest of the line.
i have same problem, when you use scanner, and put the message with System.out.println(), newLine not work correctly.I dont know why ?! when you make input = new Scanner(System.in) after out your message in console, it's work correct.
but u can make a method for give user input and in this method make a feresh scanner like this :
publis static String getUserInput(String message){
System.out.println(message);
input = new Scanner(System.in);
return input.nextLine();
}

How to run 2 times of do-while loop only?

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

Categories