Jump to content

Halp for script kiddie? [solved]


Guy

Recommended Posts

Aim: Have 2 classes, 'testing' & 'test'. Testing is the main one while test is... not. Test is supposed to ask for an input, store it in a variable, output it, return it to testing, so testing can output it.

First time I've tried making 2 classes work together. Is there an easy way to let all classes share variables?

 

Test:

import java.util.Scanner;
public class test {
   void outputvars(){ 
       System.out.println("input");
       Scanner input = new Scanner(System.in);
       String inp = input.nextLine();
       System.out.println("tet"+inp);
   }
   void returna(){
       return inp;
   }
}

 

Testing:

public class testing {
   public static void main(String[] args) {
       test testout = new test();
       testout.outputvars();
       String lol = testout.returna();
       System.out.println(lol);
   }
}

 

Or, if my code is awful (which is likely..) if someone could show me the proper way to do it...

 

TL;DR integrating 2 classes together, sharing variables/returning values from secondary to main class

 

Cheers.

 

SOLUTION: Changed test to public void, and the second void to string. got an error in the second 'part' (not sure what it's called) saying it couldn't locate the var, so I put the input part outside of both 'parts'

RIP TET

 

original.png

 

"That which does not kill us makes us stronger." - Friedrich Nietzsche

Link to comment
Share on other sites

No need for testing to extend test, but you don't even have a constructor. Also don't print from the class, print from the calling object.

 

Try this:

 

import java.util.Scanner;
public class test {
   public string input2;
   public test(String input){
        input2 = input;
}
   public string getInput() 
         return input2;
   }
}

polvCwJ.gif
"It's not a rest for me, it's a rest for the weights." - Dom Mazzetti

Link to comment
Share on other sites

No need for testing to extend test, but you don't even have a constructor. Also don't print from the class, print from the calling object.

 

Try this:

 

import java.util.Scanner;
public class test {
   public string input2;
   public test(String input){
        input2 = input;
}
   public string getInput() 
         return input2;
   }
}

I know there isn't a need for 2 classes, but I was trying to work my head around integrating them together. What's a constructor? In the code you've got, will that work on its own? I can't see where you've 'defined the scanner' (ie. Scanner input = new Sca....)

I'm pretty new to java, could you explain what the text I quoted please... thanks :P

RIP TET

 

original.png

 

"That which does not kill us makes us stronger." - Friedrich Nietzsche

Link to comment
Share on other sites

Attempting OOP as the first concept you learn is a bad idea.

 

A basic overview is that you have a class that does certain operations, and in the main method you use the class (create an instance of the class object) and do what you need to there.

 

So scanner goes in main...really it's a bad example though since whatever you're trying to do doesn't need to be OOP at all.

polvCwJ.gif
"It's not a rest for me, it's a rest for the weights." - Dom Mazzetti

Link to comment
Share on other sites

I know basic java, but my knowledge is limited to arrays/if statements/loops. trying to expand my knowledge :shades:

 

cheers.

RIP TET

 

original.png

 

"That which does not kill us makes us stronger." - Friedrich Nietzsche

Link to comment
Share on other sites

Ok, well I'll do a basic example then (the animal one)

 

public class animal(){
    public animal(){
    }
}

public class dog extends animal(){
    public dog(){
    }
    public String bark(){
          return "woof woof";
    }
}

public class main(){
    public static void main(String[] args){
             dog d = new dog();
             System.out.println(d.bark());
    }

}

 

That's basically how you do it. You create a class (animal), with a constructor(what will automatically get called when you create an instance of the object (in main)). Then, you extend it (dog class) or just use the animal class. Then, in main, you create an instance of the class, and you can call the methods that way.

polvCwJ.gif
"It's not a rest for me, it's a rest for the weights." - Dom Mazzetti

Link to comment
Share on other sites

  • 3 weeks later...

For what you were trying to do, it's best to have the classes in the same package

e.g.

package com.test;
import java.util.Scanner;

