Can a for loop be used in a JOptionPane.showMessageDialog? - joptionpane

So I'm new here, and this is my first question...Is there a proper syntax for using the for loop in JOptionPane.showMessageDialog?
This is my current code and I know that it doesn't work. My code is for showing the factors of a certain integer and I want to know how can I show that in a JOptionPane.
String c = JOptionPane.showMessageDialog(null
,for(d=1;d<=c;d++){
if(c%d==0){
d+" "
}
}
,"The factors of "+c+" are: "
,JOptionPane.INFORMATION_MESSAGE);

Thank you Petter Friberg for giving an answer, I found a solution to my problem thanks to you, although I didn't use all of your suggestions . So here's my code...
import java.util.*;
import javax.swing.*;
public class TestNo3{
public static void main(String[] args) {
JTextArea factorsArea = new JTextArea();
JTextField inputInt1 = new JTextField(5);
JPanel factorsPanel = new JPanel();
factorsPanel.add(new JLabel("Enter an integer: "));
factorsPanel.add(inputInt1);
int int1 = JOptionPane.showConfirmDialog(null, factorsPanel
,"Show the factors of a number."
,JOptionPane.OK_CANCEL_OPTION);
if(int1==JOptionPane.OK_OPTION){
String inputIntS = inputInt1.getText();
int inputIntI = Integer.parseInt(inputIntS);
for(int numB=1;numB<=inputIntI;numB++){
if(inputIntI%numB==0){
String outputS = String.format("%5d", numB);
factorsArea.append(outputS);
}
}
JOptionPane.showMessageDialog(null, factorsArea
,"The factors of "+inputIntI+" are: "
,JOptionPane.INFORMATION_MESSAGE);
}
}
}

Related

Optaplanner doesn't see my planning variable

So I have a class Cycle:
#PlanningEntity
public class Cycle {
private Integer START = 29;
private Integer END = 42;
private final int SUSTAIN_START = 29;
private final int SUSTAIN_END = 72;
#PlanningVariable(valueRangeProviderRefs = { "startRange" } )
public Integer getStartIndex() {
System.out.println("DEBUG: getStartIndex");
return START;
}
public void setStartIndex(Integer i) {
System.out.println("DEBUG: setStartIndex");
START = i;
END = i+13;
}
#ValueRangeProvider(id = "startRange")
public List<Integer> getStartIndexes () {
ArrayList<Integer> startRange = new ArrayList<Integer>();
for(int i = SUSTAIN_START; i < SUSTAIN_END; i++) {
startRange.add(i);
}
return startRange;
}
}
and Optplanner doesn't ever call any of these methods, and I have no clue why. I've tried adding a "#ProblemFactCollectionProperty" annotatation on the getStartIndexes method, but I read in the docs that that annotation should only be used within a PlanningSolution.
I've also tried using scanAnnotatedClasses and explicitly specifying the entityClass in my solver config and neither seemed to make a difference.
Why can't Optaplanner see my variable and why doesn't Optaplanner change it?
More Info: I'm using Optaplanner version 7.30.0.Final and I have another planning entity with two planning variables that are seen and changed by Optaplanner.
The problem, per #yurloc's comment, was that I was missing the PlanningEntityCollectionProperty for Cycles in my PlanningSolution class. Thanks for the help!

Method to check if number is contained in ArrayList will not work, NullPointerExcepton. Can you use ArrayList method inside a constructed method?

