-1
import java.util.Scanner;

public class SimCompanies {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner (System.in);

        boolean x=true;
        String complete = new String(":fire: Buying DAILY :fire:\n");
        while (x==true) {
            String input = scanner.next();
            if (input == "0") {
                System.out.println(complete);
                x=false;
            }
            else {
                complete += extend(input);
            }
        }
}

public static String extend(String a) {
        return new String( 
    ":" + a + ": " + ":" + a + ": " + ":" + a + ": " + ":" + a + ": \n" );
        
    }

I want to write a programme that works with an input. For every input in a new line it shall take the input and do the function "extend". I tried much and I saw that it works well with the function ( so it does everything properly with the input, no matter how many inputs I have). But I want to stopp the programme when I am writing "0". But the programme doesnt see that I am writing "0". It just always goes into the else-statement but never goes into the if-statement. It is important that at the end everything should be printed out. So what am I doing wrong?

I want this at the end (input: Satellite, Jet)

:fire: Buying DAILY :fire:
:Satellite: :Satellite: :Satellite: :Satellite:
:Jet: :Jet: :Jet: :Jet:
KerryKilian
  • 95
  • 11

2 Answers2

-1

The problem here is that you are trying to compare not the string content, but its instance reference. What you want is instead compare the string value.

Modify the if statement in the while loop as follow is a possible solution to fix the problem:

while (x==true) {
    String input = scanner.next();
    if (input.equals("0")) {
        System.out.println(complete);
        x=false;
    }
    else {
        complete += extend(input);
    }
}

or using:

if (input.compareTo("0") == 0) {

An example of input/output will be:

fire
Satellite
Jet
0
:fire: Buying DAILY :fire:
:fire: :fire: :fire: :fire: 
:Satellite: :Satellite: :Satellite: :Satellite: 
:Jet: :Jet: :Jet: :Jet: 
lorenzozane
  • 1,214
  • 1
  • 5
  • 15
-1

Strings aren't primitive so you cannot use the equality operator (==) to compare with another string.

To compare 2 strings, simply use the .equals() method that is already provided as part of the String API in Java.

i.e.

input.equals("0")
jun
  • 192
  • 15