public class Test {
   void outputvars(){ 
       System.out.println("input");
       Scanner input = new Scanner(System.in);
       String inp = input.nextLine();
       System.out.println("tet"+inp);
   }
   protected void returna(){
       return inp;
   }
}

 

then:

package com.test;

public class Testing {
   public static void main(String[] args) {
       Test testout = new Test();
       testout.outputvars();
       String lol = testout.returna();
       System.out.println(lol);
   }
}

Link to comment
Share on other sites

I think you may find this useful since you are delving directly into object-oriented programming right from the start.

 

[spoiler=Churchhilldowns.java]

Purpose/fucntion: Creates a Jframe that will allow the user to choose a post position as well as place a bet and then place the bet and post

 position into a ".dat" file for displaying in a JTable when the program is restarted. In addition, the program has JMenuBar items that will "Display"

 a preset text in a JTextField, a "Exit" selection for closing the program , and a final selection for clearing the program of any input. On top

 of that, the program has 2 JTextfields, 1 for the post position and the other for the bet, 5 JButtons, 4 buttons for the "post position", these

 buttons display their information in the first JTextField,and 1 for "Placing a Bet", and finally the program will have 1 JTable in which data from a

 ".dat" file will display text based upon what was input into the 2 Jtextfields and if nothing is in the ".dat" file nothing except the heading of the

 table will display; anything written to the ".dat" file will require a restart of the program before being displayed.

*/



import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.util.*;

import java.io.*;





public class ChurchHillDowns extends JFrame implements ActionListener

{

   private JTextField positionfield, betfield;

   private JButton postonebutton, posttwobutton, postthreebutton, postfourbutton, placebetbutton;

   private JLabel titleheading;

   private File file = new File("HorseBet.dat");











   public static void main(String[] args)

   {

       //create a new instance of the ChurchHilldowns JFrame

       ChurchHillDowns mainframe = new ChurchHillDowns();



       //set basic appearance configuration for mainframe

       mainframe.setVisible(true);

       mainframe.setTitle("Day at The Races");

       mainframe.setBounds(100, 100, 650, 400);

   }



   public ChurchHillDowns()

   {

       try

       {

          File file = new File("HorseBet.dat");

          boolean created = file.createNewFile();



          if(created)

          {

              //not existing then exists

          }



          else

          {

              //existing then nothing

          }

      }



      catch(IOException e)

      {

      }



       TableLab tabby = new TableLab("HorseBet.dat");



       //constructs the default close button and calls the method "buildingthemenu"

       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       setJMenuBar(buildingthemenu());



       //create the container

       Container cp = getContentPane();

       cp.setLayout(new BorderLayout());



       //create the topPanel and add a JTextField and JLabel to it

       JPanel topPanel = new JPanel(new GridLayout(2, 1));



       titleheading = new JLabel("Welcome to Racing at Churchhill Downs", JLabel.CENTER); titleheading.setFont(new Font("Times New Roman", Font.BOLD, 22));



       positionfield = new JTextField(55);



       topPanel.add(titleheading);

       topPanel.add(positionfield);



       //create the  button panel and add postonebutton, posttwobutton, postthreebutton, and postfourbutton to it

       JPanel buttonpanel = new JPanel();



       postonebutton   = new JButton("Post position one");   postonebutton.setBackground(new Color(255, 193, 037));

       postonebutton.addActionListener(this);



       posttwobutton   = new JButton("Post position two");   posttwobutton.setBackground(new Color(255, 193, 037));

       posttwobutton.addActionListener(this);



       postthreebutton = new JButton("Post position three"); postthreebutton.setBackground(new Color(255, 193, 037));

       postthreebutton.addActionListener(this);



       postfourbutton  = new JButton("Post position four");  postfourbutton.setBackground(new Color(255, 193, 037));

       postfourbutton.addActionListener(this);



       buttonpanel.add(postonebutton);

       buttonpanel.add(posttwobutton);

       buttonpanel.add(postthreebutton);

       buttonpanel.add(postfourbutton);



       //create the bottom panel that will have the betfield and placebetbutton

       JPanel midpanel = new JPanel(new GridLayout(2,1));



       betfield = new JTextField(55);



       placebetbutton = new JButton("Place your bet");

       placebetbutton.addActionListener(this);



       midpanel.add(betfield);

       midpanel.add(placebetbutton);



       //create the panel that will house all the other panels

       JPanel contentpanel = new JPanel(new BorderLayout());



       contentpanel.add(topPanel, BorderLayout.NORTH);

       contentpanel.add(buttonpanel, BorderLayout.CENTER);

       contentpanel.add(midpanel, BorderLayout.SOUTH);



       //add the panel and table to the container

       cp.add(contentpanel, BorderLayout.NORTH);

       cp.add(tabby, BorderLayout.CENTER);

   }



