How to iterate a condition in a while loop? Beanshell - java

Edited from my original post because I found a work around.
I'm trying to use a while loop to check if inputs exist. I have inputs that can vary in size, meaning I can have one input in a case or multiple in another. I'm using a while loop to execute many lines of code if the input(s) are present. The issue is that I know that I'll have at least one input in a case but in another case I may have 5,6,7, etc.
For example if I have:
input0="taco";
input1="water";
input2="sand";
With the example above in mind how do I iterate the condition of the while loop to make sure input0, input1, and input2 get executed?
In this example all of the commands within the while loop would be executed as long as input0,1,2 exist and are defined. My hope is that the integer q will scale with each input and the code within the while loop executes based on the current input.
When the loop reaches input3 I'd like it to exit the loop because that input does not exist.
I currently have the following:
int q=0;
String inputV =input(q);
while(inputV.contains("~")){ //first iteration takes "taco"
//This is where my long lines of code that need to be executed are
// I'm hoping that q will populate with 0,1,2 as the loop goes on and take "taco" "water" "sand" respectively
q++;
inputV=input(q);
//The next iteration will be input(1) = input1 which is "water"
}
New edit given the comment from Roger. The execution is having trouble getting through the if(f.equals(field)) statement. It passes through the for loop but can't process the if statement.
String input(int q) {
String field = "input" + q;
for (String f: global.variables) {
if (f.equals(field)) {
return (String) this.namespace.getVariable(field);
}
}
return null;
}
int q=0;
String inputV = input(q);
while(inputV != null) {
print(q + " " + inputV);
print("The input parameter is not null");
print("The input value is " + inputV);
// long lines of code executed within the while loop
q++;
inputV=input(q); }

You can find the defined variables in this.variables, global.variables or via the namespace.getVariableNames(). So with a helper method it is possible. In the example below I assumed they are defined in the global space.
input0="taco";
input1="water";
input2="sand";
String input(int q) {
String field = "input" + q;
for (String f: global.variables) {
if (f.equals(field)) {
return (String) this.namespace.getVariable(field);
}
}
return null;
}
int q=0;
String inputV = input(q);
while(inputV != null) {
System.out.println(q + " " + inputV);
q++;
inputV=input(q);
}
But, isn't there a better way for you to define the values such as array or list?

Related

finding number of words present in the string in java using recursion

A class words defines a recursive function to perform string related operations. The class details
are given below:
Class name : words
Data members/instance variables
text : to store string.
w : integer variable to store total words.
Member functions/methods
words( ) : constructor to store blank to string and 0 to integer data.
void Accept( ) : to read a sentence in text. Note that the sentence may contain more
than one blank space between words.
int FindWords(int) : to count total number of words present in text using Recursive
Technique and store in ‘w’ and return.
void Result( ) : to display the original string. Print total number of words stored in
‘w’ by invoking the recursive function.
I tried this code
public static int CountWords(String str) {
int c = 0;
int i = str.indexOf(" ");
if (str.isEmpty()) {
return 0;
}else
if (i == str.indexOf(" ")) {
return c++;
}
//str.substring(0,str.indexOf(" ")-1);
c++;
return c + CountWords(str.substring(i + 1));
}
but i need to return an integer value and i am confused with that..
In your code, the last return statement is inaccessible. Reason: you have put an if-else block and have put return in both the cases. So the function actually gets returned from the if-else block itself (within else, the condition of if is always true since you assigned the very value i.e. str.indexOf(" ")).
I have written down the code according to the question you gave above...
public int findWords(int i){
if(i > text.lastIndexOf(" "))
return 1;
i = text.substring(i).indexOf(" ") + i;
if(i < 0)
return 1;
if(text.substring(i).equals(null))
return 0;
return( findWords(i+1) + 1);
}
Hope you find it well working.
Your function already is returning a integer, it just happens to always be 0.
This is due to
else if (i == str.indexOf(" ")) {
return c++;
}
Always being true and c++ only updating after the return statement was passed.
This happens because you already set i to be the indexOf(" ") and due to the implementation of incrementation using int++. Also, keep in mind hat you need to increase the number of words by 2 here, since you're ending the function between two words.
Therefore, use this instead:
else if (i == str.lastIndexOf(" ")) {
return c+2;
}
You should see that now the function is returning the correct amount of words.

