John_165 44 Junior Poster

Use a for loop to find the smallest integer n such that n^3 is greater than 1000

So I came out with below code

public class Chapter4 {
    static int n = 0;
    public static void main(String[] args) {
        for (int i = 1; Math.pow(i, 3) <= 1000; i++) {
            n = i;
        }
        System.out.println("Smallest i is " + n);
    }
}

I get value answer 21 which looked like not the smallest integer. What is wrong with my logic ? I thought the value n should be 10 ?

John_165 44 Junior Poster

Which post/code are you referring to - there's Java, Ruby, APL and English so far.

The code you posted 16 hours ago

John_165 44 Junior Poster

What language is that ?

John_165 44 Junior Poster

JamesCherrill: Very nicely done John.

Thanks James.

John_165 44 Junior Poster

Thanks all . I finally solved it.

      import java.util.Scanner;

        public class Chapter4 {

            public static void main(String[] args) {
                final int NUMBER_PER_LINE = 5;
                Scanner input = new Scanner(System.in);
                int count = 0;
                int firstNumber = 0;
                int secondNumber = 0;
                System.out.print("Enter first number: ");
                firstNumber = input.nextInt();
                System.out.print("Enter second number: ");
                secondNumber = input.nextInt();

                for (int i = firstNumber; i < secondNumber + 1; i++) {
                    if ((i % 3 == 0) && (i % 4 == 0)) {
                        count++;
                        if (count % NUMBER_PER_LINE == 0) {
                            System.out.println(i);
                        } else {
                            System.out.print(i + "  ");
                        }

                    }
                }
            }  
}
JamesCherrill commented: Very nicely done John. +14
John_165 44 Junior Poster

Thanks guys for all the feedback. Just wonder how can I reply a comment ?

John_165 44 Junior Poster

Write a program that displays all numbers divisible by 3 and 4 within a range entered by user. Display five numbers per line. Numbers are separated by exactly two spaces.

This is my code

        public class Chapter4 {
            public static void main(String[] args) {
                Scanner input = new Scanner(System.in);
                final int NUMBER_OF_PRIMES_PER_LINE = 5;
                int count = 0;
                int[] vars = new int[10];

                for (int i = 0; i < vars.length; i++) {
                    System.out.println("Enter " + (i + 1) + " numbers: ");
                    vars[i] = input.nextInt();

                    if ((vars[i] % 3 == 0) && (vars[i] % 4 == 0)) {
                        count++;
                    }

                    if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
                        System.out.println(vars[i]+"  ");
                    }
                }
            }    
   }

I input value 120 10 times, but I only get one 120 displayed at the end.

John_165 44 Junior Poster

But how can I get the rows number so the second parameter become valid ?? Was pulling my hair out of this !

I have move some code and here the latest

public void stateChanged(ChangeEvent e) {
        int quantity = (int) ((JSpinner) e.getSource()).getValue();
        int rows = 0;

        for (int i = 0; i < ELEMENTS; i++) {
            if (numspinner[i] == e.getSource()) {
                if (quantity == 1) {
                    System.out.println("Row"+rows);
                    rows = table.getRowCount();
                    dtm.addRow(new Object[] { foodLabel[i].getText(), quantity, price[i] * quantity });
                } else {
                    System.out.println(" The Row"+rows);
                    dtm.setValueAt(quantity, rows, 1); // obj,column,row
                }
            }
        }   
}

If the quantity is 1, it adds row as expected. When click the same JSpinner again, it always display 0

John_165 44 Junior Poster

I don't know your design, so I don't know wha the "specific row" is.
What I can say is that if rows is (eg) 2, then the valid values for the second parameter are 0 and 1, but not 2. ie, the first row is row 0 and the second row is row 1, there is no row 2.

Can you explain why I will get Row1 and Row2 when I click the JSpinner more than once ?

I want to change the Noodles quantity to 2, but it display errors.

Attach with my image screen shot

John_165 44 Junior Poster

Just a guess:
Its line 12 that's the problem. rows is the number of rows, so valid values for the second parameter should be 0 to (rows-1)

Yes, the error is pointed to line 12. How can I solve that ? I want to change the value in the specific row

John_165 44 Junior Poster

I have multiple JSpinner which have items 1-10 , and one JTable. When the JSpinner is clicked, the value will be added to JTable. I want to get the row number so I can use it at setValueAt. But I get error when the JSpinner clicked more than once times.

Code

    public void stateChanged(ChangeEvent e) {  // when JSpinner clicked
            int quantity = (int) ((JSpinner) e.getSource()).getValue();
            int rows = table.getRowCount();

            for (int i = 0; i < ELEMENTS; i++) {
                if (numspinner[i] == e.getSource()) {
                    if (quantity == 1) {
                        System.out.println("Row"+rows);
                        dtm.addRow(new Object[] { foodLabel[i].getText(), quantity, price[i] * quantity });
                    } else {
                        System.out.println("Row"+rows);
                        dtm.setValueAt(quantity, rows, 3); 
                    }
                }
            }
        }

