Changing index number of a string

Hi,

My assignment is to write a program that takes as input a string and an integer n and displays the nth character of the string, but the twist is i have to get rid of the 0th index and make the string start at 1 instead of 0. I have it written so that it displays the character, but I can not figure out how to increase the index by 1. This is my first week learning this, so if my code looks ineffecient, im sorry but thats all i've learned so far. Thanks in advance.

import java.util.*;

publicclass ExtractChar{

publicstaticvoid main(String[] args){

Scanner keyboard =new Scanner(System.in);

System.out.println("Enter a word of your choosing:");

String input1 = keyboard.next();

System.out.println("Enter number of the character you would like displayed:");

int input2 = keyboard.nextInt();

String answer = input1.substring(+input2);

System.out.println("The character you are looking for is: " +answer);

}

}

Message was edited by:

rudsky

[1490 byte] By [rudskya] at [2007-11-27 9:36:27]
# 1

I'm not sure exactly what you want, but there are various String methods you should look at:

(1) charAt(int ndx) will return the character at index ndx. Note that ndx is zero-based. If you want to start counting at 1 (which of course doesn't change the string, or "get rid" of anything), then use charAt(ndx - 1)

Note the minus sign there. If you want to start counting the index from 1, then you have to subtract 1 to get the zero based index that all the Java String methods expect.

(2) substring() has a form that lets you specify the start index (zero based) and the index just past the end point. To remove the first character (index 0) of the string, and thereby produce a new string, usestr = str.substring(1, str.length());

Or to get a substring of length 1 starting at ndxanswer = str.substring(ndx, ndx + 1);

Have a read of the String methods that are available: http://java.sun.com/javase/6/docs/api/java/lang/String.html

pbrockway2a at 2007-7-12 23:05:29 > top of Java-index,Java Essentials,New To Java...
# 2
got it! thanks
rudskya at 2007-7-12 23:05:29 > top of Java-index,Java Essentials,New To Java...
# 3
You're welcome.
pbrockway2a at 2007-7-12 23:05:29 > top of Java-index,Java Essentials,New To Java...