Boolean loop combined with JOptionPane Java - java

I would love to share my code. But in my university the code gets tested for "cheating".
But here is my code in simplier form.
public static String readin() {
boolean error = false;
do {
string stringin;
stringin = JOptionPane.showInputDialog(null, "Please enter a number");
switch (stringin.length()) {
case 0:
JOptionPane.showMessageDialog(null, "Error Please repeat");
error = true;
case 1:
return stringin;
}
return null;
} while (error == true);
}
This Code is really in it's simpliest form. I know that for this case it would be smarter to set the while to JOptionPane is empty or something. Since in my code are like 12 different error cases. I want to use the boolean. Please: the return null will never occur in the real code.
But the real problem I have: It works perfectly fine besides: if he repeats the loop he doesn't give me the chance to type a new stringin in.
How can i do this?
Also I am sorry for my faults in english.
EDIT:
All your helps fixed my problems! Thank you very much! I love this forum!

Try with break before case 1 (#Tuxxy_Thang) and remove return null; before while (error); and put after.
public static String readin(){
boolean error=false;
do{
string stringin;
stringin=JOptionPane.showInputDialog(null,"Please enter a number");
switch (stringin.length()){
case 0: JOptionPane.showMessageDialog(null, "Error Please repeat");
error=true;
break;
case 1: return stringin;
}
} while (error);
return null;
}

You dont have to check for while condition as you wanted the user to repeat again.Return only if you have the right value else ask again
public static String readin() {
while (true) {
String stringin = JOptionPane.showInputDialog(null, "Please enter a number");
switch (stringin.length()) {
case 0:
JOptionPane.showMessageDialog(null, "Error Please repeat");
break;//is important in switch cases
case 1:
return stringin;
}
}
}

There are two reasons:
The return null should be moved to end.
There should be a break statement at the end of the first case
I have given the modified code and it repeats the loop if the user does not enter anything for the JOptionPane:
public static String readin() {
boolean error = false;
do {
String stringin;
stringin = JOptionPane.showInputDialog(null,
"Please enter a number");
switch (stringin.length()) {
case 0:
JOptionPane.showMessageDialog(null, "Error Please repeat");
error = true;
break; // **added**
case 1:
return stringin;
}
} while (error == true);
return null; // Moved here. It will return if user entered more than 1 letter.
}

You are making a simple job hard, use Java classes properly and you will have an easier time of things
public static String readin()
{
Boolean gettingNumber = true;
String stringin = null;
while (gettingNumber)
{
stringin = JOptionPane.showInputDialog(null, "Please enter a number");
try
{
Integer number = Integer.parseInt(stringin);
gettingNumber = false;
}
catch (NumberFormatException exception)
{
// no need to do anything
}
}
System.out.println("returning [" + stringin + "]");
return(stringin);
}
I added this because I deduced that you are asking the user to input a number but your code would only allow the user ot enter any single character regardless of whether it is a valid digit or not and that is what you would return form your original method.

Related

java - After the exception handling ends and correctly, switch code is executed in a never ending loop.

First of all, thank you for reading this post.
I have this case of exception handling followed by a switch. After the exception handling ends correctly, the switch code is executed in a never-ending loop. If I comment the exception handling part and just add
"selection = scanner.nextInt()" the code works fine. But with the exception handling, never-ending loop happens again. I am quite sure it is all about the position of the curly braces but I just can't sort out which of them.
Thank you for help on this.
import java.util.Scanner;
class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main( String[] args ) {
ToString human = new ToString("John", 30, true);
int selection = 0;
boolean quit = false;
String selecta = null;
String message = "Select option";
while (!quit) {
returnMessage(message);
while (selecta == null) {
try {
selecta = scanner.nextLine();
selection = Integer.valueOf(selecta);
break;
} catch (NumberFormatException e) {
returnMessage("An integer was expected. Please try again.");
selecta = null;
returnMessage(message);
}
}
switch (selection) {
case 1:
System.out.println(human.getAge());
break;
case 2:
System.out.println(human.getName());
break;
case 3:
System.out.println(human.isMan());
break;
case 4:
quit = true;
break;
}
}
}
public static void returnMessage (String message){
System.out.println(message);
}
}
selecta variable never gets set to null after the switch statement and since your input is in a block with a condition selecta == nullit never executes and goes straight back into the switch statement, and so on, and so on...
Put selecta = null after the switch statement and that should be it.

