Creating a parameter that accepts input for an array - java

I am practicing making arrays. I have created two classes. The first class (Processor class) contains a parameter that accepts an array of 10 values that the user inputs. It also contains 4 methods to process: the average of the numbers entered, the largest value, the smallest value, and a toString method. This class compiles with no errors.
import java.util.Arrays;
public class Processor {
public int[] value;
int aSum = 0;
int largest = value[0];
int smallest = value[0];
private int number;
public Processor() {
int[] numbers = new int[10];
}
public void arrayAverage(int[] value) {
double average = 0;
for (int i = 0; i < value.length; i++) {
aSum = aSum + value[i];
average = aSum / value.length;
}
}
public void arrayMax() {
for (int i = 1; i < value.length; i++) {
if (value[i] > largest) {
largest = value[i];
}
}
}
public void arrayMin() {
for (int i = 1; i < value.length; i++) {
if (value[i] < smallest) {
smallest = value[i];
}
}
}
public String toString() {
return Arrays.toString(value);
}
}
The second class ProcessorTester creates an instance of Processor and asks for the user to input 10 values for the array. I then call the methods from the first class and print their values. However, when I compile this class I get the following error: "incompatible type- int cannot be converted to Processor".
import java.util.Scanner;
public class ProcessorTester {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Processor[] inputs = new Processor[10];
System.out.println("Input 10 values for the array: ");
for (int i = 0; i < inputs.length; i++) {
inputs[i] = keyboard.nextInt();
}
System.out.println("The average of the numbers inputed is: ");
System.out.println(arrayAverage.inputs());
System.out.println("The largest of the numbers inputed is: ");
System.out.println(arrayMax.inputs());
System.out.println("The smallest of the numbers inputed is: ");
System.out.println(arrayMin.inputs());
System.out.println("The numbers inputed are: ");
System.out.println(toString.inputs());
}
}
Is this a problem with my coding in the main method in the Processor class?

You've declared inputs as an array of Processor:
Processor[] inputs = new Processor[10];
A Processor contains an array of integer, but a Processor is not an integer. Thus, this isn't legal:
inputs[i] = keyboard.nextInt();
that says to take the ith Processor and assign it an integer. But inputs[i] is a Processor so you can only assign Processor to it.
Pro-tip: when the compiler gives you an error, it will tell which line in which file caused the error. When posting a question always indicate the line that causes the compile error as that saves people from having to read every line of your file trying to find the issue.

I will recommend the following changes at the least:
Processor class
Change
public Processor() {
int[] numbers = new int[10];
}
to
public Processor() {
value = new int[10];
}
ProessorTest Class
In the main method,
change
Processor[] inputs = new Processor[10];
System.out.println("Input 10 values for the array: ");
for (int i = 0; i < inputs.length; i++) {
inputs[i] = keyboard.nextInt();
}
to
Processor inputs = new Processor();
System.out.println("Input 10 values for the array: ");
for (int i = 0; i < inputs.length; i++) {
inputs.value.add(keyboard.nextInt());
}

Look at your Code here:
Processor[] inputs=new Processor[10]; //1
for(int i=0; i<inputs.length;i++)
{
inputs[i]=keyboard.nextInt(); //2
}
//1 You make an array of type Processor
//2 You try to fill this Array with integers inputs[i]=keyboard.nextInt();
This causes this specific error.

Related

Using an array to input strings, and another one to output word frequency

So I am trying to complete this code. The goal is to input an array of strings, then count the frequency of how often the words are found. For example:
input:
joe
jim
jack
jim
joe
output:
joe 2
jim 2
jack 1
jim 2
joe 2
An array must be chosen for Strings, and another array much be chosen for word frequency.
My code so far:
I am stuck into trying to implement this. The string method is set, but how am I going to count the frequency of words, and also assign those values to an array. Then print both side by side. I do know that once the integer array is set. We can simply do a for loop to print the values together such as. System.out.println(String[i] + " " + countarray[i]);
public class LabClass {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int freq = 0;
for (int i = 0; i < listSize; i++) {
if (wordsList[i].compareTo(currWord) == 0) {
freq++;
}
}
return freq;
}
public static void main(String[] args) {
LabClass scall = new LabClass();
Scanner scnr = new Scanner(System.in);
// assignments
int listSize = 0;
System.out.println("Enter list Amount");
listSize = scnr.nextInt();
// removing line to allow input of integer
int size = listSize; // array length
// end of assignments
String[] wordsList = new String[size]; // string array
for (int i = 0; i < wordsList.length; i++) { //gathers string input
wordsList[i] = scnr.nextLine();
}
for (int i = 0; i < listSize; i++) {
String currWord = wordsList[i];
int freqCount = getFrequencyOfWord(wordsList, listSize, currWord);
System.out.println(currWord + " " + freqCount);
}
}
}
int some_method(String[] arr, String word) {
int count = 0;
for (int i=0; i<arr.size(); i++) {
if (arr[i].equals(word)) count++;
}
return count;
}
Then in main method:
String[] array = ["joe", "jake", "jim", "joe"] //or take from user input
int[] countArray = new int[array.size()]
for (int i=0; i<array.size(); i++) {
countArray[i] = some_method(array, array[i])
}
System.out.println(array[0] + " " + countArray[0]);
Ouput:
joe 2

Why does my method that I am trying to call to inside main not work?

minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}

Java: Filling an array with random numbers without duplicates [duplicate]

