Skip to content
Advertisement

Scanner if Choice Equals

I need the scanner to work with if choice equals, however this doesnt work, any suggestions to fix it?

I need it so when the input equals either 32, 64, 128, or 356 it will output the relevant lines, however i just get this when i run the code, Error:(18, 18) java cannot find symbol symbol: variable equals location: variable choice of type java.lang.string

    package com.company;
import java.util.Scanner;
import java.util.Random;
public class Main {
    public static final String ALPHA_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
    static Scanner scan = new Scanner(System.in);
    private static String getNum() {
        Random r = new Random();
        int offset = r.nextInt(ALPHA_CHARS.length());
        return ALPHA_CHARS.substring(offset, offset+1);
    }
public static int Length = 0;
    public static void main(String[] args) {
    System.out.println("Choose the Strings length, It must be either 32, 64, 128 or 256 characters.");
    System.out.println("Enter a value.");
    String choice;
    choice = scan.nextLine();
    if(choice.equals == 32) {
        System.out.println("Generating 32 Characters.");
        System.out.println(getNum());
    }
    if(choice.equals == 64) {
        System.out.println("Generating 64 Characters.");
    }
    if(choice.equals == 128) {
        System.out.println("Generating 128 Characters.");
    }
    if(choice.equals == 256) {
        System.out.println("Generating 256 Characters.");
    }
    else {
        System.out.println("Choose a valid integer.");
    }
    }
}

Advertisement

Answer

You are scanning a String and comparing it to an int. Besides, it is better to use else if in such cases:

public static final String ALPHA_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
static Scanner scan = new Scanner(System.in);
private static String getNum() {
    Random r = new Random();
    int offset = r.nextInt(ALPHA_CHARS.length());
    return ALPHA_CHARS.substring(offset, offset+1);
}

public static int Length = 0;
public static void main(String[] args) {
    System.out.println("Choose the Strings length, It must be either 32, 64, 128 or 256 characters.");
    System.out.println("Enter a value.");
    int choice;
    choice = scan.nextInt();
    if(choice == 32) {
        System.out.println("Generating 32 Characters.");
        System.out.println(getNum());
    }else if(choice == 64) {
        System.out.println("Generating 64 Characters.");
    }else if(choice == 128) {
        System.out.println("Generating 128 Characters.");
    }else if(choice == 256) {
        System.out.println("Generating 256 Characters.");
    }else {
        System.out.println("Choose a valid integer.");
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement