my java code needs to plus 1 and im getting an error saying
ArrayTask3.java:8: error: incompatible types: int cannot be converted to int[]
int[] row = intList [i];
It should just read my array and then add 1 to each number. could someone please help me get it to work correctly.
class ArrayTask3 {
public static void main(String[] args) {
int [] intList = {5,20,32,7,9};
int sum = 0;
for (int i = intList.length-1; i >=0; i--) {
int[] row = intList [i];
for (int j = 0; j < row.length; j++) {
row[j] = row[j] + 1;
}
System.out.println ("intList [" + i + "]: " + intList [i]);
}
for (int counter=0;counter<intList.length;counter++)
sum = sum + intList[counter];
System.out.println ("Sum = " + sum);
}
}
intList is just a int[], not a 2-d array. Instead of making a new array called "row" in your for loop, you can simply do intList[i]++.
(intList[i]++ and intList[i] = intList[i] + 1 and intList[i] += 1 are the same)
for (int i = 0; i < intList.length; i++) {
intList[i]++;
System.out.println ("intList [" + i + "]: " + intList [i]);
}
Also, it's more normal to make your for loop be
for (int i = 0; i < someArray.length; i++) {
//code
}
instead of what you did, which is
for (int i = someArray.length-1; i >= 0; i--) {
//code
}
Both of these do the exact same thing, but the first option is more "normal" and easier to read.
The issue there was that you are setting an int array equal to an int ( not an array element equal to an int ). I fixed the code for you:
class ArrayTask3 {
public static void main(String[] args) {
int [] intList = {5,20,32,7,9};
int sum = 0;
for (int i = intList.length-1; i >=0; i--) {
// you can directly set the element using this
intList[i] = intList[i]+1;
System.out.println ("intList [" + i + "]: " + intList [i]);
}
for (int counter=0;counter<intList.length;counter++)
sum = sum + intList[counter];
System.out.println ("Sum = " + sum);
}
}
intList is a single dimensional array so intList[i] is the int at position i in intList. I think what you want to do is increase the integer by one or intList[i]++; or intList[i] += 1;.
You are currently trying to loop through a 2-dimensional array or matrix by selecting rows. In which case you would need to define intList as an int[][] or an array of integer arrays.
for (int i = intList.length-1; i >=0; i--) {
/**
* I am not sure on what you want to do with this line.
* You can't assign an integer to array without reference
* If you want to copy the value of intList to row you can use int[] row = intList;
*/
int[] row = intList [i];
for (int j = 0; j < row.length; j++) {
row[j] = row[j] + 1;
}
System.out.println ("intList [" + i + "]: " + intList [i]);
}
Try using below code. It adds 1 to each number and prints the sum of all numbers at the end.
public static void main(String[] args) {
int[] intList = { 5, 20, 32, 7, 9 };
int sum = 0;
for (int i = 0; i < intList.length; i++) {
intList[i]++;
System.out.println("intList [" + i + "]: " + intList[i]);
sum += intList[i];
}
System.out.println(sum);
}
Related
Regardless of the programming language you use. You will undoubtedly encounter data while dealing with arrays, particularly duplicates, that you will want to get rid of.
This is my Output
I already inputted the correct syntax of even list array is there something that I missed?
Anyone knows how to remove duplicate element in my even list?
Here's my code:
import java.util.*;
import java.util.Iterator;
public class ArrayBubbleSortwithOddandEven {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size, temp;
System.out.print("Size of the list: ");
size = scanner.nextInt();
int number[] = new int[size];
int oddarray[] = new int[size];
int evenarray[] = new int[size];
int odd = 0;
int even = evenarray.length - 1;
for (int i = 0; i < number.length; i++) {
System.out.print("Input: ");
number[i] = scanner.nextInt();
}
for (int i = 0; i < size; i++) {
for (int swap = 1; swap < (size - i); swap++) {
if (number[swap - 1] > number[swap]) {
temp = number[swap - 1];
number[swap - 1] = number[swap];
number[swap] = temp;
}
}
}
for (int i = 0; i < number.length; i++) {
if (number[i] % 2 != 0) {
oddarray[odd++] = number[i];
} else {
evenarray[even--] = number[i];
}
}
for (int i = 0; i < number.length; i++) {
evenarray[even] = evenarray[i];
}
for (int i = 0; i < number.length; i++) {
oddarray[odd] = oddarray[i];
}
for (int i = 0; i < size; i++) { //Bubble sort
for (int swap = 1; swap < (size - i); swap++) {
if (evenarray[swap - 1] > evenarray[swap]) {
temp = evenarray[swap - 1];
evenarray[swap - 1] = evenarray[swap];
evenarray[swap] = temp;
}
}
}
System.out.println("Odd List:"); //Print Odd list
for (odd = 0; odd < oddarray.length; odd++) {
System.out.println("List " + odd + ": " + (oddarray[odd]));
}
System.out.println("Even List:"); //Print Even list
for (even = 0; even < evenarray.length; even++) {
System.out.println("List " + even + ": " + (evenarray[even]));
}
}
}
you can use a Set\HashMap to remember which number you already discover during your iteration. GOOD LUCK !
You can read about Data Structures - just google it :).
here a few questions that might help you understand.
Data Structures for hashMap, List and Set
Why key in HashMap can't be duplicated
how to find duplicate item position from set in java
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numberOfRows, numberOfColumns;
double arrayElements[][] = null;
int index[] = null;
System.out.print("Enter number of rows in array: ");
numberOfRows = keyboard.nextInt();
System.out.print("Enter number of columns in array: ");
numberOfColumns = keyboard.nextInt();
arrayElements = new double[numberOfRows][numberOfColumns]; //this command allocates memory for the array arrayElements
for (int row = 0; row < numberOfRows; row++)
{
for (int column = 0; column < numberOfColumns; column++)
{
System.out.print("Enter the Value for Row [" + row + "], Column " + "[" + column + "]: ");
arrayElements[row][column] = keyboard.nextDouble();
}
}
System.out.printf("\n Two-Dimensional Array: %d rows x %d columns\n", numberOfRows, numberOfColumns);
for (int row = 0; row < numberOfRows; row++)
{
System.out.printf("Row %3d:", row);
for (int column = 0; column < numberOfColumns; column++)
{
System.out.printf("%7.1f", arrayElements[row][column] );
}
System.out.println();
index = locateLargest( arrayElements );
}
}
public static int[] locateLargest( double[][] arrayx2 ){
}
Hello all,
I am trying to write a method for finding the largest element in a two-dimensional array, and return the index of the element with the highest value to the single-dimensional array 'index'. I have the signature written, but can anyone please help me figure out how to actually write the method that will search each element of the two-dimensional array and find the index location of the largest number?
Thank you so much!
/*Finds max value in an Array*/
public int maxValue(int array[]){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return Collections.max(list);
}
For 2 dimensional array use that:
int maxValue = 0;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray[i].length; j++) {
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
}
System.out.println("Max value of row " + i + ": " + maxValue);
}
Reference: https://stackoverflow.com/a/5877271/1848929
Firstly, if you want the returned array of your method to contain the largest element as well as the index, the return type should be double[] and not int[] since the type of the elements of the matrix is double. The method bellow will return an array containing three elements. the first element is the row index, the second is the column index, and the third is the element value. if you are going to use the code bellow, make sure to change the return type and also the type of index in your code to double[]. I hope this is helpful.
// first we assume the largest element is the one located at row 0, and
//column 0, then we compare it with the other elements in the matrix
public static double[] locateLargest( double[][] arrayx2 ){
double max = arrayx2[0][0];
int row = 0, col = 0;
double[] indexAndMaxVal = new double[3];
for (int i = 0; i < arrayx2.length; i++) {
for (int j = 0; j < arrayx2[i].length; j++) {
if (arraux2[i][j] > max) {
maxValue = arrayx2[i][j];
row = i;
col = j
}
}
}
indexAndMaxVal[0] = row;
indexAndMaxVal[1] = col;
indexAndMaxVal[2] = max;
return indexAndMaxVal;
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I have been working on this code for about a week; I am trying to make a program that generate random numbers and then sort them using the Bubble method, but I get this message "Bubble Sort: [I#ad3ba4". Does anyone see what is wrong I feel like this is so simple but I just can't find the problem.
import java.util.Random;
public class sortLibrary {
private static void bubbleSort(int[] list) {
int n = list.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - 1); j++) {
if (list[j - 1] > list[j - 1]) {
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}
System.out.println("\nBubble Sort: " + list);
}
public static void main(String args[]) {
System.out.println("Unsorted list:");
Random numbers = new Random();
int list[] = new int[20];
for (int i = 0; i < 20; i++) {
list[i] = numbers.nextInt(100);
}
for (int i = 0; i < 20; i++) {
System.out.print(list[i] + " ");
}
bubbleSort(list);
}
}
You cannot simply print a list with a println(). That is only for strings.
Instead, replace list in your println() with Arrays.toString(list) to convert the array to a string for printing.
Or, you can print it out as an array, similar to #KyleGowen's answer. Here's an alternate form of a way to iterate over an array in Java easier:
String arrayToString = "";
for(int item : list) {
arrayToString += item + ", ";
}
System.out.println("Bubble sort: [" + arrayToString.substring(0, arrayToString.length()-2) + "]");
This should also print it nicely.
See both of these at TutorialPoint's online Java compiler.
Now, you can not print Array in java just like that. If you want to print all array you need to use index or use something like this:
System.out.println("\nBubble Sort: " + Arrays.toString(list));
Also in your if statement you have list[j - 1] > list[j-1]. I think there will be list[j - 1] > list[j]. So your code looks like:
import java.util.Arrays;
import java.util.Random;
public class bubble {
private static void bubbleSort(int[] list) {
int n = list.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - 1); j++) {
if (list[j - 1] > list[j]) {
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}
System.out.println("\nBubble Sort: " + Arrays.toString(list));
}
public static void main(String args[]) {
System.out.println("Unsorted list:");
Random numbers = new Random();
int list[] = new int[20];
for (int i = 0; i < 20; i++) {
list[i] = numbers.nextInt(100);
}
for (int i = 0; i < 20; i++) {
System.out.print(list[i] + " ");
}
bubbleSort(list);
}
}
You are actually printing out the memory address of your list with
System.out.println("\nBubble Sort: "+list);
You will most likely want to loop through the list and print out the values. Something like:
System.out.print("\nBubble Sort: ");
for(int i = 0; i < list.length; i++){
System.out.print(list[i] + " ");
}
I hope this helps.
I am doing a project in which the user enters a number, x ,it will then generate x amount of random numbers and add them to an arraylist. In one text field, it will display however many random integers are in the array, I then have to make it so in another textfield, it sorts those numbers through a selection sorting. I'm pretty sure I have the code for it right, I'm just not sure how to get the sorted numbers to display on the text field #2. Heres what I have:
ArrayList <Integer> Numbers = new ArrayList <Integer>();
....
String input;
int int1,int2 = 0, min = -1000, max = 1000,j, maximum;
input = Input.getText();
int1 = Integer.parseInt(input);
Random number = new Random();
while(int2 < int1){
for (int i = 0; i < int1; i++){
int randomInt = number.nextInt(max - min + 1) + min;
Numbers.add(randomInt);
int1--;
}
}
if(Selection.isSelected() && Ascending.isSelected()){
for (int i = 0; i<Numbers.size()-1; i++){
maximum = i;
for(j = i+1; j<=Numbers.size()-1;j++){
if(j < i){
int temp = i;
i = j;
j = temp;
}
}
}
}
Output1.setText("Unsorted Numbers " + Numbers);
Output2.setText("Sorted Numbers " + //what here? );
Numbers.clear();
Thanks for any help you might be able to offer.
what about this ?
public static void main(String[] args) {
//min and max value
int min = -1000;
int max = 1000;
//collection to store numbers
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random random = new Random();
//receive input
Scanner myScanner = new Scanner(System.in);
int numberFromUser = Integer.parseInt(myScanner.nextLine());
for (int i = 0; i < numberFromUser; i++) {
numbers.add(random.nextInt(max - min + 1) + min);
}
System.out.println("Unsorted :" + numbers);
// sort the numbers
Collections.sort(numbers);
System.out.println("Sorted :" + numbers);
numbers.clear();
}
You should prepare a string:
String sortedNumbersOutput = "";
for (int i = 0; i < sortedNumbers.size(); i++) {
sortedNumbersOutput += sortedNumbers.get(i) + (i != sortedNumbers.size() - 1 ? "," : "");
}
Output2.setText("Sorted Numbers " + sortedNumbersOutput );
On a separate note, I don't believe you are sorting your list...
You are comparing on the indices and not the values at those indices.
Maybe you want to try:
boolean changes = true;
int temp;
while (changes) {
changes = false;
for (int i = 0; i < Numbers.size()-1; i++){
if (Numbers.get(i) > Numbers.get(i+1)) {
temp = Numbers.get(i);
Numbers.set(i, Numbers.get(i+1));
Numbers.set(i+1, temp);
changes = true;
}
}
}
which is called a bubble sort
I need to take single digit integers from the command line and put them into an array, and then find the most frequent integer. Sometimes this program seems to work, and other times, it doesn't.
public class MostFrequent {
public static void main(String[] args){
int num=0;
int[] freq= new int[9];//intialize array for integers 0-9
for (int i=0; i<args.length; i++){
try {
num = Integer.parseInt(args[i]);
freq[num]++;//adds to array counter
}
catch (NumberFormatException nfe) {
}
}
int max=0,j;
for (j=0; j<10; j++){
while(freq[j]>max){
max=freq[j];
}
}
System.out.println("The digit that appears most frequently is " + freq[j]);
}
}
Thanks everyone for your help, this is what ended up working for me, and thanks to whoever mentioned making the array more dynamic, that helped as well. Here is the code I finished with:
public class MostFrequent {
public static void main(String[] args){
int num=0;
int[] freq= new int[args.length];//intialize array for integers 0-9
for (int i=0; i<args.length; i++){
try {
num = Integer.parseInt(args[i]);
freq[num]++;//adds to array counter
}
catch (NumberFormatException nfe) {
}
}
int max=0,j;
for (j=1; j<args.length; j++){
while(freq[j]>freq[max]){//compares a max array val to the previous val
max=j;
}
}
System.out.println("The digit that appears most frequently is " + max);
}
}
The logic in your second loop is flawed. Also, you haven't allocated room for all digits in your array, you need an int[10] for this. One way to solve it is like this:
int[] freq = new int[10];//intialize array for integers 0-9
...
int maxindex = 0;
for (int j = 1; j < 10; j++){
if (freq[j] > freq[maxIndex]) {
maxIndex = j;
}
}
System.out.println("The digit that appears most frequently is " + j + ", that appears " + freq[j] + " times.";
Change your loop
int max=freq[0];
int maxIndex = 0;
for (j=1; j<10; j++){
if(freq[j]>max)
{
max=freq[j];
maxIndex = j;
}
}
Also, you have wrong output.
Instead of (that will give you last number)
System.out.println("The digit that appears most frequently is " + freq[j]);
Use (which prints max number and its number of occurence)
System.out.println("The digit that appears most frequently is " + maxIndex + " - " + max + "x");
Here is the implementation to find most frequent number.
#include<iostream>
using namespace std;
// Returns maximum repeating element in arr[0..n-1].
// The array elements are in range from 0 to k-1
int maxRepeating(int* arr, int n, int k)
{
// Iterate though input array, for every element
// arr[i], increment arr[arr[i]%k] by k
for (int i = 0; i< n; i++)
arr[arr[i]%k] += k;
// Find index of the maximum repeating element
int max = arr[0], result = 0;
for (int i = 1; i < n; i++)
{
if (arr[i] > max)
{
max = arr[i];
result = i;
}
}
/* Uncomment this code to get the original array back
for (int i = 0; i< n; i++)
arr[i] = arr[i]%k; */
// Return index of the maximum element
return result;
}
// Driver program to test above function
int main()
{
int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 8;
cout << "The maximum repeating number is " <<
maxRepeating(arr, n, k) << endl;
return 0;
}