linear search Arrays check values

I need to get inputs to fill an array. My problem is I also need to check if the value I input does not exist already in the array. If exists I need to show a message that says bad grade. I believe I get stuck on the search loop I and Im not able no assign the value to the array If is not already there.
String[] course = new String[9];
int index = 0;
if (menu == 1) {
boolean found = true;
do {
value = (JOptionPane.showInputDialog("Enter course " + (index + 1)));
int pos = 0;
while (pos< course.length&& !found) {
if (value == course[index]) {
found = true;
} else {
pos++;
}
} // while
if(found == true) {
course[index] = value;
} else {
course[index]="";
}
if (course[index].equals("")) {
JOptionPane.showMessageDialog(null, "Bad Course Name");
} else{
course[index] = (JOptionPane.showInputDialog("Enter course " + (index + 1)));
}
} while(course[index].equals("")); //last
}
The problem with your implementation is that once found is set to true, you never reset it back to false: it's a one-way street. That is why entering the first duplicate value prevents other non-duplicated values from being entered.
You can fix this by moving the declaration/initialization of found inside your do/while loop. However, a better approach would be defining a helper method that searches the array for you up to the specific position, and returns true if a duplicate is found:
private static boolean isDuplicate(String[] course, int maxIndex, String entry) {
...
}
Now the loop searching for duplicates would be hidden, along with the variable indicating the result. The code becomes more readable, too, because the name of the method tells the reader what happens inside.
Of course, you need to fix your string comparison: your code uses ==, which is not the way it is done in Java.

I'm having a hard time terminating a java loop

I'm sure if you read the snippet you'll understand what I'm trying to do. However, I tried it first with null and "". I think .eoln() won't work because I'm asking for multiple lines of input, of which all have an end of line. I would preferably have the loop terminate when the user returns an empty line. For some more background, I've used the ==/!= and .equals() operators/method to experiment. I also just tried a do/while to no avail.
The asterisks were added to test if the empty string was an issue for the while statement.
Can anyone explain what I clearly don't understand about Java/TextIO yet?
EDIT - Revised Code Snippet:
while(write){
pl("Begin writing content to fill file.");
pl("");
pl("Return a line with a single SPACE or");
pl("\"\\n\" to represent line breaks in your");
pl("");
pl("Return two asterisks ** when done writing,");
pl("and you will be then prompted to select a file");
pl("to save your writing to.");
String input = TextIO.getln();;
String value = new String();
while(!(input.equals(""))) {
if (input == " " || input == "\\n") {
value += "\\n" + "\\n";
} else {
value += input + " ";
} // end if/else //
input = TextIO.getln();
} // end while(input) //
TextIO.writeUserSelectedFile();
p(value);
TextIO.writeStandardOutput();
pl("Would you like to write to another file?");
Boolean cont = TextIO.getBoolean();
write = cont;
}
}

How do I make an if statement validation in processing?

I have been trying to work this out hours now, but I can't seem to find the solution.The code is basically an appointment program, and when it runs it pops out a box and the 'secretary' inserts the name and time of the patient. However, if I put "Maria" at "1200" and "John" again at "1200", the system will immediatelly replace Maria with John. My code is as follows:
String[] names = new String[2400]; // from 0:00 until 24:00
void setup()
{
String name = "";
do
{
name = input("Name");
if (name.equals("ABORT")) {
System.exit(0);
} // end the program
int time = int(input("Time code (e.g. 840 or 1200)"));
names[time] = name;
showAllNames();
}
while (true); // loop never ends
}
void showAllNames() // shows all the times where there is a name
{
for (int t = 0; t < 2400; t=t+1)
{
String name = names[t];
if (name!=null)
{
println(t + "\t" + name);
}
}
println("================");
}
public String input(String prompt)
{
return javax.swing.JOptionPane.showInputDialog(null, prompt);
}
How can I add an if command that checks that the position is null before writing - and otherwise warn the user?
Check if the index is null before writing to it:
if(names[time] == null){
//Add the name
} else {
//If the name isn't null, perhaps go to the next index, or throw an exception
}
What you want to do if the name is null is entirely up to you.
I would like to add a few suggestions as well:
Make your names variable an ArrayList, this way you can add any amount of names without changing the variable.
Don't call your showAllNames() method from within your loop, rather call it after the loop has ended.
Use normal indexes instead of a time index, this way you won't have to do null checks.

