Java error message at main method - java

I am new in this Java journey, at College they are asking me to
"Define five String variables in the main method called: shipmentNum, supplierName, revDate, revTime, employeeNum." And assign the following text:99, Costco, 12/15/2011, 10:25 AM, 33."
I have this so far, but is giving an error message: "the local variable shipmentNum is never read", I don't see why am I getting this error message.
package c1;
public class ShipmentApp {
public static void main(String[] args){
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println("99");
System.out.println("Costco");
System.out.println("12/15/2011");
System.out.println("10:25 AM");
System.out.println("33");
}
}

What you are seeing is a compiler warning, not an error. This is basically Java trying to help you find flaws in your code by analyzing what you wrote and detecting common mistakes.
In this case, Java recognized that you assigned values to a bunch of variables, but after that never use those variables again.
You probably want to write out the values of the variables, not the assigned values again.
public static void main(String[] args){
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println(shipmentNum );
System.out.println(supplierName );
System.out.println(revDate );
System.out.println(revTime );
System.out.println(employeeNum );
}

Thats warning not error but try this.
public static void main(String[] args){
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println(shipmentNum);
System.out.println(supplierName);
System.out.println(revDate);
System.out.println(revTime);
System.out.println(employeeNum);
}
or just try:
package c1;
public class ShipmentApp{
public static void main(String[] args){
System.out.println("99");
System.out.println("Costco");
System.out.println("12/15/2011");
System.out.println("10:25 AM");
System.out.println("33");
}
}

What you are receiving are warnings because you are not actually ever reading any of the variables you have declared. You could correct this by passing the variables to println instead of typing out the strings twice.
Being that these are only warnings, they should not affect the ability of the program to compile and/or execute. While you could conceivably ignore such warnings, it's usually wise to at least analyze what they are being caused by.

It's a warning that the java compiler tells you that you defined a variable but never used it.
The purpose of a variable, is that it stores information that will be used at some later point in your code. Java gives you a warning, because if you define a variable but never use it you've likely made a mistake. This is because variables that are never used are basically nonsense, and should never have been declared.
Try these print statements:
System.out.println(shipmentNum);
System.out.println(supplierName);
System.out.println(revDate);
System.out.println(revTime);
System.out.println(employeeNum);

That's is not an Error,It is just a warning shown by the IDE or compiler. There is no issue in this code to compile and run.
You may want to do as follows
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println(shipmentNum);
System.out.println(supplierName);
System.out.println(revDate);
System.out.println(revTime);
System.out.println(employeeNum);

You are writing the text out, not the value of the variables. It isn't an error, just a warning. You should probably change your code to this:
package c1;
public class ShipmentApp{
public static void main(String[] args){
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println(shipmentNum);
System.out.println(supplierName);
System.out.println(revDate);
System.out.println(revTime);
System.out.println(employeeNum);
}
}

this message is just to notice you, you have some variables haven't been used. It is not a error. if you dont want to see this warning or you cannot stand it, you can add #supresswarnings annotation at the beginning of the class. or you just follow others' suggestion to use the variables you have created.

Related

Converting Enum to a String Object for Java seamlessly

