Multiplying a array times 2 [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In the last method, computeTwice, I am trying to multiply the array that is inputed by 2, but instead of doing that it is listing the array in least to greatest order. Can someone please help me fix that issue.
Code :
import java.util.Scanner;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int numbers[] = new int[10];
for (int i = 0 ; i < numbers.length; i++ ) {
System.out.println("Enter a number");
numbers[i] = console.nextInt();
}
printReverse(numbers);
getLargest(numbers);
computeTwice(numbers);
}
public static void printReverse(int [] numbers) {
int [] revNumbers = new int[numbers.length];
for(int i = numbers.length -1; i >= 0; i--){
revNumbers[numbers.length - 1 -i] = numbers[i];
}
System.out.println("Here are you numbers in reverse: "+Arrays.toString(revNumbers));
}
public static int getLargest(int [] numbers){
int max = 0;
for(int i = 0; i < numbers.length; i++){
if(numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("The highest number is: "+max);
Arrays.sort(numbers);
return max;
}
public static int[] computeTwice(int[] numbers){
for (int i = 0; i > numbers.length; i++){
numbers[i] *= 2;
}
System.out.println("The array with two times the numbers: "+ Arrays.toString(numbers));
}
}

Next time put a stack trace, since there is an error.
public static int[] computeTwice(int[] numbers){
for (int i = 0; i > numbers.length; i++){
numbers[i] *= 2;
}
System.out.println("The array with two times the numbers: "+ Arrays.toString(numbers));
}
}
How can i, the index of the array you are targeting, be greater than the length? Perhaps you meant
for (int i = 0; i < numbers.length; i++){

public static void computeTwice(int[] numbers){
for (int i = 0; i < numbers.length; i++){
numbers[i] *= 2;
}

One little error in your for loop. Look at your conditions. You initialized it correctly (i = 0), incremented it correctly (i++), but your condition is incorrect (i > numbers.length). You need to change it to
(i < numbers.length)
Also, when you create a method with a value type, you need to return that data type, otherwise create your method header with "void".
Since you created your method with the int[] value type, you need to return your int[], like so:
public static int[] computeTwice(int[] numbers) {
for(int i = 0; i < numbers.length; i++) { //note the condition change
numbers[i] = numbers[i] * 2;
}
System.out.println("The array with two times the numbers: " + Arrays.toString(numbers));
return numbers; //note the change by adding a return statement
}
}

Related

Garbage Value Picked Up by Scanner -- Java [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 months ago.
I am trying to sort an array in descending order. The size of the array comes from user input, and then the contents of the array come from user input. Then the array is passed to a function that sorts it. The issue is that, instead of printing a sorted array, it prints [I#5caf905d. Through print statements, I have pinpointed the problem to the scanner picking up [I#5caf905d as the final value from user input, coming right after all the correct inputs. I don't know where this value came from, and I also don't understand why it is printed by the function as if it were the entire array. All help is appreciated!
Here is my code. Input is: 5 10 4 39 12 2.
import java.util.Scanner;
public class LabProgram
{
public static void sortArray (int [] myArr, int arrSize)
{
int temp;
int i;
for (i = 0; i < arrSize - 1; i++)
{
if (myArr[i] < myArr[i + 1])
{
temp = myArr[i];
myArr[i] = myArr[i + 1];
myArr[i + 1] = temp;
}
}
System.out.println(myArr);
}
public static void main(String[] args)
{
Scanner scnr = new Scanner (System.in);
int [] myArr;
int arrSize;
int i;
arrSize = scnr.nextInt();
myArr = new int[arrSize];
for (i = 0; i < arrSize; i++)
myArr[i] = scnr.nextInt();
sortArray (myArr, arrSize);
}
}
You should use one of the simpliest sorting algorithm e.g. Selection Sort:
public static void selectionSortDesc(int[] arr) {
for(int i = 0; i < arr.length; i++) {
// k index with max value
int k = i;
// find k with max value
for(int j = i; j < arr.length; j++) {
if(arr[k] < arr[j])
k = j;
}
// swap current element with the max value
swap(arr, i, k);
}
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = arr[i];
}
By the way, you should not mix sorting and printing the array. It's better to split these parts.

Why this error of sorting occuring only in cases of >5 table elements?

please see my code for BubbleSorting. When I choose 5 or more numbers for my table to be sorted I get an error:
at first.firstt.sorting_v2.sorting(sorting_v2.java:35).
Completely do not know why it occured, when I choose 2 or three element to sort it works perfect.
I know it can be made different way, this type of sorting but please show me what I did wrong as still learn and I'm very curious about the details of this error hmm.
Also see the image below:enter image description here
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose how much number you want to sort:");
int sizeOfTab = scanner.nextInt();
int[] numbers = new int[sizeOfTab];
for (int i = 0; i < sizeOfTab; i++) {
System.out.println("Choose number to collection: ");
numbers[i] = scanner.nextInt();
}
scanner.close();
System.out.println(Arrays.toString(sorting(numbers)));
}
private static int[] sorting(int[] numbers) {
boolean notDone = false;
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
int tmp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = tmp;
notDone = true;
}
}
}
return notDone ? sorting(numbers) : numbers;
}
}
Your logical error is that you are always restarting your second inner loop from j = 1 aka the second element in
for (int j = 1; j < numbers.length; j++) { ... }
You only ever want to compare numbers[i] > numbers[j] for cases where j is greater than i.
Lets say you have the array [1, 2, 3, 4]
Currently your loop will run and reach a point where it will check numbers[2] > numbers[1] and switch the second and third element despite the array already being sorted.
To fix this simply always have your second loop start from the current value of i with 1 added:
for (int j = i+1; j < numbers.length; j++) { ... }