for loop for inputting variables into array not working?

I'm trying to input 3 different variables into an array inside a while loop, as long as i don't enter stop for any of the variables. the while loop is only suppose to let me input a second variable value if the 1st variable isn't stop, and likewise with inputting a third variable value
Right now, the first loop goes fine and i can input all 3 variables, but the 2nd and 3rd time, the for loop outputs the first variable, but doesn't allow me to input a value before skipping to the 2nd variable.
ex of what i mean:
name:afasdf
extra info:afdsaf
unit cost:123123214
name: extra info: adflskjflk
also, entering Stop isn't ending the loop either
unit cost:123217
i know that this loop works when there's only one variable, and i've tried using a for loop instead of a while loop, and adding tons and tons of else statements, but it seems to stay the same
is there something wrong with the way i set up my breakers?
is the way i set up the last breaker(the one that stops even when i put stop for a double variable) messing up the rest of hte loop?
thank you so much
here is my code
ArrayItem s = new ArrayItem();
String Name = null, ID = null;
double Money = 0;
boolean breaker = false;
while(breaker ==false)
{
System.out.print("Name:" + "\t");
Name = Input.nextLine();
if(Name.equals("Stop")) //see if the program should stop
breaker = true;
System.out.print("Extra Info:" + "\t");
Details = Input.nextLine();
if(ID.equals("Stop"))
breaker = true;
System.out.print("Unit Cost:" + "\t");
Money = Input.nextDouble();
// suppose to let me stop even if i input stop
// when the variable is suppose to be a double
if(Input.equals("stop") || Input.equals("stop"))
breaker = true;
else
s.SetNames(Name);
s.SetInfo(Details);
s.SetCost(Money);
}
A couple of things about the code: "Name:" + "\t" can be simplified ot "Name:\t". This is true for the rest of the code. In Java, it's customary to use camelcase where the first word is lowercase. For example, s.SetMoney would be s.setMoney. Also, variables follow the same rules where Money would be money, and ID would be id. If your teacher is teaching you otherwise, then follow their style.
The loop should also be a do-while loop:
do
{
// read each value in sequence, and then check to see if you should stop
// you can/should simplify this into a function that returns the object
// that returns null if the value should stop (requiring a capital D
// double for the return type)
if ( /* reason to stop */)
{
break;
}
s.setNames(name);
s.setId(id);
s.setMoney(money);
} while (true);
private String getString(Scanner input)
{
String result = input.nextLine();
// look for STOP
if (result.equalsIgnoreCase("stop"))
{
result = null;
}
return result;
}
private Double getDouble(Scanner input)
{
Double result = null;
// read the line is a string looking for STOP
String line = getString(input);
// null if it's STOP
if (line != null)
{
try
{
result = Double.parseDouble(line);
}
catch (NumberFormatException e)
{
// not a valid number, but not STOP either!
}
}
return result;
}
There are a lot of concepts in there, but they should help as you progress. I'll let you put the pieces together.
Also, you did need to fix the brackets, but that's not the only issue. Because Money is a double, you must read the value as a String. I suspect that Input is a Scanner object, so you can check Input.hasNextDouble() if it's not, then you can conditionally check the String value to see if it's "stop" (note: you are checking for "Stop" and "stop", which are not equal). Your last, no-chances check compares the Scanner to "stop", which will never be true. Check
System.out.print("Unit Cost:\t");
if (Input.hasNextDouble())
{
Money = Input.nextDouble();
// you can now set your object
// ...
}
// it's not a double; look for "stop"
else if (Input.nextLine().equalsIgnoreCase("stop"))
{
// exit loop
break;
}
// NOTE: if it's NOT a double or stop, then you have NOT exited
// and you have not set money
breaker = true;
while(breaker){
Name = readInput("Name");
Details = readInput("Details");
Money = Double.parseDouble(readInput("Money"));
if(Name.equals("stop") || Details.equals("stop"))
breaker = false;
else {
// set ArrayItem
}
}
private static String readInput(String title){
System.out.println(title+":");
//... read input
// return value
}

Categories

Resources