How can I make this program read the entire file before returning value false?

I have a GUI asking for a word, and when the word isn't found it returns not found for every word within dictionary.txt. I'm assuming some sort of array will be used to increment every false, but I don't know exactly how to write something like that. I can see why it returns "Nothing matches" for every incorrect string. Any suggestions?
File file = new File("dictionary.txt");
Scanner inputFile = new Scanner (file);
inputFile.useDelimiter("\n");
String wordCheck = textField.getText();
while(inputFile.hasNext()) {
String dictWord = inputFile.next();
if (wordCheck.equals(dictWord)) {
JOptionPane.showMessageDialog(null, "Pie for you!");
break;
} else {
System.out.println("Nothing matches");
}
}
Store result of wordCheck.equals(dictWord) in boolean variable and decide what to show after reading whole file and yes remove break; satement.
boolea isValid = false;
while(inputFile.hasNext()) {
...
if (wordCheck.equals(dictWord)) {
isValid = true;
}
}
if (isValid)) {
JOptionPane.showMessageDialog(null, "Pie for you!");
} else {
System.out.println("Nothing matches");
}
You can add a boolean found = false; before your while loop and set found = true; inside the loop if you found something (instead of showing the message). Then display the message AFTER the loop, depending on the state of your found variable.

Return to previous spot in loop after try catch?

} else if (selectionKey == 2) {
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an invalid item name?");
}
That's my code atm. How do I return back to the if statement and continue the loop after it catches?
You could embed it in a loop like,
for (;;) { // <-- start an infinite loop
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
break; // <-- terminate the infinite loop.
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an "
+ "invalid item name?");
e.printStackTrace(); // <-- tell them what went wrong.
}
}
I think (if I understand your question and code correctly) that what you want is a loop containing the s.nextLine(). Note that I am assuming several things here:
s is a Scanner or something equivalent that reads input from the user
an exception is thrown if the user enters invalid input
you want to keep asking the user for input until they enter something valid
If this is the case, then you should create a loop like this:
while (true) {
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
break;
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an invalid item name?");
}
}
Also, why are you calling nextLine() twice? When you call it the first time, it will read a line from the scanner. When you call it again, it will not return the same line; it will instead wait for a new line. This means the user has to enter some random string, then enter the actual value. Finally, you should NEVER use == or != on Strings. Since they are reference types, you are essentially checking if they occupy the same location in memory, rather than if they are equal. Use s.nextLine().equals("") instead.

How to ask user if he wants to start program all over again if he typed a char/string instead of a number?

I'm new here and new to Java, started like 1-2 weeks ago and I wanted to make an app that is applying pythagora's theory. All done, but now I'm stuck in a place where I want the user to be asked if he wants to try again, start again, if he enters a character or string instead of a number.
What am I doing wrong? This is my code, I've added comments too so it would be easier in case you don't understand what I was trying to achieve.
Thanks in advance!
package pitagoracalculator;
import java.util.Scanner;
public class PitagoraCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double nr1;
double nr2;
double ipot;
boolean raspuns;
String raspuns1;
do{
try{
//user is asked for first number
System.out.print("Introduceti primul numar: ");
nr1 = input.nextDouble();
//user is asked for second number
System.out.print("Introduceti al 2-lea numar: ");
nr2 = input.nextDouble();
//result of calculation
ipot = (nr1*nr1)+(nr2*nr2);
System.out.println("Rezultatul este: "+ipot+"^2");
//in case user inserts a string/char instead of a double => error
} catch (Exception e){
System.err.println("Nu ati introdus un numar.");
break;
}
//user is asked if he wants to do another calculation
System.out.println("Doriti sa faceti un alt calcul? (da/nu)");
raspuns1 = input.next();
//if his answer is yes, raspuns = true, else raspuns = false
if(raspuns1.equalsIgnoreCase("da"))
raspuns = true;
else{
System.out.println("La revedere!");
raspuns = false;
}
//checks if the answer was true or false
}while(raspuns == true);
}
}
Replace
//in case user inserts a string/char instead of a double => error
} catch (Exception e){
System.err.println("Nu ati introdus un numar.");
break;
}
with
//in case user inserts a string/char instead of a double => error
} catch (Exception e){
System.err.println("Nu ati introdus un numar.");
//clear pending input.
if (input.hasNext()) {
input.next();
}
continue;
}
"break" exits the loop, "continue" will continue with the next cycle of the loop.
You also have to initialize the raspuns variable with true
boolean raspuns = true;
You can call method in exceptional case.For this you should make a method in same class and put your all stuff in that method use if-else loop..