Get equal values within a stack

I'm doing a stack on java that this contains five integers but I have to print out only the values are equal.
Example 1 - 2 - 2 - 3 - 4
The same number is: 2
How can I determine which make the same numbers?
Here is my code:
package e.d_pilas;
import java.util.*;
public class ED_PILAS {
private int stck[];
private int tos;
ED_PILAS(int size){
//New stack
stck = new int[size];
tos = -1;
}
void push(int value) {
stck[++tos] = value;
}
int pop() {
if (tos < 0) {
return 0;
} else
return stck[tos--];
}
public static void main(String[] args) {
int number;
Scanner read = new Scanner (System.in);
System.out.print("Enter five (5) numbers to fill the stack \n");
ED_PILAS stack = new ED_PILAS(5);
for (int i = 1; i < 6; i++){
System.out.print("Enter the value "+i+" to fill the stack \n");
number=read.nextInt();
stack.push(number);
}
System.out.println("Equal values contained in the stack: \n");
for (int j = 1; j < 6; j++){
System.out.println("\t " + stack.pop());
}
}
}
Thank you!
In the first method it will print the duplicates entries only one time. in second method if stack contains more than two entries it will print multiple times.
ArrayList<int> list=new ArrayList<int>();
for (int j = 1; j < 6; j++){
int num=stack.pop();
if(list.contains(num)){
System.out.println(num);
}
else{
list.add(num);
}
}
OR
stack.pop() methods removes the element then use stack.search() method to find duplicates
for (int j = 1; j < 6; j++){
int num=stack.pop();
if(stack.search(num)==1){
System.out.println(num);
}
else{
}
}
While you do pop() from stack you can store in ArrayList<Integer> and check on every pop() if it already exists or not. If it repeats then print it and mark it as printed (so that you donot print it again).
Use this logic it will work for consecutive same values otherwise use ArrayList:
int n=stack.pop();
int dummy;
for (int j = 1; j < 6; j++){
dummy=stack.pop();
if(n==dummy)
{
System.out.println("\t The same number is " + n);
}
else{
n=dummy;
}
Use an ArrayList to store the previous pop'd values. If you see this value again during a pop, simply print the number.
ArrayList<Integer> popdList=new ArrayList<Integer>();
for (int j = 1; j < 6; j++){
int value=stack.pop();
if(popdList.contains(value){
System.out.println(value);
} else{
popdList.add(value);
}
}
More info on ArrayLists
Also, instead of changing your main function you could edit your pop function to only return the duplicate values like this:
ArrayList<Integer> popdList=new ArrayList<Integer>();
int pop() {
if (tos < 0) {
return 0;
} else {
int value = stck[tos--];
if(popdList.contains(value){
return value;
} else{
popdList.add(value);
}
}
}

Why am I getting an error saying "<variable> might not have been initialized"? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
This program will create an array of 10 integers. Each element in the array is initialized to 2. Each element of the array is then added up to get a total for the entire array. The answer we are expecting is 20. See if you can correct the following code to produce the correct solution.
How come I get an error saying that sum might not have been initialized even if i did it in the for loop?
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[12];
int total=0;
for (int i = 0; i < 10; i++){
myArray[i] = 2;
}
for (int i = 0; i < 12; i++){
int sum = 0;
int sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}//end class WarmUp_01_22_2014
You aren't getting that message with that code; this won't compile because sum isn't visible to println. Most likely, you have a declaration of an int sum in the main body, and then you declare another int sum inside the loop. You only want to "create" the variable once, and then just assign values to it.
I suspect that you're really using total in your program; just change your second for loop to this:
for (int i = 0; i < 12; i++){
total += myArray[i]; // the variable "total" was created and set to zero above
}
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[12];
int total=0;
int sum = 0;
for (int i = 0; i < 10; i++){
myArray[i] = 2;
}
for (int i = 0; i < 12; i++){
sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}//end class WarmUp_01_22_2014
Should work. Declare your variable higher up so it can be accessed by the println() method.
A few things:
an array of size 10 integers means that you need to write new int[10] instead of new int[12]
you declared sum inside of the for loop, so it is not accessible outside of that for loop (because there is no guarantee that it will even be declared).
you are also redeclaring sum in every loop by writing int sum += myArray[i] - only declare once
i < 12 and i < 10 can be changed to be i < myArray.length to make it more general.
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[10]; // size 10, not 12
int sum = 0; // declare sum here
for (int i = 0; i < myArray.length; i++){ // < myArray.length
myArray[i] = 2;
}
for (int i = 0; i < myArray.length; i++){ // < myArray.length
sum += myArray[i]; // add on to the sum, don't declare it here
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}
How to solve the problem
A simple adjustment such as (i) bringing the declaration before entering the loop and (ii) changing the value type (int) when using variable sum the second time to avoid conflict will do the trick:
public class WarmUp_01_22_2014{
public static void main(String[] args) {
int[] myArray = new int[12];
int total = 0;
for (int i = 0; i < 10; i++) {
myArray[i] = 2;
}
//declare varaible here to avoid error
int sum = 0;
for (int i = 0; i < 12; i++) {
//change int sum+=myArray[i] to sum+=myArray[i]
sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}
Reasoning
When the compiler compiles the source code, it still doesn't know that a variable such as sum does exists. According to the compiler, the variable sum is created only if the for loop is activated (which we as humans know is inevitable but the machine doesn't).

Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000

this code doesn't function,
it said that lessthaAverage(int) in calculateArray cannot be applied to (), I'm a beginner so I still don't understand this coding yet, this is the question ask, Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000.
Calculate the occurrences of number more than 500 and find the average of the numbers.
Count the number which is less than the average and finally sort the numbers in descending order.
Display all your output. Please do HELP ME!!!,Thank You...
import java.util.*;
import java.io.*;
//import java.util.random;
public class CalculateArray
{
//declare attributes
private int arr[] = new int[1000];
int i;
//generates an array of 1000 integers between 1 to 1000
public void genArr()
{
Random ran = new Random();
for(i = 0; i < arr.length; i++)
{
arr[i] = ran.nextInt(1000) + 1;
}
}
//Calculate the occurences of number more than 500
public int occNumb()
{
int count;
for(i = 0; i < arr.length; i++)
{
if(arr[i] > 500)
{
count++;
}
}
return count;
}
//find the average of the numbers
public int average()
{
int sum, aver;
for(i = 0; i < arr.length; i++)
{
sum += arr[i];
}
aver = sum/1000;
return aver;
}
//Count the number which is less than the average
public int lessthanAverage(int aver)
{
int cnt;
cnt = 0;
for(i = 0; i < arr.length; i++)
{
if(arr[i] < aver)
{
cnt++;
}
}
return cnt;
}
//finally sort the numbers in descending order.
public void sort(int[] num)
{
System.out.println("Numbers in Descending Order:" );
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
//Display all your output
public void display()
{
int count, aver;
System.out.println(arr[i] + " ");
System.out.println("Found " + count + " values greater than 500");
System.out.println("The average of the numbers is " + aver);
System.out.println("Found " + count + " values that less than average number ");
}
public static void main(String[] args)
{
CalculateArray show = new CalculateArray();
show.genArr();
int c= show.occNumb();
show.average();
int d=show.lessthanAverage();
show.sort(arr);
show.display();
}
}
Your method lessthanAverage is expecting a int parameter. You should store the result of the average method call into a int variable and pass it to the call to lessthanAverage.
int avg = show.average();
int d=show.lessthanAverage(avg);
Your lessthaAverage() method expects an average to be passed in as a parameter, but you are not passing it in when you call it.
It seems that your method lessthanAverage needs an int as a parameter, but you are not passing it in main
public int lessthanAverage(int aver)
In main aver is not being passed:
int d=show.lessthanAverage(); // where is aver?
But if you wanted to know the average inside the method you could call your average method inside lessthanAverage:
if(arr[i] < this.average())
and not pass any parameter at all:
public int lessthanAverage()

Categories