Instantiating an object in array list [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
An example of a method that uses a normal array object.
public static void free Customer(customer[] customers, supplement[] supplements)
{
for(int i=0;i<customers.length;i++)
{
customers[i]=new customer();
customers[i].read Input();
for(int s=0;s<supplements.length;s++)
{
supplements[i]=new supplement();
supplements[i].read Input();
}
}
}
My question is, how do i convert this --> customers[i]=new customer();
and this --> customers[i].read Input(); into a valid Array list code?
I tried putting customers[i]=new customer(); & customers[i].read Input();
into the method below but the compiler returns an error saying that
"Array List required but array found"
This is a skeleton of the free Customer method that is using Array list.
public static void free Customer(Array List<customer> customers,
Array List<supplement>supplements)
{
for(int i=0;i<customers.size();i++)
{
}
}

Do it as follows:
public static void freeCustomer(ArrayList<customer> customers, ArrayList<supplement>supplements) {
for(int i=0;i<customers.size();i++) {
customers.set(i, new customer());
customers.get(i).readInput();
}
}

Related

this code of mine has no error but it isnt showing any output [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
In this code the method setEid isn't working dont know what's the problem with while loop
this code of mine has no error but it isnt showing any output
public class Emp {
private String eid;
public String getEid() {
return eid;
}
public void setEid(String e) {
while (e.length() < 12) {
eid = e;
}
}
}
public class Test {
public static void main(String[] args) {
Emp z = new Emp();
z.setEid("rgrge");
System.out.println("\n" + z.getEid());
}
}
enter code here i expect the static initialization of setEid argument should not take more than 12 characters
Your setter method have a while loop if eid length is less than 12 then it always stuck in this method.
public void setEid(String e){
while(e.length()<12)
eid=e;
}
and In your main method
public static void main(String[] args) {
Emp z=new Emp();
z.setEid("rgrge"); // you call setter
System.out.println("\n"+z.getEid());
}
you pass "rgrge" in setter and its length is less than 12. Tht's why your program is stuck in loop and not showing any thing.
Change setter implementation to this.
public void setEid(String e){
if(e.length()<12) // change while to if
eid=e;
}
so first there should have had if instead of while.
Change:
while(e.length()<12) change this as if(e.length()<12)
Explanation:
your setEid method never going to run because there is no break condition there. your while loop condition tends to the infinite. your code gets stuck in that while loop.
here you passed z.setEid("rgrge");. in your example, Length of string e is 5 which is obviously less than 12, so the condition will always be satisfied and your program will be stuck in infinite loop.

Where is the solution stub in this program and how would I call a method in it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is a specific question, don't downvote it just because it doesn't help you.
public class Answer {
public static String answer(int n) {
String nums="";
int limit = 10005;
int x=2;
while(limit>0){
if(isPrime(x)){
limit-=String.valueOf(x).length();
nums = nums + String.valueOf(x);
}
x+=1;
}
String out="";
if(n==0){
out="23571";
}else{
for(int i=1;i<6;i++){
out += String.valueOf(nums.charAt(n+i));
}
//Problem Solved: instead of this loop, it should be out = nums.substring(n,n+5)
}
return out;
}
public static boolean isPrime(int number) {
for(int check = 2; check < number; ++check) {
if(number % check == 0) {
return false;
}
}
return true;
}
}
Nothing is wrong with this code as far as I know, I'm just using it as an example for you to use.
"It must implement the answer() method in the solution stub." was in the directions for me, but I don't know much about the vocabulary of programming, I only understand logic behind programming, so this is the only thing I don't know how to solve. So what I am asking is where do I put the "answer()" at in this program?
It was looking for substring, which I didn't include because I haven't used java in about a year and simply forgot about it.
Here as I can figure out you have problems in understanding the meaning of "stub". It is simply the test method as provided by the answer here. And if you want to test the above code you have to implement the main method in your code to do the same. Something like this
public static void main(String [] args){
//Either use Scanner object or provide the hard coded input as per your requirements
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(answer(n));
}
EDIT AS PER OP REQUIREMENT
Okay so as per your requirement it is asking you for the unit test. There are many ways to do it but my preferred is to make stub concrete class
Implementation an stub concrete class in JUNIT
class Answer {
public String answer(int n){
// Code body
return "result"// in your case out variable
}
}
class solution extends Answer {
#Override
public String answer(int n){
//return "your stubbed result";
}
}

Receiving parameter for an array of objects from another class in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create one array of objects of my class Percurso for another class Custos, but I don't know how to do this. Here is what is asking in the question:
Receives as parameter an array of path-type objects
My code :
Class Custos :
public class Custos {
public String calcularViagem(Percurso [] p) {
return "";
}
}
Class Percurso :
private double kmPercorrida;
private double valorCombustivel;
private double valorPedagio;
public double getKmPercorrida() {
return kmPercorrida;
}
public void setKmPercorrida(double kmPercorrida) {
this.kmPercorrida = kmPercorrida;
}
public double getValorCombustivel() {
return valorCombustivel;
}
public void setValorCombustivel(double valorCombustivel) {
this.valorCombustivel = valorCombustivel;
}
public double getValorPedagio() {
return valorPedagio;
}
public void setValorPedagio(double valorPedagio) {
this.valorPedagio = valorPedagio;
}
public Percurso() {
this(0,0,0);
}
public Percurso(double kmPercorrida, double valorCombustivel,
double valorPedagio) {
this.kmPercorrida = kmPercorrida;
this.valorCombustivel = valorCombustivel;
this.valorPedagio = valorPedagio;
}
How can I do this ? If someone can help, I will thanks.
PS: Before someone say that this post is similar to other questions about array, it's not,I looked for questions similar that could help and I didn't found any that really could help me.
Creating an array of Percurso objects is the same as creating an array of any object. To create the array, you will need to include a line like this:
Percurso[] percursoArray = new Percurso[LENGTH]; //with your own array name and length
However, that just creates an array; it doesn't put anything in it. To put Percurso objects in the array (or, more accurately references to the objects), you need code like this.
percusoArray[0] = new Percurso(5, 2, 1);
percusoArray[1] = new Percurso(1, 1, 1); //etc
Or, if the array is long, you could create the objects in a for loop:
for (int i = 0; i < LENGTH; i++){
percusoArray[i] = new Percurso(1,2,3); //with your own values
}
Of course, a question remains-- where should you put this code? Is the array of Percurso an attribute of Custos? If so, you might create the array as a class variable of Custos and populate it in the constructor for Custos. If it's not an attribute of Custos, but rather just a parameter for one of Custos methods, you'll need this code in whichever part of your code calls calcularViagem(), whether that is another method in Custos, a method in another class, or from inside your main method.

Vector Method Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am trying to create a vector method called readfromfile which would potentially read the input from a different text file. Why does it give an error?
Edit: Thanks for the help, I have edited the code and it works!
Looks like I was confusing parameters and methods! :P
Thanks guys :D
package cas.lab1.firsteclipsePackage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Vector;
public class FirstEclipseClass {
public static void main(String[] args) {
Vector input = new Vector();
input.add("A");
input.add("B");
input.add("C");
input.add("D");
printVectorElements(input, 3);
Vector<String> results = readFromFile();
}
public static void printVectorElements(Vector input, int count) {
for (int i = 0; i < count; i++) {
System.out.println(input.get(i));
}
}
public static Vector<String> readFromFile(){ //yeah I did confuse methods and parameters
Vector<String> result = new Vector<String>();
try{
File f = new File("input.txt");
Scanner s = new Scanner(f);
while(s.hasNextLine()) {
int i = s.nextInt();
if(i % 2 == 0)
result.add("Even");
else
result.add("Odd");
System.out.println(i);
}
s.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
return result;
}
}
I guess that you are confused here. From your method call, I see that you don't need to pass any parameters, and instead want a Vector back. So I suggest you to change this line:
public static readFromFile(Vector<String> results){
To this line:
public static Vector<String> readFromFile(){
First thing: you didn't specified the return type. You should have :
public static Vector<String> readFromFile()
if you do not need any parameters in the function.
Second, for future, you cannot have this same name in the function and as a function parameter

how can we compare two list? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have 2 lists of classes namely StuPersonal of Database1,StuPersonal of Database2 of different size.
public List<StuPersonal> stpers(){
int size=0;
Session s=getmSession();
Transaction tx=s.beginTransaction();
List<StuPersonal> splM=new ArrayList();
Query q=s.createQuery("from StuPersonal");
splM=q.list();
tx.commit();
s.close();
return splM;
}
public List<StuPersonal> stpersl(){
int size=0;
List<StuPersonal> splL=new ArrayList();
Session s=getlSession();
Transaction tx=s.beginTransaction();
List<StuPersonal> spl=new ArrayList();
Query q=s.createQuery("from StuPersonal");
splL=q.list();
tx.commit();
s.close();
return splL;
}
Now i have to compare both the lists and need to take the items which are not in the presented in the second list.i.e some objects are not in the class 2 list so it needs to be stored. I have written this code which is not working properly. Please advice.
for(StuPersonal cl:sp)
{
for(StuPersonal cl2:sp2)
{
if(cl.getid().equals(cl2.getid()))
{
//i++;
break;
}
else
{
fun.updatelist(cl.getid());
break;
}
}
}
You are Checking the ID of List object not the Class_1 Object Id
if(cl.getid() == cl2.getid())
{
//i++;
break;
} else
{
fun.updatelist(cl2.getid());
break;
}
And you are using equals method, considering id as long not String.
You're not helping yourself by choosing awful names for your variables and methods, not respecting the standard naming conventions, and not correctly indenting your code.
Anyway, you should try to write short methods that do one thing only, and that represent the steps in your task. Your task is to produce a list of objects that are present in list1 but are not in present in list 2. And "being present" here means "an object with the same ID exists in the list".
So start by writing a method isPresent():
/**
* Returns true if an object with the same ID as the ID of the given object is
* present in the given list
*/
private boolean isPresent(StuPersonal object, List<StuPersonal> list) {
for (StuPersonal candidate : list) {
if (candidate.getId().equals(object.getId()) {
return true;
}
}
return false;
}
Now you can use this method in your algorithm:
// start with an empty list
List<StuPersonal result = new ArrayList<>();
// add every element of list1 unless it's present in list2
for (StuPersonal s : list1) {
if (!isPresent(s, list2)) {
result.add(s);
}
}
Here is an example with String for your scenario.
List<String> firstList = Arrays.asList("obj1", "obj2", "obj3");
List<String> secondList = Arrays.asList("obj1", "obj2", "obj3", "obj4", "obj5");
List<String> storedList = new ArrayList<String>();
for (String obj2 : secondList) {
if (!firstList.contains(obj2)) {
storedList.add(obj2);
}
}

Categories