so my program prints an array but when it does it also includes brackets and commas and i dont want those.
here is my library
import java.util.*;
public class library2
{
public static boolean IsPrime(int p)
{
for (int i = 2; i < p; i++)
{
if (p % i == 0 && i != p)
return false;
}
return true;
}
public static List<List<Integer>> GetPrimes(int n)
{
List<Integer> arr = new ArrayList<Integer>();
for (int j = 2; j < n; j++)
{
if(IsPrime(j))
{
arr.add(j);
}
}
return Arrays.asList(arr);
}
}
here is my driver
import java.util.Scanner;
import java.util.*;
import java.util.Arrays;
public class driver2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Please input an integer: ");
int n = scan.nextInt();
Boolean check = library2.IsPrime(n);
List<List<Integer>> arr = library2.GetPrimes(n);
System.out.println(Arrays.toString(arr));
}
}
ive tried the Arrays.toString(); method but i get an error when i compile. i used import java.util.Arrays; but that didnt solve anything. can someone help me out.
arr is a list and not an array.
You should iterate over and print:
Iterator<List<Integer>> arrIterator = arr.iterator();
while (arrIterator.hasNext()) {
List<Integer> l = arrIterator.next();
Iterator<Integer> lIterator = l.iterator();
while(lIterator.hasNext()){
int i = lIterator.next();
System.out.print(i + " ");
}
System.out.print("\n");
}
Related
I am trying to write code to count the frequency of each word in an array. I am wondering if I need to use two nested loops to keep track of both the array with integers and the array with the words. I have been fiddling with the code for hours and cannot make any progress. If you have any pointers, they would be much appreciated. I am given the input as first the number of elements in the array, then the words that I am supposed to count the frequency of, such as 4 dog cat dog fish.
import java.util.Scanner;
public class LabProgram {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int i;
int count;
int[] countArr = new int[listSize];
// need to use two arrays; one for frequency, one for words.
for (i = 0; i < countArr.length; ++i) {
if (wordsList[i].compareTo(currWord) == 0) {
countArr[i] += 1;
}
}
//check previous LAB that had same concept; then make it use a method.
return countArr[i];
}
public static void main(String[] args) {
int size;
int i;
size = scnr.nextInt();
String[] array = scnr.nextLine().split(" ");
for (i = 0; i < array.length; ++i) {
System.out.println(array[i]);
}
for (i = 0; i < array.length; ++i) {
currWord = array[i];
System.out.println(currWord + getFrequencyOfWord(array, size, currWord));
}
}
}
Can you please try below solution?:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
try (Scanner scnr = new Scanner(System.in)) {
int size = scnr.nextInt();
Map<String, Integer> wordCounts = new HashMap<>();
for (int i = 0; i < size; i++) {
String s = scnr.next();
if (wordCounts.containsKey(s)) {
int count = wordCounts.get(s);
wordCounts.put(s, ++count);
} else {
wordCounts.put(s, 1);
}
}
wordCounts.entrySet().stream().forEach(s -> System.out.println(
s.getKey() + ": " + s.getValue()));
}
}
}
Using Java 8 Streams:
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class LabProgram {
public static void main(String[] args) {
try (Scanner scnr = new Scanner(System.in)) {
int size = scnr.nextInt();
String array[] = new String[size];
for (int i = 0; i < size; i++) {
array[i] = scnr.next();
}
Map<Object, Integer> data = Stream.of(array)
.collect(Collectors.groupingBy(
s -> s, Collectors.summingInt(s -> 1)));
data.entrySet().stream().forEach(s -> System.out.println(
s.getKey() + ": " + s.getValue()));
}
}
}
If your input is:
4 dog cat dog fish
Output:
cat: 1
fish: 1
dog: 2
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;
}
Link to this problem:
https://www.hackerrank.com/contests/takneek/challenges/maximum-length-substring/problem
The code passes the initial test case but then times out when I go to submit on hacker rank for much larger strings. I have a feeling it's the algorithm I'm using for the unique substrings, how do I cut down this time into something efficient?
My code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList<Integer> kList = new LinkedList<Integer>();
LinkedList<String> setout = new LinkedList<String>();
LinkedList<String> setLex = new LinkedList<String>();
//Get the original text
String text = in.nextLine();
//Get n from the file
int n = in.nextInt();
//Get the next needed items for comparison and order
for (int i = 0; i < n; i++) {
kList.add(in.nextInt());
}
setout = getAllUniqueSubset(text);
setLex = sortLexographically(setout);
int findMax = findMaximumSub(setLex, kList, 0);
// System.out.println(setLex);
System.out.println(findMax);
}
//Get the unique subset to begin with and return it
public static LinkedList<String> getAllUniqueSubset(String text) {
LinkedList<String> set = new LinkedList<String>();
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < text.length() - i; j++) {
String elem =text.substring(j, j + (i+1));
if (!set.contains(elem)) {
set.add(elem);
}
}
}
return set;
}
public static LinkedList<String> sortLexographically(LinkedList<String> setout){
for(int i = 0; i < setout.size()-1; ++i) {
for (int j = i + 1; j < setout.size(); ++j) {
if (setout.get(i).compareTo(setout.get(j)) > 0) {
String testLex = setout.get(i);
setout.set(i, setout.get(j));
setout.set(j, testLex);
}
}
}
return setout;
}
public static int findMaximumSub(LinkedList<String> setLex, LinkedList<Integer> kList, int maxCheck){
for (int i = 0; i < kList.size()-1; i++) {
if (maxCheck < setLex.get(kList.get(i)).length()) {
maxCheck = setLex.get(kList.get(i)).length();
}
}
return maxCheck;
}
}
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();
}
}
}
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());
}
}