   public JMenuBar buildingthemenu()

   {

       //construct the JMenuBar items

       JMenuBar themenu  = new JMenuBar();

       JMenu filemenu    = new JMenu("File");

       JMenu editmenu    = new JMenu("Edit");



       //create the JMenu items

       JMenuItem displayitem = new JMenuItem("Display");

       JMenuItem closeitem   = new JMenuItem("Exit Program");

       JMenuItem clearitem   = new JMenuItem("Clear");



       //add the JMenuItems and JMenuBar items top the MenuBar

       themenu.add(filemenu);

       themenu.add(editmenu);

       filemenu.add(displayitem);

       filemenu.add(closeitem);

       editmenu.add(clearitem);



       //set keyboard shortcuts

       filemenu.setMnemonic('F');

       editmenu.setMnemonic('E');

       displayitem.setMnemonic('D');

       closeitem.setMnemonic('E');

       clearitem.setMnemonic('C');



       //add actionlisteners to the JMenuItem

       displayitem.addActionListener(



           new ActionListener()

           {

               public void actionPerformed(ActionEvent event)

               {

                   positionfield.setText("Choose the post position of the horse in Race 1, enter the bet in lower field, and then press the bet button.");

               }//close actionPerformed

           }//close ActionListener

                                    );



       closeitem.addActionListener(



           new ActionListener()

           {

               public void actionPerformed(ActionEvent event)

               {

                   System.out.println("Enjoy the races!");

                   System.exit(0);

               }//close actionPerformed

           }//close actionlistener

                                  );



       clearitem.addActionListener(



           new ActionListener()

           {

               public void actionPerformed(ActionEvent event)

               {

                   positionfield.setText("");

                   betfield.setText("");

               }//close actionPerformed

           }//close actionlistener

                                                        );



      return themenu;

   }



   public void actionPerformed(ActionEvent e)

   {

       //next four if statments check to see if any of the post buttons were clicked and sets the text of the JTextField to whatever matches

       if(e.getSource() == postonebutton)

       {

           positionfield.setText("Post position one");

       }



       if(e.getSource() == posttwobutton)

       {

           positionfield.setText("Post position two");

       }



       if(e.getSource() == postthreebutton)

       {

           positionfield.setText("Post position three");

       }



       if(e.getSource() == postfourbutton)

       {

           positionfield.setText("Post position four");

       }



       //check to see if the placebetbutton was clicked and then calls upon the betting() function

       if(e.getSource() == placebetbutton)

       {

           betting();



       }

   }



   private void betting()

   {

       try

       {

           String  position = positionfield.getText(), bet = betfield.getText();

           double vbet = Double.parseDouble(bet);

           BufferedWriter outer = new BufferedWriter(new FileWriter("HorseBet.dat", true));



           //makes sure that the user doesn't try to click the "Place a bet" button with 0, 1, > 19, and < 16 characters

           if(position.length() == 0 || position.length() > 19 || position.length() == 1 || position.length() < 16)

           {

               JOptionPane.showMessageDialog(this, "Please click one of the post buttons!");

           }



           //sends data to the file if nothing is wrong as well as sets the text of the positionfield

           else

           {

               positionfield.setText("You have placed $" + bet + " on the horse in " + position + ". Hope your horse wins!" );



               outer.write("$" + bet + " on the horse in " + position);

               outer.newLine();



               outer.close();

           }

       }



       //checks to make sure that the bet field has a number entered into it

       catch(NumberFormatException e)

       {

           JOptionPane.showMessageDialog(this, "The bet field must be numeric.");

       }



       //standard Input/Output Stream error prevention

       catch(IOException e)

       {

           JOptionPane.showMessageDialog(this, "File Input error!");

       }

   }

}



