Input has to taken by the user. My code is given below. Why does it only output zeroes? What is the solution?
Output of the program is 0 0 0 0 (total number of input taken).
import java.util.Arrays;
import java.util.Scanner;
public class atlast {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] array = new int[107];
for (int i = 0; i < n; i++) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; i++) {
System.out.print(array[i] + " ");
}
}
}
int[] array = new int[107];
You are initializing a table that contains 107 value of 0.
So, if the n is small, the first elements will be 0.
To see the result replace n in the last loop by 107 and you will see the values
You initialized an array with size 107 which implies there are 107 zeroes in the array initially before accepting the input from the user. Since there are four zeroes in the output, you must have taken 4 values for input. So there are four non-zero values and 103 zero values in the array. When you apply Arrays.sort 103 zeros comes before 4 non-zero values. Hence when you print n values (which is 4 in this case) you get only zeroes.
You could use ArrayList instead so that numbers will be initialized only when user enters it.
Related
I have created a program previously using the BubbleSort method that works to sort numbers in a list that already exists, however, I am having difficulty with trying to manipulate this program in order to allow a user to input the list of numbers to be sorted instead. So far I have:
import java.util.Scanner;
public class MedianValue {
public static void main(String[] args) {
//use scanner to input list of numbers to sort
Scanner scan = new Scanner(System.in);
int[] numbers = new int[] {scan.nextInt()};
//nested for loop
//outer loop just iterating
//inner loop going through and flipping
//checking if out of order (if statement)
int counter = 0;
//outer loop: keep doing this until it's sorted
for(int i = 0; i < numbers.length - 1; i = i + 1)
//put in a inner loop number.length times minus one because we don't want to swap the last element
for(counter = 0; counter < numbers.length - 1; counter = counter + 1)
{
if (numbers [counter] > numbers [counter + 1])
{
int temporary = numbers [counter];
numbers [counter] = numbers [counter + 1];
numbers [counter + 1] = temporary;
}
}
for(int i =0; i < numbers.length; i = i + 1)
{
System.out.print(numbers[i] + " ");
}
}
}
But, in this program, instead of sorting the inputted numbers, the program simply prints the first number that is inputted by the user. I am not sure if I need to move where my scanner function is placed, or add on to it within the loop for it to sort all of the numbers as I want it to do. I am lost on where to change the program if that is the case.
That's because int[] numbers = new int[] {scan.nextInt()}; is a single assigment. scan read a single input and assign to number[0].
You actually need to modify your code for scan to read n numbers and store in n-sized numbers.
something like.
int[] numbers = new int[scan.nextInt()];
for( int i = 0; i < numbers.length; i++)
numbers[i] = scan.nextInt();
The code int[] numbers = new int[] {scan.nextInt()}; will always create an array (not a List) of size 1.
Usually in these kinds of assignments you get n + 1 numbers, for example 5 3 6 2 4 1 would mean "I'm going to give you five numbers. Oh here they are: 3 6 2 4 and 1!"
You probably want something like int[] numbers = new int[scan.nextInt()]; - then loop from 0 to numbers.length to fill the array.
I am doing the Hackerrank questions to get better at solving puzzles. I've been working on the Simple Sum Array question in the Data Structures section for nearly 2 hours O_O
I seriously thought I solved it because I tested it on the terminal on my mac and it ran fine, but when I submit the code in Hackerrank, it failed all 3 test cases T_T
I don't understand where the problem is and why the test cases failed. Does anyone see the problem? Please help.
Below is the code:
import java.io.*;
import java.util.*;
public class Solution {
public static int sumArray( int[] arr ){ //arr stands for the array to pass in
int result = 0;
for (int i = 0; i < arr.length; i++){
result = result + arr[i];
}
return result;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner input = new Scanner(System.in);
System.out.println("Print out the size of the array: ");
int size = input.nextInt();
int[] array = new int[size];
System.out.println("Type out the numbers you want in the array. One line only, each number is separated by a space");
String numbers = null;
String[] splitString = null;
while ( input.hasNextLine() ){
numbers = input.nextLine();
splitString = numbers.split("\\s");
if (splitString.length == size){
break;
}
}
//splitString = numbers.split("\\s");
int i = 0;
for (String s : splitString){
//System.out.println(s);
array[i] = Integer.parseInt(s);
i++;
}
System.out.println( sumArray(array) );
}
}
Also, here's the Hackerrank question to clarify what they wants:
Given an array of integers, can you find the sum of its elements?
Input Format:
The first line contains an integer, denoting the size of the array.
The second line contains space-separated integers representing the array's elements.
Output Format:
Print the sum of the array's elements as a single integer.
Sample Input:
6
1 2 3 4 10 11
Sample Output:
31
From the first time seeing your code you have two issues:
1- arr.length should be arr.length - 1
Because, your iteration starts from 0 and length not
2- the way you print your array is wrong
Because, you should use something like this:
Arrays.toString(array)
I needed an array that takes integers from a user until '0' is entered; then it prints average, max and min. I wrote an array with 700 elements and it breaks. When I input 0 everything works well. The problem is when I input 0 it takes 0 as an element. I solved that somehow so it can calculate the average correctly but it still takes some 0 from somewhere. For example, I input 8 and then 3 and then 0, and the output is the average is 4.000000, the biggest one is 5, the smallest one is 0, but the smallest one should be 3.
I guess it's because the remaining 697 elements are considered as 0.
I found a lot of answers for this problem but I want to solve it without copying the array or creating a new one. Is there anything that I can do to fix this without adding an array or another for loop or something? Like a line that means 'when the 0 is entered remove all remaining elements and don't use them for anything'?
import java.util.Scanner;
import java.util.stream.IntStream;
public class PlayingWithNumbers2 {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
int[] array = new int[700];
System.out.println("Enter numbers enter 0 to end");
int i;
int max = array[0];
int min = array[0];
int a = array[0];
for (i = 0; i < array.length; i++) {
a=input.nextInt();
if(a==0){
break;
}
array[i] = a;
if(array[i]>max)
max = array[i];
else if(array[i]<min)
min = array[i];
}
double sum = IntStream.of(array).sum();
double Ave = sum/i;
System.out.printf(" The Average is %f \n the biggest one is %d \n the smallest one is %d", Ave, max, min);`
}
}
The problem with the min/max is both are initialized to array[0] which means both are initialized to '0' and so the min check will always keep it at 0 as it is below anything you enter. You also need to remove the else condition. Try this
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
then inside the loop change the checks to be
if(array[i]>max)
max = array[i];
if(array[i]<min)
min = array[i];
You can use range():
double sum = IntStream.of(array).range(0, i).sum();
double Ave = sum/(i-1);
In this way, you'll be counting only numbers that are truly entered by the user and leave 'fake' 0 out of your sum.
In this lab, you will be creating a program that merges two arrays of non-negative (equal to or greater than 0) integers. Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter a negative number. You may disregard any negative numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
After the two arrays have been input, your program must check to make sure the elements of each array have been entered in order. If an out of order element is found, print the message “ERROR: Array not in correct order”.
Your task is to merge the two input arrays into a new array, with all elements in order, lowest to highest. Print out each of the original arrays entered, followed by the merged array.
Please note that your program must output the arrays with exactly one space between each of the numbers.
Sample Run 1:
Enter the values for the first array, up to 10000 values, enter a negative number to quit
3
3
5
6
8
9
-1
Enter the values for the second array, up to 10000 values, enter a negative number to quit
3
4
5
6
-5
First Array:
3 3 5 6 8 9
Second Array:
3 4 5 6
Merged Array:
3 3 3 4 5 5 6 6 8 9
Sample Run 2:
Enter the values for the first array, up to 10000 values, enter a negative number to quit
4
5
7
2
-1
Enter the values for the second array, up to 10000 values, enter a negative number to quit
3
3
3
3
3
3
-100
First Array:
4 5 7 2
Second Array:
3 3 3 3 3 3
ERROR: Array not in correct order
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
import java.lang.Object;
import java.util.Arrays;
import java.util.ArrayList;
import org.apache.commons.lang3.ArrayUtils;
class Main
{
public static void main (String str[]) throws IOException {
{
Scanner scan = new Scanner(System.in);
int[] arrayone = new int[10000];
int[] arraytwo = new int[10000];
int [] mergeQ = new int[arrayone.length + arraytwo.length];
int integers = 0;
int inte = 0;
System.out.println("\nEnter the values for the first array, up to 10000 values, enter a negative number to quit");
for (int i = 0; i < arrayone.length; i++)
{
arrayone[i] = scan.nextInt();
if (arrayone[i] < 0){
break;
} else {integers ++;}
}
System.out.println("\nEnter the values for the second array, up to 10000 values, enter a negative number to quit");
for (int i=0; i<arraytwo.length; i++)
{
arraytwo[i] = scan.nextInt();
if (arraytwo[i] < 0)
{
break;
} {inte ++;}
}
System.out.println("First Array:");
for (int i=0; i< integers; i++)
{
System.out.print(arrayone[i] + " ");
}
System.out.println("\nSecond Array:");
for (int i=0; i< inte; i++)
{
System.out.print(arraytwo[i] + " ");
}
System.out.println("\nMerged Array:");{
String[] both = ArrayUtils.addAll(arrayone[integer], arraytwo[inte]);
Arrays.sort(both);
}
}
}
}
you were adding elements but not the arrays themselves.
In you second loop
}{ inte++; }
change this to
}else {inte ++;}
one solution could be
int[] both = ArrayUtils.addAll(Arrays.copyOf(arrayone, integers), Arrays.copyOf(arraytwo,inte));
Arrays.sort(both);
for (int i=0; i< both.length; i++){
System.out.print(both[i] + " ");
A very bad way to do it.. but will work in your CS class
for (int i=0; i< integers; i++){
mergeQ[i] = arrayone[i];
}
for (int i=integers; i< inte + integers; i++){
mergeQ[i] = arraytwo[i - integers];
}
int both[] = Arrays.copyOf(mergeQ,integers+inte);
Arrays.sort(both);
for (int i=0; i< both.length; i++){
System.out.print(both[i] + " ");
}
Note: this way is pretty evil.. memory inefficient.. etc..
Here is another way it is a bit cleaner but roughly has the same performance as the one above..
System.arraycopy(arrayone, 0, mergeQ, 0, integers);
System.arraycopy(arraytwo, 0, mergeQ, integers, inte);
int both[] = Arrays.copyOf(mergeQ,integers+inte);
Arrays.sort(both);
for (int i=0; i< both.length; i++){
System.out.print(both[i] + " ");
}
Okay here's a Java assignment I've been having trouble with. I asked earlier about this and got some good comments and advice, but have since understood the assignment more clearly and the issue has changed a bit. So here's the assignment:
***
Your task is to complete the program below by writing three methods (askInfo, copyInfo and setArray). Program should ask for integers (max 100 integers) until the users types in zero. Integers can vary from one to one hundred and they are stored in an array that has 100 elements. Numbers are asked for with the askInfo method, which receives the array with numbers as parameter. Method returns the number of integers. The number zero is not saved in the array; it is merely used to stop giving input. The given numbers are then copied to another array which size is the amount of given numbers. Copying is done with copyInfo method which receives both arrays as parameters. After this the elements of the new array are put in ascending order with setArray method and printed on screen with printArray method.
Program to complete:
import java.util.*;
public class RevisionExercise {
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(realArray, tempArray);
setArray(realArray);
printArray(realArray);
}
// Your code here
public static void printArray(int[] realArray ) {
System.out.println("\Ordered array: ");
for(int i = 0; i < realArray .length; i++) {
System.out.println(realArray [i]);
}
}
Example print:
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
9
8
6
5
3
I'm struggling with the askInfo method. So far I've written this but it returns only zeroes. Here's my askInfo method:
public static int askInfo(int[] tempArray) { //askinfo-metodi
Scanner reader = new Scanner(System.in);
int i;
for (i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
tempArray[i] = reader.nextInt();
if (tempArray[i] == 0) {
return tempArray[i];
}
}
return tempArray[i];
}
***
How can I make it to register the input and get the amount of numbers to be passed to the next method in the assignment as described in the assignment.
You never store your integer luku values in your array, so your array never changes from the default initialized integer values of all zeroes. Inside your loop, you need to add an
tempA[i] = luku;
After the if-statement confirms that luku is not 0. All in all:
if (luku == 0) {
return i;
}
tempA[i] = luku;