This is a project I am working on and it is supposed to take input from the user then which is an area code then see if it is contained in a array list. My method that I have created will not work in another class and I am not sure why, it is returning a NullPointerException.
The NullPointerException is shown at this line of code: if (mountainTime.contains(input))
This is the class with methods
package finalPro;
import java.util.ArrayList;
public class Final
{
public Final()
{
input = 0;
timezone = 0;
}
public void checkIfTrue(int y)
{
input = y;
if (mountainTime.contains(input))
{
timezone = 1;
}
else
timezone = 0;
System.out.println(timezone);
}
public int getZone()
{
return timezone;
}
public ArrayList<Integer> mountainTime;
private int input;
private int timezone;
}
Here is test class
package finalPro;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class FinalLogic
{
public static void main(String[] args)
{
ArrayList<Integer> mountainTime = new ArrayList<Integer>();
mountainTime.add(480);
mountainTime.add(602);
mountainTime.add(623); //Arizona area codes
mountainTime.add(928);
mountainTime.add(520);
mountainTime.add(303);
mountainTime.add(719); //Colorado
mountainTime.add(720);
mountainTime.add(970);
mountainTime.add(406); //Montana
mountainTime.add(505); //New Mexico
mountainTime.add(575);
mountainTime.add(385);
mountainTime.add(435); //Utah
mountainTime.add(801);
mountainTime.add(307); //Wyoming
Final myMap = new Final();
{
String x = JOptionPane.showInputDialog("Please enter a number: ");
int input = Integer.parseInt(x);
myMap.checkIfTrue(input);
}
}
}
I hope it's not too late, I haven't done anything special to fix your code, just some movement of code,
Removed the initialization logic from class FinalLogic to Final class .(btw Final name is not really good, you might be aware final is reserved word in Java. Although your name is case sensitive but still)
package finalPro;
import javax.swing.JOptionPane;
public class FinalLogic {
public static void main(String[] args) {
Final myMap = new Final();
String x = JOptionPane.showInputDialog("Please enter a number: ");
int input = Integer.parseInt(x);
myMap.checkIfTrue(input);
}
}
And here is your class Final
package finalPro;
import java.util.ArrayList;
public class Final {
public Final() {
input = 0;
timezone = 0;
// moved all initialization logic to constructor
mountainTime = new ArrayList<>();
mountainTime.add(480);
mountainTime.add(602);
mountainTime.add(623); // Arizona area codes
mountainTime.add(928);
mountainTime.add(520);
mountainTime.add(303);
mountainTime.add(719); // Colorado
mountainTime.add(720);
mountainTime.add(970);
mountainTime.add(406); // Montana
mountainTime.add(505); // New Mexico
mountainTime.add(575);
mountainTime.add(385);
mountainTime.add(435); // Utah
mountainTime.add(801);
mountainTime.add(307); // Wyoming
}
public void checkIfTrue(int y) {
input = y;
if (mountainTime.contains(input)) {
timezone = 1;
} else
timezone = 0;
System.out.println(timezone);
}
public int getZone() {
return timezone;
}
public ArrayList<Integer> mountainTime;
private int input;
private int timezone;
}
I tried in my workspace, it gives no NPE, Hope it helps.

MVEL extracting a string from a string

I have the strings "000134567 - AA - 2001" and "002134567 - AB - 2001" and I want to extract all the numbers before the " - AA". But I only want to return the numbers starting from the first non-zero number. For example, I would want "134567" or "2134567".
Is there some function that would allow me to do this using MVEL? Any help is appreciated.
I do not think directly we can use MVEL for this, but yes tweaking little bit might help us.
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;
public class MyTest {
public static void main(String[] args) {
String myString = "000134567 - AA - 2001";
Map contextMap = new HashMap();
contextMap.put("myString", myString);
ParserContext ctx = new ParserContext();
ctx.addPackageImport("java.util.regex");
Serializable s = MVEL.compileExpression("outputString(myString)", ctx);
System.out.println(MVEL.executeExpression(s, contextMap, getMvelFactory(contextMap)));
}
private static VariableResolverFactory getMvelFactory(Map contextMap) {
VariableResolverFactory functionFactory = new MapVariableResolverFactory(contextMap);
MVEL.eval(
"outputString = def (myString) { java.util.regex.Pattern p = java.util.regex.Pattern.compile(\"[0-9]+\"); java.util.regex.Matcher m = p.matcher(myString); if (m.find()) { String output = m.group(); return output.replaceAll(\"^0+\", \"\");}};",
functionFactory);
return functionFactory;
}
}
Function
Below is my function written in java which i have included inside Mvel VariableResolverFactory.
outputString = def (myString) {
java.util.regex.Pattern p = java.util.regex.Pattern.compile("[0-9]+");
Matcher m = p.matcher(myString);
if (m.find()) {
String output = m.group();
return output.replaceAll("^0+", "");
}
};
Creating Parser Context and adding import
Since java.util.regex package is not available with MVEL, so we will import this package explicitly.
ParserContext ctx = new ParserContext();
ctx.addPackageImport("java.util.regex");
Compiling Expression using above Import
This will just compile the expression and will add imports for later use while evaluation.
Serializable s = MVEL.compileExpression("outputString(myString)", ctx);
Varying variable
You can pass through your variables as below,
Map contextMap = new HashMap();
contextMap.put("myString", myString);
Rest you can change the function body, signature and return statement as per your needs.