I clicked the same JSpinner more then once and get this output

Row1
Row2

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
        at java.util.Vector.elementAt(Unknown Source)
        at javax.swing.table.DefaultTableModel.setValueAt(Unknown Source)
        at gui.FoodOrdering.stateChanged(FoodOrdering.java:250)
        at javax.swing.JSpinner.fireStateChanged(Unknown Source)
        at javax.swing.JSpinner$ModelListener.stateChanged(Unknown Source)
        at javax.swing.AbstractSpinnerModel.fireStateChanged(Unknown Source)
        at javax.swing.SpinnerNumberModel.setValue(Unknown Source)
        at javax.swing.JSpinner.setValue(Unknown Source)
        at javax.swing.plaf.basic.BasicSpinnerUI$ArrowButtonHandler.actionPerformed(Unknown Source)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)

Any help would be appreciated.

John_165 44 Junior Poster

Line 142 - is the -- intentional?

What did you meant ?

John_165 44 Junior Poster

In my Food Tab, I wanted to achieve this
Click Here

But I only able to get this
Click Here

How can I increase the width of the JTextField which are in Food Tab ? Below is my code

public class FoodOrdering {

    static private JFrame frame;
    static private JTextField textField;
    static private GridBagConstraints gbc;
    static private JLabel[] foodLabel;
    static private JLabel[] labels;
    static private JTextField[] qtyField;
    static private JLabel[] foodImage;
    static private File[] file;
    private static final int ELEMENTS = 9;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    FoodOrdering window = new FoodOrdering();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     * 
     * @throws IOException
     */
    public FoodOrdering() throws IOException {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     * 
     * @throws IOException
     */
        static void initialize() throws IOException {
        frame = new JFrame();
        frame.setBounds(100, 100, 700, 550);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        frame.setLocationRelativeTo(null);

        JLabel lblFoodOrdered = new JLabel("Food Ordered");
        lblFoodOrdered.setBounds(529, 11, 81, 14);
        frame.getContentPane().add(lblFoodOrdered);

        TextArea textArea = new TextArea();
        textArea.setBounds(462, 31, 199, 275);
        frame.getContentPane().add(textArea);

        JLabel lblTotal = new JLabel("Total  : ");
        lblTotal.setBounds(519, 315, 46, 14);
        frame.getContentPane().add(lblTotal);

        textField = new JTextField();
        textField.setBounds(575, 312, 86, 20);
        frame.getContentPane().add(textField);
        textField.setColumns(10);

        JButton btnOrder = new JButton("Order");
        btnOrder.setBounds(521, 352, 89, 23);
        frame.getContentPane().add(btnOrder);

        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        addIt(tabbedPane, "Foods");
        addIt1(tabbedPane, "Drinks");
        addIt1(tabbedPane, "Desserts");
        tabbedPane.setBounds(23, 11, 400, 450);
        frame.getContentPane().add(tabbedPane);

        frame.setVisible(true);
    }

    static void addIt1(JTabbedPane tabbedPane, String text) {
        JLabel …
John_165 44 Junior Poster

There's an active discussion ongoing in S.O. for this question, so there's no need to reply here until/unless OP comes back first.

Yes,I am here

John_165 44 Junior Poster

I wonder how to handle exception in ResponsesEntity.
When it receive wrong url, it supposes to go to the catch block and display the log. But I keep getting error message in console. The try-catch not working as it not display log message.

 @GetMapping("abc/{Id}")
        public ResponseEntity info(@PathVariable("Id") String id) {
            HttpEntity httpEntity = new HttpEntity(buildHttpHeaders());
            String theUrl = url + "/xxx ...";
            ResponseEntity<TDto> responseEntity = restTemplate.exchange(theUrl, HttpMethod.GET, httpEntity, TDto.class);
            TDto tdto = responseEntity.getBody();
            Tran tran = new Tran();
            try {
                  tran.setDate(new Date());
                  tran.saveAndFlush(tran); // save to database
            }catch(Exception e)
            {
                log.info("Log: "+e);
            }
            return responseEntity;
        }

Error

    org.springframework.web.client.HttpClientErrorException: 404 Not Found
        at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
        at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
        at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
        at com.rh.tranglo.controller.ApiController.retrieveTransactionInfo(ApiController.java:41)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)

Is there a way to handle exception by displaying the log in catch block?

Also posted at https://stackoverflow.com/questions/44952572/handle-exception-in-responsesentity-java

John_165 44 Junior Poster

You have to use third-party to connect Android with MySQL

John_165 44 Junior Poster

Hi John!! Welcome to DaniWeb :)

Thanks Dani . Why I not getting any notifications if someone has replied my post ?

John_165 44 Junior Poster

Morning and welcome to DaniWeb...

Thanks for the warm welcome. Is afternoon here

John_165 44 Junior Poster

A guy come from Malaysia, just want to say hi with you all :)