so my program is supposed to access a text document then do all that jazz that currently works. The only problem that I can't figure out is how to shuffle the contents of an array without having them end up on top of each other. Both internets and multiple tries with random and for loops have been unfruitful. here is my code:
import java.io.*;
import java.util.*;
public class lab_6 {
public static void main(String[] args)throws FileNotFoundException {
Scanner input = new Scanner(System.in); //reads from keyboard
System.out.println("What is the name of your file. ");
String name = input.nextLine();
Scanner reader = new Scanner(new File(name));// Open text file
System.out.println("how many names are in your array");
int num = input.nextInt();
String[] names = new String[num];
for (int index = 0; index< names.length; index++)
{
names[index] = reader.nextLine();// Gets a line while there is one
}
System.out.println("\nOriginal List");
printList(names);
System.out.println("\nShuffled List");
shuffle(names);
printList(names);
System.out.println("\nSorted List");
Arrays.sort(names); // this is a built in method
printList(names);
System.out.println("What name are you looking for");
Scanner input1 = new Scanner(System.in); //reads from keyboard
String find = input1.nextLine();
int index = search(names,find);
if(index == -1)
System.out.println("The name was not there");
else
System.out.println(find+" was found at position "+index);
System.out.println("The average length of all the names is "+averageLength(names));
}
public static void printList(String[] array) // print the list of names numbered
{
for (int i=0; i<array.length; i++)
{
System.out.println((i+1)+") "+ array[i]);
}
}
public static void shuffle (String[] array) // mix-up the array
{
}
public static int search(String[] array, String find)
{
for(int i=0; i<array.length; i++) {
if (array[i].equals(find) ) return i;
}
return -1;
}
public static double averageLength(String[] array) //return the average length of the names
{
int sum=0;
for (int i=0; i<array.length; i++)
{
int l= array[i].length();
sum +=l;
}
int average = sum/(array.length);
return average;
}
}
String[] names = ...;
Collections.shuffle(Arrays.asList(names));
// done
Note that Arrays.asList() returns a modifiable (but fixed-length) list, backed by the array, and not a copy of the array. So the array will be shuffled.
Just use the Fisher-Yates shuffle (Knuth algorithm P):
private Random rand = new Random();
public static void shuffle(String[] array) { // mix-up the array
for (int i = array.length - 1; i > 0; --i) {
int j = rand.nextInt(i + 1);
String temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
See:
Knuth, D. 1969, 1998: Seminumerical Algorithms 1st & 3rd Eds. The Art of Computer Programming Series, Volume 2, p. 125.
Fisher, Ronald A.; Yates, Frank (1948) [1938]. Statistical tables for biological, agricultural and medical research (3rd ed.). London: Oliver & Boyd. pp. 26–27.
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
https://stackoverflow.com/a/1520212/636009
You can use the Collections class, with the shuffle method. The documentation is available here.
Example
int[] values = {1,2,3,4,5};
List<Integer> valuesList = Arrays.asList(values);
Collections.shuffle(valuesList);
// valuesList is shuffled.

How to convert a char array to an int array?

Say I am using this code to convert a String (containing numbers) to an array of characters, which I want to convert to an array of numbers (int).
(Then I want to do this for another string of numbers, and add the two int arrays to give another int array of their addition.)
What should I do?
import java.util.Scanner;
public class stringHundredDigitArray {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
String num1 = in.nextLine();
char[] num1CharArray = num1.toCharArray();
//for (int i = 0; i < num1CharArray.length; i++){
//System.out.print(" "+num1CharArray[i]);
//}
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = num1CharArray[i];
}
for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
System.out.print(" "+num1intarray[i]);
}
}
}
I really have to split the string, to preferably an array of additionable data types.
try Character.getNumericValue(char); this:
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
Try This :
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++)
{
num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
System.out.print(num1intarray[i]);
}
Short and simple solution!
int[] result = new int[charArray.length];
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i]));

java display method

Here im required to Write a method printArray that displays the contents of the array num and Display the contents of the array with each
number separated by a space. and i have to start a new line after every 20 elements.
i wrote this code but whenever i try to execute it, it shows the array without the new line
public class project2 {
public static void main(String[] args) {
int num []= new int [100];
for (int i=0;i<num.length;i++){
num[i]=-1;
num[7]=7;
}
printArray(num);
System.out.println(num);
}
public static void printArray (int array1[]){
int count =20;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (array1[x]==count){
System.out.println(" ");
count=array1[x]+count;
}
}
}
}
import java.util.Arrays;
import java.util.Random;
public class project2 {
public static void main(String[] args) {
int num[] = new int[100];
Random random = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = random.nextInt(100);
}
printArray(num);
System.out.println('\n' + Arrays.toString(num));
}
public static void printArray(int array1[]) {
int count = 20;
for (int i = 0; i < array1.length; i++) {
System.out.printf("%2d ", array1[i]);
if ((i + 1) % count == 0) {
System.out.println("");
}
}
}
}
You should use the modulo (or remainder) operator (%), that suits your usage much better:
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (x>0 && (x%count)==0){
System.out.println(" ");
}
}
This way, you will get a new line every count characters, and the first line will not have it (that is why the x>0 check is there).
Also, in the original post, this line is frankly totally bad:
count=array1[x]+count;
Just what would it do? Why do you add the value stored in the array to the fixed counter? Considering this line, I advise that you should really sit back a bit, and try to think about how things work in the background... There is no magic!
Take a closer look at your if-statement:
if (array1[x]==count)
According to your array values, this will never return true
i have to start a new line after every 20 elements.
Change to following code:
if (x%20 == 0)
{
System.out.println();
}
in place of
if (array1[x]==count)
{
System.out.println(" ");
count=array1[x]+count;
}
Problem is with
if (array1[x]==count)
You are comparing count with value present in array. Instead compare it with desired count ie 20 or Use modulo operator as suggested in other answers / comments .
int count = 1;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (count == 20){ // Check if its 20th element
System.out.println(" ");
count=1; // reset count
}
count++;
}

Categories

Resources