Password masking does not terminate the program when needed

I developed the following application in which I needed to masking the PIN and terminate the program after the user has entered the wrong PIN thrice. However, the program terminates only if i close the stopThread at the beginning (I commented it in the code below), however the password masking does not occur for all the three channces when I do so. But, when I close the stopThread just before displaying the login successful screen, the program does not terminate. I need to use ctrl+c to end the program.
Any help is greatly appreciated.
boolean stopThread = false;
boolean hideInput = false;
boolean shortMomentGone = false;
public static double userBal=0.0D;
public void run(){
try{
sleep(500);
} catch(InterruptedException e){
}
shortMomentGone = true;
while(!stopThread){
if(hideInput){
System.out.print("\b*");
}
try{
sleep(1);
} catch(InterruptedException e){
}
}
}
public static final int NB_OF_TRIES = 3;
public void validatePin(){
BankAccount getAll=new BankAccount();
String pin="";
getAll.Login();
Login hideThread =new Login();
hideThread.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try{
do{
} while(hideThread.shortMomentGone == false );
// Now the hide thread should begin to overwrite any input with "*"
hideThread.hideInput = true; // Read the PIN
System.out.println("\nPIN:");
boolean pinMatch = false;
int i = 0;
while(!pinMatch && i < NB_OF_TRIES) {
hideThread.hideInput = true;
pin = in.readLine();
i++;
//hideThread.stopThread = true; //Program terminates after third attempt
//PIN masking is stopped, if uncommented
System.out.print("\b \b");
if(pin.equals(" ")){
System.out.println("Please do not leave unnecessary spaces!");
getAll.Login();
}else if(pin.equals("")){
System.out.println("Please do not press the enter key without entering the PIN!");
getAll.Login();
}
FileInputStream fileinputstream = new FileInputStream(".\\AccountInfo.txt");
DataInputStream datainputstream = new DataInputStream(fileinputstream);
BufferedReader bufferedreader1 = new BufferedReader(new InputStreamReader(datainputstream));
do
{
String s1;
if((s1 = bufferedreader1.readLine()) == null)
{
break;
}
if(s1.trim().charAt(0) != '#')
{
String as[] = s1.split(" ");
if(pin.equals(as[0]))
{
System.out.println("You have login!");
String s2 = as[2];
userBal = Double.parseDouble(s2);
getAll.balance = userBal;
hideThread.stopThread = true;
getAll.MainMenu();
System.exit(0);
}else if(pin != as[0]){
System.out.println("Invalid PIN!");
getAll.Login();
System.out.println("\n NOTE :- You are only allowed to enter the PIN THREE times. The number of tries remaining before your card is blacklisted are "+i + "\n Please re-enter your PIN");
}
}
} while(true);
datainputstream.close();
}//End of While Loop
}catch(Exception exception)
{
System.err.println((new StringBuilder()).append("Error: ").append(exception.getMessage()).toString());
}//End of try-catch block
}
There's a readPassword() method in java.io.Console, use that. Why do you need a separate thread at all? That makes everything way too complicated.
Regarding your question why this does not close: Java may optimize while(isTrue){} to something like if(isTrue) { while(true) { } } if you don't set isTrue volatile or synchronize the access to isTrue (getter/setter). This optimizations is called hoisting and explained in Effective Java SE, item 66.
Here is an article which explains exactly your problem: echoing * instead of blanks.
http://java.sun.com/developer/technicalArticles/Security/pwordmask/
They are going the complicated way, too but it works. I would prefer blanks over asterisks since that is the easier way to go. Not echoing * is *nix standard afaik.
Actually after I analysed it a but more i realized that the reason the system wont terminate is because it is not kept in the proper place. Therefore, the solution would be to end the program as soon as the while loop is closed and then everything would work fine.
} while(true);
datainputstream.close();
}//End of While Loop
System.exit(0); // After the system is closed the program would terminate after the third attempt
}catch(Exception exception)
{
System.err.println((new StringBuilder()).append("Error: ").append(exception.getMessage()).toString());
}//End of try-catch block

Categories

Resources