Java noob

  • Thread starter Thread starter Kua
  • Start date Start date

Kua

Kua

Associate
Joined
21 Jul 2008
Posts
512
Location
Lancaster
Hullo! I'm a first year CS student at Lancaster and I'm really struggling with the Java module. I'm hoping it'll all click into place soon. Not sure how appropriate it is to copy-pasta the whole question.

But I have to write an encode class that takes a String as its input parameter and returns an array of int values, based on a message the user inputs. Each int will be the ASCII value for each character in the original string.

We have to cast each char as an int, but the original message is a String. So I really have no clue what to do.

I understand the concept of arrays but **** me if I can use them!

I've probably not explained that too well, but like I say I don't know whether its kosher to show the whole question.
 
I have done exactly this in c++ if that helps at all? I am not sure I can post my code here though as it is for a uni project.
 
I have done exactly this in c++ if that helps at all? I am not sure I can post my code here though as it is for a uni project.

May be explain the concepts if you can... Do I need to cast the String as an array of Chars? If that's even possible.
 
In c++ a string IS an array of characters and you can access the elements by array index. Not sure if java is the same.
 
Here you go

public class TestProg
{
public static void main(String args[])
{
String s = "Hello, world!";
char array[] = s.toCharArray();

for (int i=0; i<array.length; i++)
System.out.print(array);
System.out.println();
}
}


Converts a string to a character array.
 
And to get the ascii code you would do

int ascii_code = 0;

ascii_code = int(array[0]);

to get the first letter. But set it up as a loop to an array instead.
 
And to get the ascii code you would do

int ascii_code = 0;

ascii_code = int(array[0]);

to get the first letter. But set it up as a loop to an array instead.

Cheers man, Feel as though I've got something to work off now. (That normally means I'm about to get stuck again. But we can always hope)
 
Here is another solution, along the same lines as Ross1234 but using a type cast to get the value.

The comments in the code below assume the call was stringToIntArray("Hello");

Code:
public int[] stringToIntArray(String str) {
	[COLOR="SeaGreen"]// convert the string into an array of characters
	// chars = {'H', 'e', 'l', 'l', 'o'}[/COLOR]
	char[] chars =  str.toCharArray();
	[COLOR="SeaGreen"]// create an empty integer array of the same length
	// ints = {0, 0, 0, 0, 0}[/COLOR]
	int[] ints = new int[chars.length];
	[COLOR="SeaGreen"]// iterate over the character array[/COLOR]
	for(int i = 0; i < chars.length; i++){
		[COLOR="SeaGreen"]// cast each character in the array to an integer
		// store the integer value in the ints array[/COLOR]
		ints[i] = (int) chars[i];
	}
	[COLOR="SeaGreen"]// return the ints array
	// ints = {72, 101, 108, 108, 111}[/COLOR]
	return ints;
}
 
Last edited:
Yikes this is devilishly difficult.

"In your Encode class, write a method that takes a String as an input parameter and returns an array of int values, based on the contents of the original message. Each element in the array will be the ASCII value of the relevant character of the message string."

The input has to be a variable that's in my main program, so I don't know whether I can simply us the name of the variable in the parameter for the constructor method I'm creating....

Here's the code I have in the Encode class:

