Passing values from main class to other classes in Java - java

I'm on a project that requires passing values from main class to other classes. All of the classes are correctly working when they have their main functions. However, my project should have only one main class that calls other functions in other classes.
An example for main and another class is below. I want to scan the input through main class and pass it to parse class. Current implementation gives two error which are:
Exception in thread "main" java.lang.NullPointerException
at url.checker.Parse.GetInput(Parse.java:16)
at url.checker.Main.main(Main.java:14)
Java Result: 1
Given input: -url=google.com,-time=5,-email=asdfg#hotmail.com
Main.java:
package url.checker;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the parameters as '-url=' , '-time=' , '-email='.");
Parse.s = in.nextLine();
Parse.GetInput(Parse.s);
}
}
Parse.java:
package url.checker;
import java.util.Scanner;
public class Parse
{
static String s;
static String result[];
public static void GetInput(String s)
{
int i;
for(i=0;i<3;i++)
{
if (s.startsWith("-url="))
result[0] = s.substring(5, s.length());
else if (s.startsWith("-time="))
result[1] = s.substring(6, s.length());
else if (s.startsWith("-email="))
result[2] = s.substring(7, s.length());
else
System.out.println("You didn't give any input.");
}
}
}
Thank you very much for your help.

static String result[];
You never initialized the array; Since its a static it gets initialized to null by default.
Initialize using static String[] strings = new String[10];. This will hold 10 elements of String.

Related

Problems with non-static variable inputs and trying to run methods

I've done a bunch research into trying to solve this issue (for about 2.5 hours), but I'm still not able to compile my program. I have tried making the method not static, but when attempting to run it, it gives me this error:
"Error: Main method is not static in class prog6, please define the
main method as: public static void main(String[] args)"
When the main method is static, I get following error in a compiler
Error: "non-static variable input cannot be referenced from a static
context
usd = input.nextDouble();"
I'm sorry if this question comes off redundant, I don't mean to ask without looking for an answer on my own, but I've been working at this for hours now and I don't understand what I'm doing wrong.
Some extra info on this program: it's meant to take inputs from the user to find out what currency they want to convert to, and how much USD they would like to convert. Then, I would invoke a method in order to do the calculations and return them. (Any amount trying to be converted over $200, will need 5% fee.)
import java.util.Scanner;
public class prog6
{
Scanner input = new Scanner(System.in);
public static void main (String[] args)
{
char curr = 0;
double usd;
double result;
while (curr!='Q' || curr!='q') { //loop
System.out.println("What type of currency would you like to buy?");
curr = input.next().charAt(0);
System.out.println("How many dollars would you like to convert?");
usd = input.nextDouble(); //asking user for info needed to convert
if (usd>200) {
usd = (usd)*(0.95);
}
result = calc (curr,usd); //invoke the method
}
}
public double calc (char mCurr,double mUsd) //method
{
if (mCurr=='E' || mCurr=='e') {
return (mUsd)*(0.88);
}
else if (mCurr=='P' || mCurr=='p') {
return (mUsd)*(0.77);
}
else if (mCurr=='Y' || mCurr=='y') {
return (mUsd)*(113.17);
}
return 0;
}
}
The main method will need to be static. From there, create an instance of your class and call a non-static method from the static main method. eg..
public class Prog6 {
private Scanner input = new Scanner(System.in);
public static void main (String[] args) {
Prog6 prog6 = new Prog6();
prog6.start();
}
public void start() {
char curr = 0;
double usd;
double result;
// etc...
}
}
You could make the member variable static but it's better form to use regular non-static members and methods and call this from the static main method.
There are two ways to solve your prolem
Change the input variable to static;
or
In main method, prog6 myprog= new prog6(); and refer input as myprog.input ....

Law of Demeter-Inputting parameters

i was running the PMD tool for my code and checking it for a simple program that inputs two strings for beginning purposes.when i do something like a=in.nextLine(); it shows object not created locally.Can you help?
import java.util.Scanner;
class Test {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String a, b;
a = in.nextLine();
b = in.nextLine();
in.close();
}
}

Making a program into two different classes