class TableLab extends JPanel

{

    TableLab(String dataFilePath)

    {

        JTable table;

        TableModel model;



        setLayout(new BorderLayout());



        model = new TableModel(dataFilePath);



        table = new JTable();

        table.setModel(model);

        table.createDefaultColumnsFromModel();



        JScrollPane scrollpane = new JScrollPane(table);

        add(scrollpane);

    }

}

 

 

 

[spoiler=TableModel.java]

import javax.swing.*;

import javax.swing.table.*;

import javax.swing.event.*;

import java.io.*;

import java.util.*;



public class TableModel extends AbstractTableModel

{

 protected Vector<Object> data;

 protected Vector<Object> columnNames;

 protected String datafile;



 public TableModel(String f)

 {

	 datafile = f;



	 initVectors();

 }



 public void initVectors()

 {

	 String aLine;



	 data = new Vector<Object>();

	 columnNames = new Vector<Object>();



	 try

	 {

		 FileInputStream fin = new FileInputStream(datafile);



		 BufferedReader br = new BufferedReader(new InputStreamReader(fin));



		 columnNames.addElement("Bet");



		  //extract data



		  while((aLine = br.readLine()) != null)

		  {

			  StringTokenizer st1 = new StringTokenizer(aLine, "|");

			  while(st1.hasMoreTokens())



			  data.addElement(st1.nextToken());

		  }



		  br.close();

	  }



	  catch(Exception e)

	  {

		  e.printStackTrace();

	  }

  }



  public int getRowCount()

  {

	  return data.size() / getColumnCount();

  }



  public int getColumnCount()

  {

	  return columnNames.size();

  }



  public String getColumnName(int columnIndex)

  {

	  String colName = "";



	  if(columnIndex <= getColumnCount())



	   colName = (String)columnNames.elementAt(columnIndex);



	  return colName;

  }



  public boolean isCellEditable(int rowIndex, int columnIndex)

  {

	  return false;

  }



  public Object getValueAt(int rowIndex, int columnIndex)

  {

	  return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);

  }

}

 

 

 

[spoiler=TableLab.java]

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

import java.io.*;

import java.util.*;



public class TableLab extends JPanel

{

 public TableLab(String dataFilePath)

 {

	 JTable table;

	 TableModel model;



	 setLayout(new BorderLayout());



	 model = new TableModel(dataFilePath);



	 table = new JTable();

	 table.setModel(model);

	 table.createDefaultColumnsFromModel();



	 JScrollPane scrollpane = new JScrollPane(table);

	 add(scrollpane);

 }



 public Dimension getPreferredSize()

 {

	 return new Dimension(600,300);

 }



 public static void main(String[] args)

 {

	 JFrame frame = new JFrame("Wonderland Horse Farm");

	 TableLab panel = new TableLab("Horse.dat");



	 frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

	 frame.setForeground(Color.black);

	 frame.setBackground(Color.lightGray);

	 frame.getContentPane().add(panel,"Center");

	 frame.setSize(panel.getPreferredSize());

	 frame.setVisible(true);

	 frame.addWindowListener(new WindowCloser());

 }

}



 class WindowCloser extends WindowAdapter

 {

	 public void windowClosing(WindowEvent e)

	 {

		 Window win = e.getWindow();

		 win.setVisible(false);

		 System.exit(0);

	 }

 }

 

Quote - Revenge is such a nasty thing that only breeds more vengeful souls, but in some situations revenge does not even need to be sought out, but only bided.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.