-4

OK, so what I want to do is create 2 classes. One is main class and the second class is to make a loop sentinel control and then return the total of it till the user enters 0. I couldn't get it to work. I don't know how to call the other class because I'm very new to Java. Here's what I have.

Class 1:

import java.util.*;

public class HW3 {

public static void main(String[] args) {

    OrderDetails object = new OrderDetails();
    int n;
    n = object.OrderDetails(0);
    System.out.println(n);

Class 2:

import java.util.*;

public class OrderDetails {

Scanner input = new Scanner(System.in);

int total=0;

int n1;

public int OrderDetails(int n1){

    while (n1 != 0){

        System.out.println("Enter your number");

        n1 = input.nextInt();

        total += n1;

    } // End while loop

    return total;

} // End method
Hikkup
  • 13
  • 4

2 Answers2

1

First of all

public int OrderDetails(int n1)

You are using the name of the class as the method name, it will work and run but some IDE will complain on it that you are using the name of the class as a method that you need to change it as a constructor.

object.OrderDetails(0);

Now the problem is that you are passing 0 which will break the while statement, instead pass a different value let say -1, so you will go inside the while loop and get some values from the user.

sample:

object.OrderDetails(-1); //change the name of your method
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
0

The n1 in the class scope is an instance variable, but the parameter n1 in the method is a local scope, and so it hides the instance variable. Also, the method is named the same as the class which is bad practice.

None of this is the problem - the real problem is the caller is calling with the one value that would stop it from entering the while loop. If you called with anything other than zero, you will see it produce the desired result.

Venkat Rangan
  • 385
  • 1
  • 2
  • 7