How to use do while loops [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to put a password onto this section of code, I am trying to use a do while loop but it carries on looping.
Can you please show me where my errors are? The password I am using is 1234.
import javax.swing.*;
public class cipherprac
{
static int choice = 0;
public static String msg;
public static int password = 1234;
public static int response = 0;
public static void main (String[] args)
{
msg = JOptionPane.showInputDialog("Enter the message");
response = Integer.parseInt(JOptionPane.showInputDialog("Enter the password"));
do
{
char enc;
String encmsg = "";
int len = msg.length();
for (int i = 0; i < len; i++)
{
char cur = msg.charAt(i);
int val = (int) cur;
val = val - 30;
enc = (char) val;
encmsg = encmsg + enc;
msg = encmsg;
}
}
while(response == password) ;
JOptionPane.showMessageDialog(null, " " + msg);
}
}

You don't change the response (nor password) in your code, so if you set it to 1234 then it will be looping for ever.

response = Integer.parseInt(JOptionPane.showInputDialog("Enter the password")); is the last time you set "response", so it will be that forever, hence the infinite loop.
This seems to be some sort of custom encryption? Anyway, you'd want to do something like:
do
{
...
}
while(response == password && "Certain condition isn't met");
This way it will end the loop if for some reason the user input changes OR if it is done with your process.

Well you do not change the value of your password or response variable inside the loop. So how is the loop supposed to stop?
Your loop will run once and at the end check whether condition for continuing is met. If yes, it will start the next iteration of the loop code block. If you do not change anything inside the loop which has an effect on the loop's condition, it will run once (if the condition evaluates to false) or until you kill the program (if the condition evaluates to true).
As for the normal work of a loop, here you can find a good explanation with examples in many languages (including Java): Wikipedia link

There are multiple issues:
Not updating response inside the loop
While condition loops again if successful, I think it should try again on unsuccessful password if I understand correctly.
Do you want to keep trying until your password is correct?
In this case, your while condition should be true when they are not equal, so that if it is not successful, you keep trying.
In your case, if your response is not 1234, it will not try, and if it is, it will loop forever.
Ideally for a do while loop:
set condition value before loop
do{
// do some work
// update condition value
}while(condition);

Related

If-else One line statement (with string and integer) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm creating a program. This code below is the Java program. Checking if the value of B and H, input by the user is equal to zero. If it is true, then a math formula will execute which is p = b*h then if it is false, a string will be shown on the console. But the thing is, it keeps on giving me an error that string cannot be converted to int or int cannot be converted to string.
Here is the code:
import java.util.Scanner;
public class StaticProject{
static {
Scanner input = new Scanner (System.in);
int B = input.nextInt();
int H = input.nextInt();
int P;
int solution = B>=0 && H>=0 ? P = B*H : "java.lang.Exception: Breadth and height must be positive";
}
How can I improve my coding when it comes in doing this oneline bi-conditionals statement? Any tips?
your solution variable Type is int, and your else statement returns an String, this is the cause of error.
you can change your code to this:
Scanner input = new Scanner (System.in);
int B = input.nextInt();
int H = input.nextInt();
int P;
if (B >= 0 && H >= 0) {
P = B*H;
} else {
throw new Exception("Breadth and height must be positive");
}
System.out.println(P);
}
You are trying to assign string to an int variable, if your statement is evaluated as false.
You need to use if/else condition, which both sides have the same type.
In your case, it's not possible.
another possibility is use System.out.println() command, to print the result of whatever resulted by the condition.
There is no virtue in writing code in as few lines as possible. By all means, don't write unnecessary code, but just don't think that concise code is objectively "better".
The best type of code to write is simple code. Maybe it's a little more verbose; but if you write code that people can understand at a glance, they know what it does straight away.
Here is how I would write it:
if (B < 0 || H < 0) {
// Actually, non-negative, rather than positive.
throw new Exception("Breadth and height must be positive");
// Or, maybe, don't even use exceptions at all:
// System.out.println("The message");
// return;
}
// No need for `solution` variable.
P = B * H;
System.out.println(P);
Of course, you might argue this isn't code everybody will understand at a glance. Sure. Readability is subjective; but I assert that anybody with just a little bit of experience in Java can work it out.
You can write a conditional ?: expression which results in an exception being thrown in the case of the condition being false.
// Define a method which does the throwing.
static int justThrow(String message) throws Exception {
throw new Exception(message);
}
// In the main method:
int solution = B>=0 && H>=0 ? P = B*H : justThrow("Breadth and height must be positive");
I emphasize that you can, but you shouldn't do this. It's obscure. It's trying to be "a bit too clever". It will have people reading your code and scratching their heads, because they will wonder why you wrote a method for something so simple; what is the solution variable for, given that it will have the same value as P etc.

OutofBounds Exception [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying here to measure how many white spaces there are in text typed in a JTextArea. I am getting an outofbounds exception. Why so?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at ClassTest.main(ClassTest.java:11)
import javax.swing.*;
public class ClassTest {
public static void main(String [] args) {
JFrame frame = new JFrame();
JTextArea textarea = new JTextArea();
frame.setSize(300, 300);
frame.add(textarea);
frame.setVisible(true);
String text=textarea.getText();
int count = 0;
for(int i=0;i>=text.length();i++) {
char spacecount = text.charAt(i);
if(spacecount==' ') {
System.out.print(count++);
}
}
}
}
I believe it should be < not >= for the 'for' loop condition.
Your for loop is as follows:
for(int i=0; i>=test.length();i++){
char spacecount = test.charAt(i);
if(spacecount==' '){
System.out.println(count++);
}
}
Let us take a walk through the for loop. The first part says, we create an int called i and initialize it to 0;
i = 0;
Next part says, keep looping while this condition is true. So it will loop while
i >= test.length()
The next part says, after each iteration, let us add 1 to i. The only reason it could possibly run is
if test.length() == 0;
if test.length() == 1;
0 is not >= 1 so it won't run. That means, the only reason it could run is if the length is 0. Now if the string is of length 0, it would be "".
What is the charAt(0)? Nothing. There is no 0 index. If the String were "a". Then charAt(0) would return "a". It is reaching for something that does not exist and therefore will not run. So one of the problems is that you need to change the condition to < instead of >=. Next, it is recommended to use camel case for fields (such as spacecount) which means you should change it to spaceCount.
Lastly, it may not occur in this case but let us say, test = null. What happens? What is null.length()? Is that even possible? Well actually it will compile in the case that test = null; and then test.length() is executed. However, you cannot call such a method on a null value so you will get the dreaded runtime error, the "NullPointerException". This says, uh oh. We have a string that points to null. Well we cannot do anything with it. Here comes the exception. So in future code, it is recommended to be able to account for such cases. So what do we do? How do we check if a String == null? Well... String == null. So in the future, if it is possible for something to be null, put the for loop in an if statement that says:
if(test != null){
//put for loop here
} else{
//do something else
}

Counter Loop - Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Edit: I have found a way to work with CompareTo to help with this problem, but for some reason I cannot get the count down to work.
It's a negative number that needs to get more negative to meet the requirements, but I am missing something here. When I execute the down section it closes the program. So to me this means that I have something messed up and the program isnt seeing the problem and closing.
We are supposed to:
Ask the user for an integer then ask the user if he/she wants to count
up or down. Display a table of numbers where the first column contains
the counter, the second column contains the counter plus 10, and the
third column contains the counter plus 100. Make it so each number
takes up 5 spaces total.
If counting up, the first column should contain numbers 1 through the
user input; If counting down, the first column should contain numbers
-1 through the the negative of the user input;
Do user input validation on the word "up" and "down". Allow for any
case.
import java.util.Scanner;
public class ps1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Comparision string already declared
String up = "up";
String down = "down";
//initialize the counters sum
int sum = 0;
//ask the user for a number
System.out.println("Enter an ending value");
int num1 = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Count up or down?");
String input = keyboard.nextLine();
while (input.equalsIgnoreCase(up) || input.equalsIgnoreCase(down)) {
System.out.println("Count up or down?");
input = keyboard.nextLine();
}
if (input.compareToIgnoreCase(up) == 0) {
if (num1 >= 0)
for (int c = 1; c <= num1; c++) {
sum = sum + c;
System.out.printf("%5d%5d%5d\n", c, c + 10, c + 100);
else
System.out.println("Up numbers must be positive");
if (input.compareToIgnoreCase(down) == 0) {
for (int c1 = -1; c1 <= num1; c1--) {
sum = sum + c1;
System.out.printf("%5d%5d%5d\n", c1, c1 + 10, c1 + 100);
}
}
}
}
}
I see you have figured out core logic. BTW, your code will not compile, there is a syntax error.
Your code would look like this:
print(a a+10 a+100)
I know that it's not valid syntax but you would be able to figure out the correct way to write the code.
To print data properly, you will need following:
https://dzone.com/articles/java-string-format-examples
I would recommend visualizing the output first. In your case, it would look like following: (_are spaces)
Enter an ending value: 2
Direction: Up
____1___11__101
____2___12__102
Also, think about error cases. What will happen in following:
Enter an ending value: -10
Direction: Up
Error: Improper data
You are allowing user to enter a positive num1 and count down using for (int counter1 = -1; counter1 >= num1; counter1--). This makes no sense as counter1 >= num1 resolves to -1 >= 1 which is never true. When direction is down the number must be negative and when direction is up the number must be positive.
You might need to loop until user provides a valid direction. Currently you go down for any input that is not up. A possible solution would be to:
String input;
do {
input = keyboard.nextLine();
} while (!input.equalsIgnoreCase("up") && !input.equalsIgnoreCase("down"));
Please use shorter variable names. counter1 is scoped just to the for loop block so call it i. It's easier to read.
Whichever editor you are using configure auto formatting :)