I am shaky with parsing and handling text files. How do I convert my method signatures with enums to strings so I can read from a text file and parse effectively without wasting CPU resources? I currently have method signatures like this
public void createReservation(VehicleType v, String cName, long phoneNumber, String sDate, String eDate) throws Exception //right here
{
//trouble with representing VehicleType v in my Reservation text file
}
Reservation.txt file looks like this matching the signature Above
"COMPACT", "John Wick", 312 900 6001, "2019-02-09", "2019-02-14"
"SUV", "Harvey Dent", 302 600 2001, "2019-02-11", "2019-02-15"
In my main class I have a parseVehicleLine method like this..
private void parseReservationLine(String str){
Scanner sc = new Scanner(str);
sc.useDelimiter(",");
while(sc.hasNext()){
vehicleType = sc.next();//there is an error here because it is still an enum of Vehicle class
String cName = sc.next();
long phoneNumber = sc.nextLong();
String Date = sc.next();
String eDate = sc.next();
}
sc.close();
}
public abstract class Vehicle {
public enum VehicleType
{
ECONOMY(18.00), PREMIUM(22.50), SUV(25.50);
private double vehicleDailyCost;
private VehicleType(double vehicleDailyCost)
{
this.vehicleDailyCost = vehicleDailyCost;
}
public double getVehicleDailyCost()
{
return vehicleDailyCost;
}
}
Can someone explain how I could properly convert the VehicleType enum to a String without issues? Thanks!
You are reading the text file as String, so I think you need to convert String to VehicleType, not vice-versa as you mentioned.
You should be able to get enum from String using valueOf():
vehicleType = VehicleType.valueOf(sc.next());

Variable not in scope (I think), but not sure how to fix it

What I am doing is just practicing for a test and I thought it was doing just fine, but I am getting, what I think is a scope problem. It says, "teams cannot be resolved to a variable type" and I've tried a few things I thought would fix it, but they didn't work. Here is the code:
import java.util.Scanner;
public class fundamentalsofgame {
public String hteam;
public String cteam;
public String teams(String hometeam, String compteam){
String hteam = hometeam;
String cteam = compteam;
return "The teams are " + hteam + " vs " + cteam;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String hometeam;
String awayteam = "New England Cheatriots";
hometeam = scanner.next();
teams team = new teams(hometeam, awayteam); //error
}
}
teams is a method and not your class name instead it is fundamentalsofgame. So you need to make object of fundamentalsofgame and call teams method on it. Change this:
teams team = new teams(hometeam, awayteam); //error
to
fundamentalsofgame obj = new fundamentalsofgame();
fundamentalsofgame.teams(hometeam, awayteam);

pass the argument of array from command line instead of scanner in java

I write the code in Java to get the arguments by scanner. I have several classes : ChartToHtml.java, ExecutionProperties.java, ExecutionV2.java, TestCase.java, TestCaseList.java, Section.java and all of them will be called from ImplTest.java.
They are working fine when I execute either from eclipse or command line by scanner. The problem is when I want to execute them via program arguments and pass the arguments in one single line. It considers the input as single String but I have to use a String[] as input for Section class.
Here are my Section class and ImplTest classes
public class Section {
Ini.Section root;
ArrayList<String> StringList = new ArrayList<String>();
ArrayList<TestCase> TCList = new ArrayList<TestCase>();
String sectionSearched;
String section;
String filenameSearched;
public Section (){
}
public Section (String filenameSearched, String sectionSearched) {
this.sectionSearched = sectionSearched;
this.filenameSearched = filenameSearched;
}
public ArrayList<String> findSection(String filename, String... wanted) throws IOException, IOException {
Ini myIni = new Ini(new File (filename));
for (String d : wanted) {
root = myIni.get(d);
for (String name : root.keySet()){
StringList.add(root.get(name));
}
}
return StringList;
}
public ArrayList<TestCase> convertStringToTestCase(ArrayList<String>StringList){
for ( int i = 0; i < StringList.size(); i++) {
String name = StringList.get(i) ;
TestCase tc = new TestCase (name);
TCList.add(tc);
}
return TCList;
}
public String[] getSection(int NumOfSec){
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Input section name:");
section = scanner.nextLine();
for (int i =0; i<NumOfSec; i++){
String token[]= section.split(" ");
System.out.println(Arrays.toString(token));
return token;
}
}
}
}
My Main class
public class ImplTest {
public static void main(String[] args) throws IOException, ConfigurationException, TemplateException {
ExecutionV2 ex = new ExecutionV2();
TestCaseList tc = new TestCaseList();
Section s = new Section();
ChartToHtml chr= new ChartToHtml();
ExecutionProperties ep = new ExecutionProperties();
ImplTest imp = new ImplTest();
String filename = ex.getcfg();
String []sec = ex.getSection();
int it = ex.getIterationMax();
String runTCpath =ex.getRunTCdir();
String dir = chr.getChartDir();
ArrayList<TestCase> TClist = s.convertStringToTestCase(s.findSection(filename, sec));
ex.executeTestCaseList(TClist, it , runTCpath);
ex.getTCAttribute(TClist);
ep.setConfigProperties(tc.getTCPassed(), tc.getTCFailed());
chr.generateHistoryTable();
chr.generateChartAndTableTemplate(tc.getTCPassed(), tc.getTCFailed(),ex.getNameList(), ex.getPassedList().toString(), ex.getItList().toString(),dir);
}
}
Then I modified the main class to pass the arguments via run configuration and pass this single line:
ArrayList<TestCase> TClist = s.convertStringToTestCase(s.findSection(**args[0]**, **args[1]**));
ex.executeTestCaseList(TClist, Integer.parseInt(**args[2]**) , **args[3]**);
ex.getTCAttribute(TClist);
ep.setConfigProperties(tc.getTCPassed(), tc.getTCFailed());
chr.generateHistoryTable();
chr.generateChartAndTableTemplate(tc.getTCPassed(), tc.getTCFailed(),ex.getNameList(), ex.getPassedList().toString(), ex.getItList().toString(), **args[4]**);
and pass this singe line into program arguments
C:\\Users\\syuniyar\\.EasyTest\\4\\ccl\\config\\test2.cfg 12346 5 C:\\EasyTest\\4\\bin\\runTC.exe C:\\Users\\syuniyar\\EclipseWS\Test3\\chart.html
it is working fine. However, when I modify the input from ...12346... to ...12346 12345..., I get such error:
Exception in thread "main" java.io.IOException: Cannot run program "5": CreateProcess error=2, The system cannot find the file specified
I also try with VM arguments but the option of System.getProperty() is only for single string.
I know why I get this error because it reads 12345 as 'it' which is not correct. What I wanna ask :
Is it possible to have an array as single argument in main method?
To directly answer your question, "Is it possible to have an array as [a] single argument in [a] main method?", no. The main method accepts arguments in the form of one array of String objects (usually called "args"). Each of these strings is considered an argument.
When executing the main method from the command line, these arguments come after the program name and are delimited by spaces. They are loaded into an array and passed into the main method.
As mentioned in the comments (esp. #Ismail Kuruca), if it is important to you to pass in several strings as one argument, you can concatenate the strings to make your arguments technically one String, and thereby treated as one argument.

How to set java object attribute like the way in javascript

All:
I have a data model object in Java like:
class Model {
String name;
String email;
}
What I want to do is dynamically determine what attribute I want to set by using a variable like in Javascript object;
String field = "name";
// This is what I try to achieve, not the real code.
New Model().field = "according content";
or
New Model()[field] = "according content";
Thanks
You could reflection as in this link
In this example they have
public long chapters = 0;
and can get/set it as
Field chap = c.getDeclaredField("chapters");
out.format(fmt, "before", "chapters", book.chapters);
chap.setLong(book, 12);
out.format(fmt, "after", "chapters", chap.getLong(book));

how to get a string from java function in php

I have written 2 java codes (FullTextIndexer.java and Indexer.java) FullTextIndexer has functions :
public static StringBuilder do_exist = null;
public static String do_exist_str;
public static String a_value = new String("my_string");
public static void main(String[] args){
//... here I find "do_exist" value by using "Indexer.java" and printed it with system.out.println; which is the correct value
do_exist_str = do_exist.toString();
}
public static String get_file()
{
main(args);
return do_exist_str;
}
Then I compiled it and compress it as FullTextIndexer.jar and put it into my WEB-INF/lib folder.
And in my php code :
require_once("java/Java.inc");
$session = java_session();
$t = new Java('java.lang.System');
$t=new Java("web_java.FullTextIndexer");
$gotten = java_values($t->get_file());
$a_value = java_values($t->a_value);
echo $gotten;
echo sizeof($gotten);
echo $gotten[0].$gotten[1];
I expect to get my file_name string however I always get an array like {0=0, 1=0} of size 2.
But it writes $a_value correctly.
I guess it finds its value in main(args) but erase afterwards and cannot return "do_exist_str" correctly.
I cannot find a way to get this string correctly. Any help will be appreciated. Thanks in advance

Categories