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.
Related
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?
We were given a task to make a program that takes the input of the user. there two types of input the user can use, 1st is the "Type in the Size" and the second is "Type in the style" either way the user can just input in the 1st field or the 2nd field. when the users clicks ok the two inputs will be use to sortout a arraylist which contains the type of size and style in it.
public void viewResult(String style, String size) {
style = style.toLowerCase();
size = size.toLowerCase();
new_list = new ArrayList<>();
for(Items_container items:current_arrayList)
{
if (items.getStyle().toLowerCase().contains(style) && items.getSize().toLowerCase().contains(size))
{
new_list.add(items);
break;
}
else if (items.getSize().toLowerCase().contains(size)) {
new_list.add(items);
break;
}
else if (items.getStyle().toLowerCase().contains(style)) {
new_list.add(items);
break;
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
if (new_list.size() == 0) {
results.setText("Search not found");
} else {
results.setText("Results");
}
}
this is the method that I use to sortout out the Items_container now it does work fine (I guess)
but the problem is for example the user inputs "large" in the size input field and "blazzing" in the style input field the program must sort the items_container using the given inputs but it is not working because the program also includes all the items that has the same size or the same style.
I tried adding a break to the loop but now it only shows one data and what if there two or more data that matches the givens inputs, how can I do that?
You should check first if both conditions are set. That way you can separate if either one matches and if both match. Maybe put singular matches in a separate list in case no items match both conditions, but that's up to you.
And as others already said, break stops the loop, continue moves to the next item.
like code below:
for (int i = 0; i <current_arrayList.size() ; i++) {
if(current_arrayList.get(i).getStyle().toLowerCase().contains(style)
&& current_arrayList.get(i).getSize().toLowerCase().contains(size))
{
new_list.add(current_arrayList.get(i));
//if used break ,stop loop
}
else if (current_arrayList.get(i).getSize().toLowerCase().contains(size)) {
new_list.add(current_arrayList.get(i));
}
else if (current_arrayList.get(i).getStyle().toLowerCase().contains(style)) {
new_list.add(current_arrayList.get(i));
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
adapter.notifyDataSetChanged();
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 am fetching column values from my DB (Which is working fine) then I am putting these values into 'String X' one at a time as it loops. In the same loop I want to compare the values supplied to me by the user through UI with X and based on this comparison I want x to be true or false. But x always shows true! Here is my code:
private boolean fillData() {
Cursor c = DBHelper.fetchAllIDs();
// List<String> idList = new ArrayList<String>();
if (c.moveToFirst()) {
do {
String X = (c.getString(c.getColumnIndexOrThrow("IDno")));
Toast.makeText(getApplicationContext(), "" +X, Toast.LENGTH_LONG).show();
String B = null;
B = Idno.getText().toString();
if (B.equals(X));
{
Toast.makeText(getApplicationContext(), "If condition true"+B, Toast.LENGTH_LONG).show();
x=true;
}
} while (c.moveToNext());
}
return x;
}
Try to print the value of
String X = (c.getString(c.getColumnIndexOrThrow("IDno")));
such as Sop(x) or inside log.
and same way print the value of
B = Idno.getText().toString();
Sop(B) or inside log(B).
It may be both are same in meaning but different in present (case sensitive).
use
if(B.equalsIgnoreCase(X))
{
}
instead of if (B.equals(X));
don't put the condition termination symbol such as ; at end of if statement.
I got this folks, I had mistakenly put a ';' at the end of my if statement. Sorry! Silly!
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
}