简体   繁体   中英

getting a length of a string from a variable array java

Im a student learning Java and this is part of my program and it is supposed to get the length of a string but the strings are all in an array. I try to run this in eclipse and it says i get an error where it says length = name[x].length() can someone let me know if there is a way to fix this

public class GuessName
{

    Random random = new Random();

    Scanner scan = new Scanner(System.in);
    String[] name = new String[10];
    int x,length;
    char guess1,guess2,guess3;

    public void names()
    {
        name[0] = "MARK";
        name[1] = "CHARLIE";
        name[2] = "MEG";
        name[3] = "KYLE";
        name[4] = "JUSTIN";
        name[5] = "KATARINA";
        name[6] = "JOEL";
        name[7] = "KEVIN";
        name[8] = "MICHAEL";
        name[9] = "JENNA";
        name[10] = "GREG";
    }

    public void start()
    {
        x = random.nextInt(10);
        length = name[x].length();
    }

You have an array, as follows:

String[] name = new String[10];

The number between the [] represents the size of the array. In your example, your array has a size of 10 meaning your array has 10 indexes which are [0,9] (because indexes start at 0). The last line of your names() method is:

name[10] = "GREG";

Do you know where I'm getting at?

Also, what does your main method look like? If you're receiving a NullPointerException it probably means you are calling start() before names() .

I commented out the parts that was problematic. Also, you are trying to initialize 11 names as opposed to 10. Please note that arrays index starts at 0. I don't know why you have scanner object in there but you can use this block to complete your code.

import java.util.Random; 
import java.util.Scanner;

  public class GuessName {



 //   Scanner scan = new Scanner(System.in);
    String[] name = new String[10];
    int x,length;
    char guess1,guess2,guess3;

    public GuessName()
    {
        name[0] = "MARK";
        name[1] = "CHARLIE";
        name[2] = "MEG";
        name[3] = "KYLE";
        name[4] = "JUSTIN";
        name[5] = "KATARINA";
        name[6] = "JOEL";
        name[7] = "KEVIN";
        name[8] = "MICHAEL";
        name[9] = "JENNA";
       // name[10] = "GREG";
    }

    public void start()
    {
        Random random = new Random();
        this.x = random.nextInt(10);
        this.length = name[this.x].length();
    }
    public static void main(String[] args) {
        GuessName gn = new GuessName();

        gn.start();

        System.out.println("The name is: "+gn.name[gn.x]+" and the length is: "+ gn.x);
    } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM