Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 16 of 16

Thread: how to convert a input array of type Strings to a class type

  1. #1
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Worried
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Question how to convert a input array of type Strings to a class type

    class Passenger{
    String name;
    int age;
    char gender;
    int weight;

    public Passenger(){
    }
    public Passenger(String name,int age,char gender,int weight){
    }
    }
    class Train {
    public int getTotalWeight(Passenger[] passengers) {
    }
    }
    public class TestTrain {
    public static void main(String[] args) {
    Train test = new Train();
    Passenger[] passenger={"A,21,M,62","B,45,M,78","C,22,F,56","D, 10,F,30","E,8,F,29"};
    test. getTotalWeight( passengers);
    }

    This is showing error.....error it gives isthat it cannot change from string type to passenger type.........

    plz help how to do it??????
    Last edited by adit; August 16th, 2014 at 01:52 AM.


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: how to convert a input array of type Strings to a class type

    When posting code, please use the highlight tags to preserve formatting.

    It looks like you're trying to create an array of Passengers, but then you're filling it with Strings. That doesn't make a lot of sense.

    Start smaller: Can you create a single instance of Passenger instead of an array?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. The Following User Says Thank You to KevinWorkman For This Useful Post:

    adit (August 16th, 2014)

  4. #3
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: how to convert a input array of type Strings to a class type

    You might want to give the Passenger array variable a name as well!
    Improving the world one idiot at a time!

  5. The Following User Says Thank You to Junky For This Useful Post:

    adit (August 16th, 2014)

  6. #4
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Worried
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: how to convert a input array of type Strings to a class type

    thanks for replying..
    @Kevin

    while giving input it is either a type of String or int or char.And it gives a error (cannot convert from String to passenger). So i think i need to give the input in passenger type but i dont know how do i achieve that. If u can plz give an example it would really help.[COLOR="Silver"]

    --- Update ---

    Quote Originally Posted by Junky View Post
    You might want to give the Passenger array variable a name as well!
    I tried but it still gives the same error (cannot convert from String to passenger).If u have any idea how to correct it....if possible an example would suffice.

  7. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: how to convert a input array of type Strings to a class type

    Post your updated code correctly using code or highlight tags which are explained near the top of this link.

  8. #6
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Worried
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: how to convert a input array of type Strings to a class type

    Quote Originally Posted by GregBrannon View Post
    Post your updated code correctly using code or highlight tags which are explained near the top of this link.
    QUESTION
    Define a class Passenger having the fields name (String), age (int), gender (char : M/F), weight (int). Define 2 constructors for this class, one with parameters and one which has no parameters.

    Also define a class Train in which there are the following functions. Note that there are no fields in the class Train.

    - int getTotalWeight(Passenger[] passengers) - returns the total weight of all the passengers in the input

    DOUBT
    if i take input it is in (String or char or integer )....but we have to use this input to find total weight of all passengers.......and the method is
    getTotalWeight(Passenger [] passengers)

    which gives the error(cannot convert from String to Passenger).So how i take this input and use it to find the total weight of the passengers.

    WHAT I EXPECT
    i want you to tell what input i should take(if my input is wrong) or how can i use this input to in class train to find total weight.

    MY INPUT(if this type of input is correct...plz check)
    ("A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30"," E,8,F,29")

    MY CODE

     
    class Passenger{
    	String name;
    	int age;
    	char gender;
    	int weight;
     
    	public Passenger(){
    		}
    	public Passenger(String name,int age,char gender,int weight){
    		this.name=name;
    		this.age=age;
    		this.gender=gender;
    		this.weight=weight;
    	}
     
    }
     
     class Train {
    	 public int getTotalWeight(Passenger[] passengers) {
    		int total=0;
     
    		//(here will be the code)
     
    		return total;
     
    	 }
    }
    public class TestTrain { //main class
     
    	public static void main(String[] args) { //main method
    		// TODO Auto-generated method stub
         Train test =new Train();
         //i initialize my input
        String [] passengers = {"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30","E,8,F,29"}:
       tets.getTheWeight(passengers);   // here i get error

  9. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: how to convert a input array of type Strings to a class type

    Nice post! Very helpful. Thanks for taking the time to be thorough, clear, and posting the code correctly.

    First, let's eliminate the syntax errors from the code you posted, since we don't know if those are included in your environment or copy/paste errors, etc.

    1. The line

    Passenger [] passengers = {"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30"," E,8,F,29"}:

    appears to end in a colon rather than a semicolon. Fix that.

    2. The code you posted is missing two close braces, '}', at the end. Please add those.

    3. Then, in the line "// here i get error", there is a typo. If you were to mouse over the red line (if that's what you're seeing), you will get an explanation that you can mouse into and even select and copy. In my IDE, I get the error:

    tets cannot be resolved

    tets? What is that? The compiler doesn't know, but it appears to be a typo. Fix that.

    4. Once that error is corrected, a new error appears in the same line:

    The method getTheWeight(String[]) is undefined for the type TestTrain

    Similar to #3, what is "getTheWeight()"? The compiler doesn't know what that is, and it's more than a typo this time. It's the name of a method that either doesn't exist or there's a name mixup. Fix that.

    Once those errors are fixed, return with your updated code and the questions you still have.

    We can't get to your original question of "So how i take this input and use it to find the total weight of the passengers?" until you fix the above errors and define your design a bit more. For example,

    Passenger [] passengers = {"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30"," E,8,F,29"}; // with semicolon

    doesn't make sense. You might instead, define a string of Passenger attributes:

    String [] passengerData = {"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30"," E,8,F,29"};

    and then send each element of that String object to a Passenger() constructor in a loop to create Passenger objects

    Passenger passenger[i] = new Passenger( passengerData[i] );

    That approach will require modifying the existing Passenger() constructor or adding a new one - not a big deal.

    Come back with updated code when you're ready to move on. If you're stuck and don't get what I've suggested, then ask more questions about that.

  10. #8
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Worried
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: how to convert a input array of type Strings to a class type

    MY INITIAL QUESTION

    Define a class Passenger having the fields name (String), age (int), gender (char : M/F), weight (int). Define 2 constructors for this class, one with parameters and one which has no parameters.

    Also define a class Train in which there are the following functions. Note that there are no fields in the class Train.

    - int getTotalWeight(Passenger[] passengers) - returns the total weight of all the passengers in the input

    THE ERROR I AM STILL GETTING

    The method getTotalWeight(Passenger[]) in the type Train is not applicable for the arguments (String[]).

    EXPLANATION ABOUT THE QUESTION

    we need to use the input to find the total weight of all passengers in class TRAIN.

    MY MAIN DOUBT
    how to remove the error i am getting???

    CODE

     
    package module4a;
     
     
    class Passenger{
    	String name;
    	int age;
    	char gender;
    	int weight;
     
    	public Passenger(){
    		}
    	public Passenger(String name,int age,char gender,int weight){
    		this.name=name;
    		this.age=age;
    		this.gender=gender;
    		this.weight=weight;
    	}
     
    }
     
     class Train {
    	 public int getTotalWeight(Passenger[] passengers) {
    		int total =0;
     
                     // here we have to write code
     
     
    		return total;
     
    	 }
    }
    public class TestTrain {
     
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
         Train test =new Train();
         String[] passengers ={"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30","E,8,F,29"};
         test. getTotalWeight( passengers);
    	}
     
    }

  11. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: how to convert a input array of type Strings to a class type

    Beautiful! Nice corrections so far.

    The signature of the getTotalWeight() method was specified by the assignment, so you can't mess with that. Since that's the reason for the error. you'll have to prepare the parameter in the statement,

    test. getTotalWeight( passengers);

    to agree with the getTotalWeight() method's signature, i.e. pass it an array of Passenger objects rather than an array of String objects. The question is then, how to create an array of Passenger objects from what you have? As I suggested before, the passenger data contained in the String array you have now can be used to create Passenger objects. The Passenger() constructor is not specified by the assignment, so you could have a constructor with the signature:

    public Passenger( String passengerData ) { }

    and a call to create Passenger objects:

    passengers[i] = new Passenger( passengerData[i] );

    The above statement would be in a for() loop in your current main() method, using the String array passengers which I renamed for clarity, passengerData, to get you started, main() would look something like:
    public static void main(String[] args)
    {
        Train test =new Train();
        String[] passengerData ={"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30","E,8,F,29"};
        Passenger[] passengers = new Passenger[passengerData.length];
     
        // a loop to make Passenger objects out of passengerData and store them
        // in a Passenger array
        for ( int i= 0 ; i < passengerData.length ; i++ )
        {
            // create a Passenger object and store in passengers array
            (the statement I showed you above)
        }
     
        test. getTotalWeight( passengers);
    }
    You'll have to modify the Passenger() constructor to accept the String argument and then parse the String argument into the parts and types needed for the Passenger fields. I recommend you look at the String.split() method to do part of that and then convert the parsed elements into the types needed.

    Make some progress and come back when you need more help. I can't do much more without doing the whole thing for you.

    Hints: You will need at least one other method in Passenger to complete the needed code in the Train method.

  12. The Following User Says Thank You to GregBrannon For This Useful Post:

    adit (August 25th, 2014)

  13. #10
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Worried
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: how to convert a input array of type Strings to a class type

    made some progress...but still a lot to do...

    giving my code here...

    package module4a;
     
    class Passenger{
    	String name;
    	int age;
    	char gender;
    	int weight;
     
    	public Passenger(){
    		}
     
    	public Passenger(String passengerData){
     
    		String[] data = passengerData.split(",");
    		Passenger pass = new Passenger();
    		pass.name = data[0];
    		pass.age = Integer.parseInt(data[1]);
    		pass.gender = data[2].charAt(0);
    		pass.weight = Integer.parseInt(data[3]);
    	}
    }
     
     class Train {
    	 public int getTotalWeight(Passenger[] passengers) {
    		int total=0;
    		for(int i =0;i<passengers.length;i++){
    			Passenger pass = new Passenger();
    			total =total+pass.weight;
    		}
    		System.out.println(total);
    		return total;
     
    	 }
    }
    public class TestTrain {
     
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
         Train test =new Train();
         String[] passengerData ={"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30","E,8,F,29"};
         Passenger[] passengers = new Passenger[passengerData.length];
         for ( int i= 0 ; i < passengerData.length ; i++ ){
        	 passengers[i]= new Passenger(passengerData[i]);
         }
         test. getTotalWeight( passengers);
     
    	}
     
    }

  14. #11
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: how to convert a input array of type Strings to a class type

    Pretty good. You've essentially answered your initial question, but you demonstrated that you're missing some basic concepts.

    You've misunderstood the use of a constructor as shown by the changes you made to the Passenger() constructor. If you write a constructor that creates an instance of the class using a 'new' statement, you're probably doing something wrong or very special, like writing a copy constructor. In this case, the Passenger object being created by the Passenger() constructor happens when you call the constructor using the 'new' statement in the main() method.

    How to fix: Eliminate the 'pass' object entirely.

    There's no reason for the Train class to be creating passengers. It might be helpful if you wrote a comment at the beginning of each of the classes that describes what they do. Get rid of the 'pass' object and use the weight of each of passengers[] elements to find the total weight.

    Keep chuggin'.

  15. #12
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Worried
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: how to convert a input array of type Strings to a class type

    I have coded the Passenger construct but i dont understand how to add the total weight of all the passengers ...if you could give some hint...

     
    package module4a;
     
    class Passenger{
    	String name;
    	int age;
    	char gender;
    	int weight;
     
    	public Passenger(){
    		}
     
    	public Passenger(String passengerData){
    	String data[] = passengerData.split(",");
    	this.name = data[0];
    	this.age = Integer.parseInt(data[1]);
    	this.gender= data[2].charAt(0);
    	this.weight = Integer.parseInt(data[3]);
    		}
     
     class Train {
    	 public int getTotalWeight(Passenger[] passengers) {
    		int total=0;
    		for(int i =0;i<passengers.length;i++){
     
    			total =total+passengers[i].weight;
    		}
     
    		return total;
     
    	 }
    }
    public class TestTrain {
     
    	public   void main(String[] args) {
    		// TODO Auto-generated method stub
         Train test =new Train();
         String[] passengerData ={"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30","E,8,F,29"};
         Passenger[] passengers = new Passenger[passengerData.length];
         for ( int i= 0 ; i < passengerData.length ; i++ ){
        	 passengers[i]= new Passenger(passengerData[i]);
     
         }
         test. getTotalWeight( passengers);
     
    	}
    }
    }

  16. #13
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: how to convert a input array of type Strings to a class type

    Much better on the constructor. Note that the keyword 'this' is not required, because there is no confusion with local variables of the same name. Leaving the 'this' is also okay, it's just not required.

    Are you running, or trying to compile and run, the program just as you've posted it? If so, you're surely getting errors. Resolve those, post them if you need help resolving them. Reason: A top-level public class with a static main() method is required as the program's entry point, and that doesn't exist in what you've posted. Your indentation is off, so while the class TestTrain may appear to be at the top level because it begins in column 0, it is indented improperly and should not start in column 0. And someone removed the modifier 'static' from the main() method signature.

    As for your total weight question, you have all of the the code needed, except you need to output the results of the last line in your main() method - print it.

    A more appropriate way to access each passenger's weight attribute stored in the Passenger field, weight, while preserving encapsulation is to is to add an accessor (or getter) method to the Passenger class. In this case, the method would have the signature:

    public int getWeight()

    Surely, you've heard of this. An alternative to what you have would be to add the method getWeight() to Passenger and then in the Train.getTotalWeight() method, obtain the weight of each passenger object in the loop using the getWeight() method, storing the sum of the weights in total, just as you're doing now.

  17. #14
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Worried
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: how to convert a input array of type Strings to a class type

    when i write static in the code it gives following error.....and i am having difficulty in correcting that...

    error

    The method main cannot be declared static; static methods can only be declared in a static or top level type.

     
    package module4a;
     
    class Passenger{
    	String name;
    	int age;
    	char gender;
    	int weight;
     
    	public Passenger(){
    		}
     
    	public Passenger(String passengerData){
    	String data[] = passengerData.split(",");
    	this.name = data[0];
    	this.age = Integer.parseInt(data[1]);
    	this.gender= data[2].charAt(0);
    	this.weight = Integer.parseInt(data[3]);
    		}
     
     class Train {
    	 public int getTotalWeight(Passenger[] passengers) {
    		int total=0;
    		for(int i =0;i<passengers.length;i++){
     
    			total =total+passengers[i].weight;
    		}
     
    		return total;
     
    	 }
    }
    public class TestTrain {
     
    	public static  void main(String[] args) {
    		// TODO Auto-generated method stub
         Train test =new Train();
         String[] passengerData ={"A,21,M,62","B,45,M,78","C,22,F,56","D,10,F,30","E,8,F,29"};
         Passenger[] passengers = new Passenger[passengerData.length];
         for ( int i= 0 ; i < passengerData.length ; i++ ){
        	 passengers[i]= new Passenger(passengerData[i]);
     
         }
         test. getTotalWeight( passengers);
     
    	}
    }
    }

  18. #15
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: how to convert a input array of type Strings to a class type

    Notice the words "top level" in the error message? Sound familiar? I explained the significance of the top-level public class and why it appears you have one but don't in Post #13. Indent your code properly and then rearrange your code so that you have a top-level public class with a main() method for the program's entry point.

  19. #16
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Worried
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: how to convert a input array of type Strings to a class type

    i have tried this question in a different way....is it correct??...but there are some mistakes due to which i am not getting the output.....it would be great if you could point out to me...

     
    package module4a;
     
    class Passenger{
    	String name;
    	int age;
    	char gender;
    	int weight;
     
    	public Passenger(){
    		}
     
    	public Passenger(String name,int age,char gender,int weight){
    		this.name = name;
    		this.weight = weight;
    	   Passenger passengers3 = new Passenger("A",23,'F',45);
    	   Passenger passengers1 = new Passenger("B",13,'M',55);
    	   Passenger passengers2 = new Passenger("C",33,'M',65);
    	   Passenger[] passengers = {passengers3,passengers1,passengers2};
    		}
    }
     
     class Train {
    	 public int total(Passenger[] passengers) {
    		 Passenger object = new Passenger();
    		 int total =0;
    		 for(int i=0;i<passengers.length;i++){
    			 total = total+object.weight; 
    		 }
    		 System.out.println(total);
    		return total;
     
    	 }
     
    	 }
     
    public class TestTrain {
     
    	public static  void main(String[] args) {
    		// TODO Auto-generated method stub
    	   Train test = new Train();
    	    System.out.println();
     
     
    }
    }

Similar Threads

  1. [SOLVED] Type mismatch: cannot convert from void to JTextField
    By nikolaiL in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 9th, 2014, 12:28 PM
  2. Replies: 2
    Last Post: January 14th, 2013, 03:22 PM
  3. having problem declaring a generic type array in OrderSet class
    By mia_tech in forum What's Wrong With My Code?
    Replies: 2
    Last Post: July 10th, 2012, 06:39 PM
  4. How to convert from type double to type int?
    By rph in forum Object Oriented Programming
    Replies: 7
    Last Post: July 25th, 2011, 04:21 AM
  5. Typecasting of double variable to integer
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 2
    Last Post: December 5th, 2010, 03:41 AM