Trying to use PlaceRequest the right way

i have two Presenters: A DevicePresenter and a ContainerPresenter. I place a PlaceRequest in the DevicePresenter to call the ContainerPresenter with some parameters like this:
PlaceRequest request = new PlaceRequest.Builder()
.nameToken("containersPage")
.with("action","editContainer")
.with("containerEditId", selectedContainerDto.getUuid().toString())
.build();
placeManager.revealPlace(request);
In my ContainersPresenter i have this overridden method:
#Override
public void prepareFromRequest(PlaceRequest placeRequest) {
Log.debug("prepareFromRequest in ContainersPresenter");
super.prepareFromRequest(placeRequest);
String actionString = placeRequest.getParameter("action", "");
String id;
//TODO: Should we change that to really retrieve the object from the server? Or should we introduce a model that keeps all values and inject that into all presenters?
if (actionString.equals("editContainer")) {
try {
id = placeRequest.getParameter("id", null);
for(ContainerDto cont : containerList) {
Log.debug("Compare " + id + " with " + cont.getUuid());
if(id.equals(cont.getUuid())) {
containerDialog.setCurrentContainerDTO(new ContainerDto());
addToPopupSlot(containerDialog);
break;
}
}
} catch (NumberFormatException e) {
Log.debug("id cannot be retrieved from URL");
}
}
}
But when revealPlace is called, the URL in the browser stays the same and the default presenter (Home) is shown instead.
When i print the request, it seems to be fine:
PlaceRequest(nameToken=containersPage, params={action=editContainer, containerEditId=8fa5f730-fe0f-11e3-a3ac-0800200c9a66})
And my NameTokens are like this:
public class NameTokens {
public static final String homePage = "!homePage";
public static final String containersPage = "!containersPage";
public static final String devicesPage = "!devicesPage";
public static String getHomePage() {
return homePage;
}
public static String getDevicesPage() {
return devicesPage;
}
public static String getContainersPage() {
return containersPage;
}
}
What did i miss? Thanks!
In your original code, when constructing your PlaceRequest, you forgot the '!' at the beginning of your nametoken.
.nameToken("containersPage")
while your NameTokens entry is
public static final String containersPage = "!containersPage";
As you noted, referencing the constant in NameTokens is less prone to such easy mistakes to make!
Sometimes the problem exists "between the ears". If i avoid strings but use the proper symbol from NameTokens like
PlaceRequest request = new PlaceRequest.Builder()
.nameToken(NameTokens.containersPage)
.with("action","editContainer")
.with("containerEditId", selectedContainerDto.getUuid().toString())
.build();
it works just fine. Sorry!

Check for array index to avoid outofbounds exception

I'm still very new to Java, so I have a feeling that I'm doing more than I need to here and would appreciate any advise as to whether there is a more proficient way to go about this. Here is what I'm trying to do:
Output the last value in the Arraylist.
Intentionally insert an out of bounds index value with system.out (index (4) in this case)
Bypass the incorrect value and provide the last valid Arraylist value (I hope this makes sense).
My program is running fine (I'm adding more later, so userInput will eventually be used), but I'd like to do this without using a try/catch/finally block (i.e. check the index length) if possible. Thank you all in advance!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex02 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader(new InputStreamReader(
System.in));
try {
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Zero");
myArr.add("One");
myArr.add("Two");
myArr.add("Three");
System.out.println(myArr.get(4));
System.out.print("This program is not currently setup to accept user input. The last printed string in this array is: ");
} catch (Exception e) {
System.out.print("This program is not currently setup to accept user input. The requested array index which has been programmed is out of range. \nThe last valid string in this array is: ");
} finally {
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Zero");
myArr.add("One");
myArr.add("Two");
myArr.add("Three");
System.out.print(myArr.get(myArr.size() - 1));
}
}
}
Check for array index to avoid outofbounds exception:
In a given ArrayList, you can always get the length of it. By doing a simple comparison, you can check the condition you want. I haven't gone through your code, below is what i was talking-
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("stringA");
list.add("stringB");
list.add("stringC");
int index = 20;
if (isIndexOutOfBounds(list, index)) {
System.out.println("Index is out of bounds. Last valid index is "+getLastValidIndex(list));
}
}
private static boolean isIndexOutOfBounds(final List<String> list, int index) {
return index < 0 || index >= list.size();
}
private static int getLastValidIndex(final List<String> list) {
return list.size() - 1;
}