So I had to write a code that takes a word and reverse it I got it to work but for my homework I had to make it into two classes a tester class and a main class how do I do that?
public static void main(String args[])
{
String original = "";
String reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
{
reverse = reverse + original.charAt(i);
}
System.out.println("Reverse of entered string is: "+reverse);
}
You create two classes. You can even put a main method in both of them.
public class Homework {
public static void main(String[] args) {
// Code here to prompt user for string and to print reversed string
}
static String reverse(String input) {
// Code here to do the actual reverse logic, returning reversed string
}
}
public class HomeworkTest {
public static void main(String[] args) {
test("Hello", "olleH");
test("This is a test", "tset a si sihT");
}
private static void test(String input, String expected) {
String rev = Homework.reverse(input);
System.out.println(input + ": " + rev);
if (! expected.equals(rev))
System.out.println(" ** NOT AS EXPECTED: " + expected);
}
}
You can now run the Homework for manual testing, or the HomeworkTest class for automatic testing.
You could get the original String in the Main-class and hand it to the second class to execute the for-loop. The second class then returns the reversed String so that the Main-Class can print it out.
The second class could contain a static method which reverses the String (executes the for-loop) or you can create an object of the second class and and this Object the original String to reverse.
There are several ways to do this. Most trivially, you could make a static function in a Test class, like so:
class Test
{
public static void runTest(String args[])
{
//same as your above program
}
}
But that is probably not what your teacher wants. Instead, you could make a Test class that reverses a set of strings.
class Test
{
public static void runTests()
{
//iterate through a list of hard-coded strings to test
}
}
You would then make a separate function in a Reverser class and the Test.runTests() function would test the Reverser class.
However, there are standardized ways of doing this. One common way is called JUnit. If you are using Eclipse, try this page for instructions.
The simplest way is to
Divide your code into a function public String reverse(String input)
Create new Tester class
Add test method in tester class public void test()
Prepare assertions to test your function assert reverse("ola").equals("alo") : "First assertion failed"
In main function run new Tester().test();
To make assertions working you have to run jvm with -ea option

Compilation error in UVA 11854

This is the link for the actual problem, here
I have submitted my code multiple times, but each time it had a compilation error. The original message was
"Main.java:4: error: class Egypt is public, should be declared in a file named Egypt.java
public class Egypt {
^
1 error"
I have no idea where I went wrong. I have copied my code for the problem below. please help me with this code:
import java.util.Scanner;
import java.util.Arrays;
public class Egypt {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true){
int[] arr = new int[3];
for (int i = 0; i < 3; i++)
arr[i] = input.nextInt();
if((arr[0]+arr[1]+arr[2])==0)
return;
Arrays.sort(arr);
int d = (int)(Math.pow(arr[0],2) + Math.pow(arr[1], 2));
if(Math.sqrt(d)==arr[2])
System.out.println("right");
else
System.out.println("wrong");
}
}
}
From the Java specifications here,
All programs must begin in a static main method in a Main class.
Do not use public classes: even Main must be non public to avoid compile error.
So, I think you must use
class Main

How to pass objects between two Java classes with main

Basically I create a custom object in one program and instantiate with values in one program, then I create another program and want to print the instantiated object output.
import java.util.Scanner;
class example {
int value;
String name;
String city;
}
public class Yummy21 {
static example[] obj=new example[3];
static Scanner input=new Scanner(System.in);
public static void main(String args[])
{
init();
}
public static void init()
{
for(int i=0;i<3;i++)
{
obj[i]=new example();
}
for(int i=0;i<3;i++)
{
System.out.println("for the object "+i+" enter the name ");
obj[i].name=input.next();
System.out.println("for the object "+i+" enter the city ");
obj[i].city=input.next();
System.out.println("for the object "+i+" enter the name ");
obj[i].value=input.nextInt();
}
}
}
And the next program:
public class Yummy22 extends Yummy21 {
public static void main(String args[])
{
for(int j=0;j<3;j++)
{
System.out.println("the value of the object["+j+"].name is "+obj[j].name);
}
}
}
The first program works fine, meaning it takes the values and the second program shows NullPointerException.
Yummy22.main does not invoke Yummy21.init. perhaps put a
static {
init();
}
in Yummy21.
This being said, these 3 classes are abominations of Java. Please at least follow naming conventions. Class example should be Example. Also better to code all this with object level fields, constructors and non static members
serialize the data from program 1 and write it to disk and then read it from program 2.

Categories

Resources