Code:
public class Encode {

public encode(message){
  
    char myArray[] = message.toCharArray();
    
    int asciiCode;
    
    for(int j=0; j<myArray.length; j++) {
    asciiCode = int(myArray[j]);
    return myArray[j]
    }
    
}

(Let's hope that's valid markup!)

Code:
public QuestionDialog qDialog = new QuestionDialog ("Enter your message");

void setup()
{

      String message = qDialog.getAnswer();
      println(message);
      
            
      
      for (int i=0; i<myArray.length; i++)
      println(array[i]);
      
}

And thats the code in the main program...

Sorry. My heads swimming again now. I seem to keep losing track of what I'm doing. Its not like reading a book, where you just continue where you left off. Its like spinning dozens of plates. I just can't keep em all spinning!

I'm sure that metaphor makes no sense whatsoever. But this does get easier, right?
 
Last edited:
"... a method that takes a String as an input parameter and returns an array of int values, based on the contents of the original message. Each element in the array will be the ASCII value of the relevant character of the message string."

That description fully describes what the method I posted above does. Your method is on the right track but your syntax is slightly wrong, compare it to mine and you'll see where they differ, apart from that they function identically.

The input has to be a variable that's in my main program, so I don't know whether I can simply us the name of the variable in the parameter for the constructor method I'm creating....

Again, you're on the right track here. You need to pass the message variable to your encode method and then print the result. In the case of the method I wrote it would be:

Code:
for (int i : Encode.StringToIntArray(message)) {
   System.out.println(i);
}

Where Encode points to an instance of the class which contains the encode method (assuming the method is not static).
 
So it looks like this?

Code:
public encode(String){

//stuff

}

And the code you posted above goes inside the main program?

I've named it encode here, but you've named it StringToIntArray.
 
The code I posted is the encode method, I named it StringToIntArray to reflect its function but you can call it whatever you want. So this would be one possible implementation of your Encode class:

Code:
public Encode {

  public Encode()
  {
[COLOR="YellowGreen"]    // Empty Constructor[/COLOR]
  }

  public int[] stringToIntArray(String str) {
  [COLOR="YellowGreen"]  // convert the string into an array of characters
    // chars = {'H', 'e', 'l', 'l', 'o'}[/COLOR]
    char[] chars =  str.toCharArray();
  [COLOR="YellowGreen"]  // create an empty integer array of the same length
    // ints = {0, 0, 0, 0, 0}[/COLOR]
    int[] ints = new int[chars.length];
   [COLOR="YellowGreen"] // iterate over the character array[/COLOR]
    for(int i = 0; i < chars.length; i++){
 [COLOR="YellowGreen"]     // cast each character in the array to an integer
      // store the integer value in the ints array[/COLOR]
      ints[i] = (int) chars[i];
    }
[COLOR="YellowGreen"]    // return the ints array
    // ints = {72, 101, 108, 108, 111}[/COLOR]
    return ints;
  }

}

Then in your main program you can make use of the class by doing the following:

Code:
[COLOR="YellowGreen"]// construct an instance of the Encode class[/COLOR]
Encode encoder = new Encode();
[COLOR="YellowGreen"]// execute your encode method on the message[/COLOR]
int[] ASCIIMessage = encoder.stringToIntArray(message);

[COLOR="YellowGreen"]// print the message in ASCII codes[/COLOR]
for (int i : ASCIIMessage) {
   System.out.println(i);
}

Java can be confusing to begin with because like most programming languages there are several ways to achieve exactly the same result. I'm not sure how much you know yet so some of this may be way beyond your knowledge.
 
Thanks Rob. I've got it working but we're using Processing and it didn't like this line of code:

Code:
for (int i : ASCIIMessage) {
   System.out.println(i);
}

So I used this instead:

Code:
for (int i = 0; i < ASCIIMessage.length; i++) {
   println(ASCIIMessage[i]);
}

Still feeling a bit all at sea with it, but I'll keep plugging away :p
 
Thanks Rob. I've got it working but we're using Processing and it didn't like this line of code:

Code:
for (int i : ASCIIMessage) {
   System.out.println(i);
}

That called an enhanced for-loop in Java (also known as a foreach loop in other languages) and is is just a shorter way of writing it the other way. Processing uses a subset of Java to make it easier to learn although behind the scenes it all gets turned into real Java.

I'm glad that Processing is actually being used to teach Java, it's a great way to start. My university started with BlueJ which was around some time before Processing and has the same idea, making Java easier to learn without having to get dirty with all of the complex 'boilerplate' code.
 
Back
Top Bottom