jeudi 27 avril 2017

Method help- beginners mistakes

import java.util.*;
public class Problem5
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Number();
}
}
public int Number()
{
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}

I'm having a lot of trouble writing methods in terms of the method signature.

The errors I'm getting typically involve "error: class, interface, or enum expected" on the receiving or returning types.

In this case, the errors are on the returning aspect in the method signature and then later within the method when trying to return an int.

Can anyone could explain what I'm doing wrong?




Which is better practice? Using private variables or public methods within the class?

Example:

private int x = 4;

public TestClass(int x) {
    this.x = x;
}

public TestClass(int x) {
    setX(x);
}

public void setX(int x) {
    this.x = x;
}

Is the first constructor better practice or the second? I'm asking this because when I encapsulate my classes in IntelliJ IDEA if I used this.x = x before, it changes it to setX(int newX);.




Java calling array from another class

i am new to java so please be gentle. i am trying to store arrayList of objects to txt file created from array ipvalue[] that instantiated in another class. now my problem is that whenever i try to load the array from Mainframe class to Arraystorage class it displays the entire array as null outputs. i guess the problem is that the array data is generated within the Mainframe method. and when i call the array from another class it simply takes the array as it is initialized so my question is how can i access the array after it is assigned with values and not as initialized

new String[50] mainframe class:

public class Mainframe extends javax.swing.JFrame {
static int ipcounter = 0;
public static String[] ipvalue = new String [50];


/**
 * String a[]Creates new form Mainframe
 */
    public Mainframe() {
         try {
        initComponents();
        this.setLocation(500,250);
        Nettest.main(null);
        Display.setText(Nettest.indicator);
        Arraystorage.main(null);
        Path path = Paths.get("ipcounter.txt");

         File file = new File("ipcounter.txt");


         FileReader in = new FileReader("ipcounter.txt");
        BufferedReader br = new BufferedReader(in);

        readline = Integer.parseInt(br.readLine()); 
        in.close();
        ipcounter = readline;

         if(ip.tracker.Nettest.status == true){
         ipvalue[ipcounter] = Readipfromurl.inputLine;
       //  crosscheck();

        Writer writer = null;
         writer = new BufferedWriter(new OutputStreamWriter(
         new FileOutputStream("ipcounter.txt"), "utf-8"));
          writer.write(String.valueOf(ipcounter+1));

          writer.close();
         System.out.println(ipvalue[ipcounter]);
          ipcounter++;


arraystorage class:


public class Arraystorage implements Serializable{
   public static void main(String[] args) throws 
 ClassNotFoundException { 

   ArrayList<String> list = new ArrayList<String>();
  for (int i=0; i<50;i++){
  list.add(Mainframe.ipvalue[i]);}
   try {
       PrintWriter out = new PrintWriter(new BufferedWriter(new 
  FileWriter("data.txt")));
   for( int x = 0; x < list.size(); x++)
 {
 out.println(list.get(x));
 }

   out.close();


   } catch (IOException ex) {

 Logger.getLogger(Arraystorage.class.getName()).log(Level.SEVERE, 
null, ex);
   }




Singleton Implementation: counter not incrementing as expected with multiple pointers to instance

The following program aims to instantiate and use the singleton pattern class proposed by Loki Astari and accepted as answer at the following link. C++ Singleton design pattern

Note the addition of a simple counter, by way of the private counter variable, along with the increment() mutator, and getCtr() accessor methods.

Expected program output is:

0
1
Press any key to exit...

The actual output is

0
0
Press any key to exit...

Why is the counter in the singleton class not being incremented as expected?

What follows is a minimal, complete, and verifiable program, written to illustrate the issue.

#include "stdafx.h"
#include <iostream>
#include <string>

class S {
public:
    static S & getInstance() {
        static S instance;
        instance.counter = 0; // initialize counter to 0
        return instance;
    }
    S(S const &) = delete;
    void operator = (S const &) = delete;

    void increment() { ++counter; }
    int getCtr() { return counter; }
private:
    S() {}
    int counter;
};

int main() {
    S * s; // s is a pointer to the singleton object
    S * t; // t is another pointer to the singleton object.

    std::cout << s->getInstance().getCtr() << std::endl;
    s->getInstance().increment(); // increment counter
    std::cout << t->getInstance().getCtr() << std::endl;

    std::cout << "Press any key to exit...";
    std::cin.get();
    return 0;
}

Thx, Keith :^)




Is it possible to have two way composition in python?

First off I am very sorry if this is the wrong way to ask this question so please don't rip me. What I am trying to do is something very similar to the following.

class Driver:
    def __init__(self):
        self.kind = "Driver"
    def class_of_driver(self):
        if self.model == 'corvette':
            print('fast')
class Car:
    def __init__(self, brand, model, cost, color):
        self.brand = brand
        self.model = model
        self.cost = cost
        self.color = color
        self.drivers = Driver()

I want to be able to create the object like this:

corvette = Car('chevy','corvette','200','red')

Then ulitmately be able to do something like:

corvette.class_of_driver

or

corvette.class_of_driver()

and get the return of fast in this scenario. I have been messing with this for an hour and so and becoming stuck. I know I can pass self into itself like:

self.drivers = Driver(self)

But of course if the object changes in the future it will not reflect this change.

Any advice would be greatly appreciated and let me say thank you in advance.




How to call function inside class

i have a problem with calling function inside my class

So, this is my code

<?php 

class JESUS {

public $Name = [];

public function Update($name,$ver,$desc){
    $var = "Name: ".$name." Version: ".$ver." Description: ".$desc."";
    array_push($this->Name, $var);
}

Update('test1','test2','test3');

}

?>

And Update function is not working. Can you tell me how can i make it work?




insert into std::map using class method

I searched a lot for this issue, but didn't find anything, so sorry if it's duplicate.

I have a problem with inserting into std::map using class method which returns *this. If i try to insert more values, only the first one is actually inserted. Let me show you my code:

using namespace std;

class test{
public:
   test(){}
   test Add(const int &a, const  int &b);
   void print(){
    for (auto it = map1.begin(); it != map1.end(); ++it) {
        cout << it->first << " " << it->second << endl;
    }
}

private:
   map<int,int> map1;

};

test test::Add(const int &a, const int &b) {

map1.insert(make_pair(a,b));

return *this;

}

But when i try something like this:

int main ( void ) {

test a;

a.Add(1,5) . Add( 4, 8);

a.print();

return 0;
}

only the first value is inserted into the map. What should i change to insert into map this way?

Thank you very much for your help.