PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] How can i remove the last "-" in the output?

 August 18, 2022     arrays, error-handling, java, output     No comments   

Issue

    public static void main(String[] args) {
    int[] array = new int[6];

    for (int i = 0; i < array.length; i++) {
        array[i] = (int) (Math.random() * 90) + 1;
    }

    System.out.println("Dein Lottotipp lautet:");
    sort(array);
    printArray(array);
}

public static void sort(int[] array) {

    for (int i = 1; i < array.length; i++) {
        int sortieren = array[i];
        int j = i;
        while (j > 0 && array[j - 1] > sortieren) {
            array[j] = array[j - 1];
            j--;
        }
        array[j] = sortieren;

    }

}

public static void printArray(int[] array) {

    for (int i = 0; i < array.length; i++) {

        if (array[i] < array.length - 1) {
            System.out.print(array[i]);
        } else {
            System.out.print(array[i] + "-");
        }

    }
    System.out.println("");
}

How can i remove the last "-" in the output , im not the best java programmer; The output should be 27-28-37-73-75-81 ,but the output is this 27-28-37-73-75-81-., i need to remove the last - . Can someone please send me the edited code?


Solution

To not print the last -, this line: if (array[i] < array.length - 1) { needs to become: if (i === array.length - 1).

At the moment, you are comparing the content of the array with the index you are currently processing. Comparing the content of the array won't do what you need, since you are only interesting in the current iteration number.



Answered By - npinti
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing