This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
Write a method that returns a new array by eliminating the duplicate values in the array using this header:
public static int[] eliminateDuplicates (int[] list)
all I have so far is my main, but what I wanted to do for the other method was use a for loop to check values at each space in my array and print them if they did not equal any of the other entries. Working on it as we speak!
My output is this: The distinct numbers are: [I#4554617c
first of all this is 11 characters and at max I should be printing 10.
import java.util.Scanner;
public class EliminateDuplicates
{
public static void main(String [] Args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter ten whole numbers: ");
int[] tenNumbers = new int[10];
for (int i=0; i<10; i++)
{
tenNumbers[i] = input.nextInt();
}
System.out.println("The distinct numbers are: " + eliminateDuplicates(tenNumbers));
}
public static int[] eliminateDuplicates (int[] list)
{
int count = 0;
for (int i = 0; i > list.length; i++)
{
for (int j = i + 1; j < list.length; j++)
{
if(list[i] == list[j])
{
list[j] = -1;
}
}
}
for (int i = 0; i < list.length; i++)
{
if(list[i] != -1)
{
count++;
}
}
int[] array2 = new int[count];
int newCount = 0;
for (int i = 0; i < list.length; i++)
{
if(list[i] != -1)
{
array2[newCount] = list[i];
}
}
return array2;
}
}
import java.util.ArrayList;
public class EliminateDuplicates {
//This is called Generics, It'll be a little later in your studies
public static <E> ArrayList<E> eliminateDuplicates(ArrayList<E> list) {
ArrayList<E> newList = new ArrayList<>(list.size());
for (E aList : list) { // for (int i = 0; i <= list.lenght; i++){
if (!newList.contains(aList)) {
newList.add(aList);
}
}
return newList;
}
public static void main(String[] args) {
ArrayList<Integer> tenNumbers = new ArrayList<Integer>();
tenNumbers.add(14);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
ArrayList<Integer> newList = eliminateDuplicates(tenNumbers);
System.out.print("The distinct numbers are: " + newList);
}
}
import java.util.*;
public class Question {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr = {1,2,3,3,4,5,6,1};
int[] ne = new int[arr.length];
ArrayList<Integer> already= new ArrayList();
int i = 0;
while(i<arr.length){
if(!already.contains(arr[i]))
already.add(arr[i]);
i++;
}
System.out.println(already.toString());
}
}
Related
I am making a java program that prints the even and odd numbers of an array. This is my even code that returns the evens variable and prints the evens in the runner case.
public static int[] getAllEvens(int[] array)
{
String evens;
for(int i=0; i<array.length; i++)
{
if(array[i]%2==0)
{
evens = (array[i]+" ");
}
}
return evens;
}
But when I compile, it says that the evens variable cannot be converted to int[]. I get that String or int shouldn't be used to define evens but I do not know how else I can return array[i]+" ".This is so difficult for me.
Edit 1: Using Scanner & using temporary ArrayList to make int[] compact
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int[] evens = getAllEvens1(arr);
for (int i : evens) {
System.out.print(i + " ");
}
}
public static int[] getAllEvens1(int[] array) {
int[] temp = new int[array.length]; // if all of array are `even`..
Arrays.fill(temp, -1); //or any flag.. to indicate it's unnecessary
int j = 0;
for (int i : array) {
if (i % 2 == 0) {
temp[j++] = i;
}
}
int[] ret = new int[j];
j = 0;
for (int i : temp) {
if (i != -1) {
ret[j++] = i;
}
}
return ret;
}
public static int[] getAllEvens(int[] array) {
ArrayList<Integer> temp = new ArrayList();
for (int i : array) {
if (i % 2 == 0) {
temp.add(i);
}
}
return temp.stream().mapToInt(Integer::intValue).toArray();
}
}
There are several problems in your code..
First you're trying to return String whereas your function return type is int[]
Secondly, you're assigning only current even number to the String which hasn't even initialized yet..
Fix:
public static String getAllEvens(int[] array) {
StringBuilder evens = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
evens.append(array[i]).append(" ");
}
}
return evens.toString();
}
Or by using String instead of StringBuilder:
public static String getAllEvens(int[] array) {
String ret = "";
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
ret += array[i] + " ";
}
}
return ret;
}
please change the return type of the method.
your returning String but method return type is int Array. That is the issue you're unable to compile the code.
you could do some thing like this:
FYI: I have not tested this but should be ok.
public static int[] getAllEvens(int[] array) {
int[] tmp = new int[array.length];
for (i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
tmp[even_count++] = array[i];
}
}
return tmp;
}
i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}
I am having trouble figuring out the programming logic.How do you get the array of strings to print asteriks at random indexes. Note that the 3 is the number of asterisk to be generated in the array.
so the output can be [a,b*,c*,d,e*,f,g,h] or [a*,b,c,d,e,f,g*,h*]
public class Generate
{
public static void main(String[] args)
{
String[] list = {"a","b","c","d","e","f","g","h"};
for(int i =0; i <list.length; i++)
{
System.out.print(" " + list[i]);
generateAsterisk(list);
}
System.out.println();
}
public static void generateAsterisk(String[] list)
{
for(int i = 0; i < 3; i++)
{
int index = (int)(Math.random()*i);
}
System.out.print("*");
}
}
You can do it like that:
import java.util.Random;
public class Generate {
public static void main(String[] args) {
String[] list = { "a", "b", "c", "d", "e", "f", "g", "h" };
//do it 3 times or change to as many times you want to add an asteriks
for (int i = 0; i < 3; i++) {
addRandomAsteriks(list);
}
//print the array
for (int i = 0; i < list.length; i++) {
System.out.print(" " + list[i]);
}
System.out.println();
}
public static void addRandomAsteriks(String[] list) {
Random rand = new Random();
int randomNumber = rand.nextInt(list.length - 1);
String string = list[randomNumber]; //get the string at the random index
if (!string.contains("*")) {
// add the asteriks
list[randomNumber] = string.concat("*");
}else {
//if it had already an asteriks go through the
//add-method again until you find one that has no asteriks yet.
addRandomAsteriks(list);
}
}
This is a more object oriented point of view than YassinHH's answer.
This solution works and has only arrays in use.
You can call the generateAsteriks method only once, with the number of asteriks you want:
String[] list = {"a","b","c","d","e","f","g","h"};
generateAsterisks(list, 3);
...
And change your generateAsteriks method to this:
public static void generateAsterisks(String[] list, int numAsteriks)
{
for(int i = 0; i < numAsteriks && i < list.length; i++)
{
int index = (int)(Math.random()*list.length);
//check if already added *
if(list[index].lastIndexOf('*') != list[index].length()-1) {
list[index] = list[index] + "*";
} else {
//don't count this loop iteration
i--;
}
}
}
The error occurs at odd[count1] = value.
This program should basically print a 2d array with evens being less than odds and then both sorted from lowest to highest.
public static void main(String args[]) {
int[][] arzarehard = {{12,13,17}, {38,44,13}, {54,37,15}, {35,25,17}};
oddSort(arzarehard);
}
public static void oddSort(int[][] thots) {
int [] even = new int[thots.length + thots[0].length];
int [] odd = new int[thots.length + thots[0].length];
for (int i=0; i<even.length; i++) {
even[i] = Integer.MAX_VALUE;
}
for(int i=0; i<odd.length; i++) {
odd[i] = Integer.MAX_VALUE;
}
int count = 0;
int count1 = 0;
//try non for each - possibly causing problem
for (int[] row : thots) {
for(int value : row) {
if (value%2==0) {
even[count] = value;
count++;
} else {
//odd.add(value); - adds it to the end and then concatinate
odd[count1] = value;
count1++;
}
}
}
//even bubble sort
for(int j=0; j<odd.length; j++) {
for(int i=0; i<odd.length-1; i++) {
if(odd[i]>odd[i+1]) {
int temp = odd[i];
int tempTwo = odd[i+1];
odd[i] = tempTwo;
odd[i+1] = temp;
}
}
}
//odd bubble sort
for(int j=0; j<even.length; j++) {
for(int i=0; i<even.length-1; i++) {
if(even[i]>even[i+1]) {
int temp = even[i];
int tempTwo = even[i+1];
even[i] = tempTwo;
even[i+1] = temp;
}
}
}
int e = 0;
int o = 0;
for(int j=0; j<thots.length; j++) {
for(int i=0; i<thots[0].length; i++) {
if(e<even.length) {
thots[j][i] = even[e];
e++;
} else {
thots[j][i] = odd[o];
o++;
}
}
}
for(int[] whatever : thots) {
for( int value : whatever) {
System.out.print(value + " ");
}
System.out.println();
}
}
The basic idea is that I am inputting a 2d array. Then breaking that array into an even and odd array. Then sorting both and putting them back together to print.
since in you code size of array even[] and odd[] is 7.it should be sufficient enough to hold all the values.when you assigh value 17 to odd[7] this will through ArrayIndexOutOfBoundException.
change code-
int [] even = new int[thots.length + thots[0].length];
int [] odd = new int[thots.length + thots[0].length];
to-
int [] even = new int[thots.length * thots[0].length];
int [] odd = new int[thots.length * thots[0].length];
Use following code-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class BinarySearch{
public static void main(String args[]) {
//System.out.println(Integer.MAX_VALUE);
int[][] arzarehard = {{12,13,17}, {38,44,13}, {54,37,15}, {35,25,17}};
oddSort(arzarehard);
}
public static void oddSort(int[][] thots) {
List<Integer> evenList=new ArrayList<Integer>();
List<Integer> oddList=new ArrayList<Integer>();
for (int[] row : thots) {
for(int value : row) {
if (value%2==0) {
evenList.add(value);
} else {
oddList.add(value);
}
}
}
Collections.sort(evenList);
Collections.sort(oddList);
int i=0;
int j=0;
for(Integer even:evenList){
if(j==thots[0].length){
i++;
j=0;
}
thots[i][j]=even;
j++;
}
for(Integer odd:oddList){
if(j==thots[0].length){
i++;
j=0;
}
thots[i][j]=odd;
j++;
}
for(int[] whatever : thots) {
for( int value : whatever) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
String[] sortedArr = new String[arr.length];
for(int i=0;i<sortedArr.length;i++)
{
sortedArr[i] = compareArrayElements(arr);
}
System.out.println("The strings in the sorted order of length are: ");
for(String sortedArray:sortedArr)
{
System.out.println(sortedArray);
}
}
public static String compareArrayElements(String[] arr) {
String temp = null;
for(int i=0;i<arr.length-1;i++)
{
temp = new String();
if(arr[i].length() > arr[i+1].length())
temp = arr[i+1];
else
temp = arr[i];
}
return temp;
}
}
If you really want to learn Java: use a Comparator. Any other way is bad Java code.
You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.
For your actual code, here are some hints:
Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.
Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".
Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.
You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
Use bubble sort, but instead of comparing ints, just compare String lengths.
I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.
Good luck.
References:
Bubble sort in Java
Sorting an array of strings
Implement bubbleSort() and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
bubbleSort(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String item : arr) {
System.out.println(item);
}
}
// Mutates the original array
public static void bubbleSort(String[] arr) {
boolean swapped = false;
do {
swapped = false;
for (int i = 0; i < arr.length - 1; i += 1) {
if (arr[i].length() > arr[i + 1].length()) {
swap(arr, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
// Mutates the original array
public static void swap(String[] arr, int index0, int index1) {
String temp = arr[index0];
arr[index0] = arr[index1];
arr[index1] = temp;
}
}
Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string
import java.util.*;
class strings {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>(2);
System.out.println("Start entering your words or sentences.");
System.out.println("Type stop to stop.");
String b;
int c = 0, d;
do {
b = in.nextLine();
b = b.trim();
a.add(b);
c++;
}
while (!b.equalsIgnoreCase("stop"));
if (c > 1)
a.remove(a.size() - 1);
System.out.println("Choose the sort you want. Type the corresponding
number");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int sc=in.nextInt();
switch(sc) {
case 1: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] > sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
case 2: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] < sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
}
}
}
For instance, the following:
ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);
By lambda:
str.sort((String s1, String s2) -> s1.length() - s2.length());
By static Collections.sort
import static java.util.Collections.sort;
sort(str, new Comparator<String>{
#Override
public int compare(String s1, String s2) {
return s1.lenght() - s2.lenght()
}
});
Both options are implemented by default sort method from List interface
Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]
we can use Comparator for sorting the given string array to sort it based on length with the following code:
String[] sortByLength(String[] inputArray) {
Arrays.sort(inputArray, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
return inputArray;
}
//sort String array based on length
public class FirstNonRepeatedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your String");
String str = in.nextLine();
String arrString[] = str.split("\\s");
arrString = sortArray(arrString);
System.out.println("Sort String ");
for(String s:arrString){
System.out.println(s);
}
}
private static String[] sortArray(String[] arrString) {
int length = arrString.length;
String s;
for (int i = 0; i < length ; i++) {
s= new String();
for(int j = 0; j < length; j++ ){
if(arrString[i].length()< arrString[j].length()){
s = arrString[i];
arrString[i] = arrString[j];
arrString[j] = s;
}
}
}
return arrString;
}
}
import java.util.*;
public class SortStringBasedOnTheirLength {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String[] str1=str.split("\\s");
for(int i=0;i<str1.length;i++)
{
for(int j=i+1;j<str1.length;j++)
{
if(str1[i].length()>str1[j].length())
{
String temp= str1[i];
str1[i]=str1[j];
str1[j]=temp;
}
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]+" ");
}
}
}