0

I'm trying to make a random generated array word, i dont find any problems with this code, but it just doesn't run, it doesn't show me the array's word when there is a random generated number. What is wrong with my code?

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

public class apples{
    public static void main(String[] args){
        Random dice = new Random();
        Scanner scan = new Scanner(System.in);
        String me[] = new String[5];


        me[0] = "Wow";
        me[1] = "LoL";
        me[2] = "Jis, Ji";
        me[3] = "Mes";
        me[4] = "Jus";


        System.out.println("Enter YES or NO: ");
        String roll = scan.nextLine();
        String name = "yes";
        if(roll == name){
            int result = dice.nextInt(5);
             if(result == 0){
                 System.out.println(me[0]);
             }else if(result == 1){
                 System.out.println(me[1]);
             }else if(result == 2){
                 System.out.println(me[2]);
             }else if(result == 3){
                 System.out.println(me[3]);
             }else if(result == 4){
                 System.out.println(me[4]);
             }
        }else{
            System.out.println("Bad");
        }

        }

    }
aretas_pau
  • 99
  • 1
  • 8

4 Answers4

4

Use string equals method to compare string instead of ==

Replace the below condition

if(roll == name)

with

if(roll.equals(name))

String equals compares the contents of the string while == checks whether the two references point to the same memory objects or not.

Read this related post to learn more about string comparsions: Java String.equals versus ==


Unrelated, but instead of the chain of:

if (result == 0){
   System.out.println(me[0]);

Consider something closer to:

System.out.println(me[result]);
Community
  • 1
  • 1
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
2

roll==name will always return false because in that case you are checking whether they refer to the same memory location.

Use if (roll.equals(name)) instead.

Dulanga
  • 1,326
  • 7
  • 15
1

Also,

if(roll.equals(name)){
        int result = dice.nextInt(5);
         if(result == 0){
             System.out.println(me[0]);
         }else if(result == 1){
             System.out.println(me[1]);
         }else if(result == 2){
             System.out.println(me[2]);
         }else if(result == 3){
             System.out.println(me[3]);
         }else if(result == 4){
             System.out.println(me[4]);
         }
    }else{
        System.out.println("Bad");
    }

can be replaced with:

if(roll.equals(name))
{
     int result = dice.nextInt(5);
     System.out.println(me[result]);
}
else
{
     System.out.println("Bad");
}

To reduce redundant IF statements.

0

In java you must use equals function to compare String

roll.equals(name)

just see this for more details this How do I compare strings in Java?

Community
  • 1
  • 1
Andres
  • 4,323
  • 7
  • 39
  • 53