Can I return Boolean value in a loop statement? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I just came up with a problem returning a Boolean value in accordance with a given condition. I thought in order to check the given condition for full possibilities I need to use for loop. But when I tried to compile it, it gives me error, possibly because there is uncertainty returning a Boolean value using for loop. Here is an original problem:
Return true if the given string contains a "bob" string, but where the middle 'o' char can be any char.
bobThere("abcbob") → true
bobThere("b9b") → true
bobThere("bac") → false
And here is my code:
public boolean bobThere(String str)
{
for(int i=0; i<str.length()-3; i++)
{
if (str.length()>=4): && str.charAt(i)=='b' && str.charAt(i+2)=='b')
{
return true;
}
else
return false;
else if (str.length()==4 && str.charAt(0)=='b' && str.charAt(2)=='b')
{
return true;
}
else
{
return false;
}
}
}
I just wanted to ask :
1. Can I fix the this code for returning a value. I mean, can I use for loop and return specific value for a given condition? If yes, please could you give me a sample.
2. Or are there any ways other than for loop to solve this problem.
Thanks in advance.
The compiler error is almost certainly because you have an elseif after an else. That's invalid.
Looking at your code, what you seem to want to do is loop through the string, and then return true if you're at the start of a b?b string. I'm not sure why you have your second if condition in there - at the moment your code would check the first and third characters of the string on every iteration of the loop, if the string happens to be exactly four characters long. Pointless, it doesn't need to be there. The check for length isn't necessary at all.
Additionally, your end condition for the loop is currently i < string.length()-3. This means that the final three characters of the string will not be checked. You would need to change this to either i <= string.length()-3 or i < string.length()-2 to solve this.
Your else return false stuff is going to give you a serious problem. Your code will enter the loop once, and then either return true or false, without ever going to the next phase of the loop. What you should do is loop through the string, and if you find what you're looking for, return true. Otherwise, don't return at all, and keep going with the loop. If you get to the end of the loop it means you never found what you were looking for, so you can at that point return false.
Taking those comments into account, your revised code would look like this (please note I haven't compiled or run this):
public boolean bobThere(String str)
{
for(int i = 0; i <= str.length() - 3; i++)
{
if (str.charAt(i) == 'b' && str.charAt(i + 2) == 'b')
{
return true;
}
}
return false;
}

Java add line to specific part of text file

COMMENTS BELOW ARE ANSWERING ANOTHER QUESTION, THIS IS THE ONLY WAY FOR ME TO ASK NEW QUESTION...
Okay. My program is like writing info on a .txt file. Currently it is writing info to end of the text file like so:
t/1/15/12
o/1/12/3
o/2/15/8
... (lots of lines like this.. all with different numbers)
o/1/16/4
Then.. when I add line using:
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("C://Users/Mini/Desktop/Eclipse/Japda/map/" +Numbers.map +".txt"), true));
fw.newLine();
fw.write(RightPanel.mode.charAt(0) +"/" +ID +"/" +Numbers.middlex +"/" +Numbers.middley);
fw.close();
It adds the line I want to but currently to the end of the text file.. However I would like it to write that line to a specific part of the text files.. I already do know the number of the line I want to write it.. (It is calculated depending on other lines..) :D Is there any way to do it? Or what would be the best way to edit one specific line in the middle of that text file?
To achieve what you require, you would need to use a RandomAccessFile. Steps:
First create a RandomAccessFile then:
Create a variable called lineStart which is initially set to 0
(beginning of the file)
Read in the file line by line using readline
Check whether it is the required line that you wish to insert before
If it is the correct place, then lineStart will hold the position
just before the line you wish to insert before. Use seek to
position you at the correct place by initially using seek(0) to
position you at the start of the file, then seek(lineStart) to get
the required position. You then use writeChars to write to the file.
Remember that you have to explicitly write the newline.
If it is not where you wish to insert then call getFilePointer, and
store value in lineStart
REPEAT STEPS 2-5 UNTIL YOU ARRIVE AT THE DESIRED PLACE FOR INSERTION
You want a do-while loop:
do {
//code
} while (expression);
Source:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
You probably want something like this:
int[] done = new int[100];
int randomquestion;
do{
randomquestion = (int)(Math.random() * 83 + 1);
if(done[randomquestion] != 1)
{
//ask random question
//if answer is correct, set done[randomquestion] = 1
//else just let do-while loop run
}
//check if all questions are answered
} while (!areAllQuestionsComplete(done));
Here is the method areAllQuestionsComplete(int[]):
private boolean areAllQuestionsComplete(int[] list)
{
for(int i = 0; i<list.length; i++)
{
if(list[i] != 1)
{
return false;//found one false, then all false
}
}
return true;//if it makes it here, then you know its all done
}
Looking at your latest code:
for(int i = 0; i<done.length; i++)
{
done[i] = 0;//need default values else wise itll just be NULL!!!
}
do{
ran = (int)(Math.random() * 83 + 1);
//before entering the do-while loop, you must set default values in the entire done[] array
if(done[ran] != 1)
{
//ask random question
//if answer is correct, set done[ran] = 1
//else just let do-while loop run
if (ran == 1) { //1
question = "kala";
rightanswer = "fish";}
if (ran == 2) { //2
question = "peruna";
rightanswer = "potato";}
if (ran == 3) { //3
question = "salaatti";
rightanswer = "cabbage";}
if (ran == 4) { //4
question = "kalkkuna";
rightanswer = "turkey";}
if (ran == 5) { //5
question = "kia";
rightanswer = "tikku";}
//YOU MUST HAVE EVERY CONDITION COVERED
//say your random number makes the number 10
//you dont set question to anything at all (hence getting null!)
System.out.println(question);
System.out.print("Vastaus?: ");
answer = in.readLine();
//if (answer == rightanswer){
//must use .equals with Strings...not ==
if (answer.equals(rightanswer)){
right++;
done[ran] = 1;}
else{wrong++;}
}
//check if all questions are answered
} while (!areAllQuestionsComplete(done));//use the method I wrote!
EDIT:
You must put default values in the array. When you create an array, the default value is null.
int[] done = new int[100];//create array but everything is null
for(int i = 0; i<done.length; i++)
{
done[i] = 0;//need default values else wise it'll just be NULL!!!
}
//must be done before the do-while loop starts
Finally, make sure your random number generator picks the correct range in numbers. If you have an array that is size 100, then it's indexes will be 0-99. This means there is no done[100]. It goes from done[0] to done[99].
If you have done[] be a size of 5, then it will range from done[0] to done[4]. That means you should randomly generate like this:
randomquestion = (int)(Math.random() * 5 );

Categories

Resources