JAVA: Passing an array to a method - java

I can't seem to pass my array to a secondary method. It only sees one of the 10 inputs, so I can't properly use it in the secondary method.
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter some numbers: ");
double [] numbers = new double [10];
int n = 0;
int i = 0;
while(n < numbers.length) {
numbers[i] = input.nextDouble();
n+=1;
}
System.out.println(min(numbers));
}
public static double min(double[] array) {
System.out.println(array[1]);
double smallest = array[0];
for (int l = 1; l < array.length; l++) {
if (array[l] < smallest) {
smallest = array[l];
System.out.println("Your smallest = " + smallest);
}
}
return 0;
}

In the first while loop, the variable i does not change.

while (n < numbers.length) {
numbers[i] = input.nextDouble();
n+=1;
}
variable i is never being changed so you are assigning each new number to the same spot in the array overwriting the previous number.
Just use your n variable instead:
while (n < numbers.length) {
numbers[n] = input.nextDouble();
n += 1;
}

Related

How to find the sum of all the numbers entered before or after finding the Sorted array list?

I have written a program in ArrayList to find the sorted array. But I have to find the sum of the numbers entered as well.
I couldn't succeed in getting the results as it is in the array list
import java.util.ArrayList;
import java.util.Scanner;
public class project1 {
public static void main(String[] args) {
int add = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter 5 numbers: ");
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 5; i++) list.add(input.nextInt());
System.out.println("add" +add);
System.out.println("Sorting numbers...");
sort(list);
System.out.println("Displaying numbers...");
System.out.println(list);
}
public static void sort(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i++) {
int currentMin = list.get(i);
int currentIndex = i;
for (int j = i + 1; j < list.size(); j++) {
if (currentMin > list.get(j)) {
currentMin = list.get(j);
currentIndex = j;
}
}
if (currentIndex != i) {
list.set(currentIndex, list.get(i));
list.set(i, currentMin);
}
}
}
}
I am looking to get the sum of the entered numbers along with sorting. Any help will be very appreciated.
change this
for (int i = 0; i < 5; i++) list.add(input.nextInt());
to this
int sum = 0;
for (int i = 0; i < 5; i++){
int num = input.nextInt();
list.add(num);
sum += num;
}
the value of the sum is saved inside sum and you can do what ever you want with it.
I am using the For loop to add the values the user entered to a var name sum that is located out side of the for loop and when the for loop is done you have the sum
You could just write sum += currentMin at the bottom of the for (int i; ... loop. This way you count every number exactly once, after it is put in its final place.
ArrayList<Integer> list = new ArrayList<>();
int sum = 0
for (int i = 0; i < 5; i++) {
int in = input.nextInt();
sum = sum + in;
list.add(in);
}

How to initialize variable back to 0 in a while loop in java?

I want my code to loop, but reinitialize the variable back to 0. Every time I input a number, it add it to the previous result, but I want it to reset. I attached two images below. One is the actual output and the other is the expected output.
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
Actual Output
Desired Output
You can use continue
if(n == 0) {
sum = 0;
total = 1;
continue;
}
You can initialize the variables inside the while loop
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
while (true) {
int sum = 0;
int total = 1;
int n = 0;
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
To zero a variable, simply assign 0 at the appropriate point.
sum = 0;
An appropriate place to insert this statement for your desired output is immediately before the first for loop. Likewise, reset total before the second for.
However, a much better way to write this is to declare the variable where it is needed, as you have done for x and y. This applies to am, sum, total and n
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("enter an integer number: ");
int n = input.nextInt();
if (n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
String am = input.nextLine();
if (am.equals("a")) {
int sum = 0;
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
int total = 1;
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
I don't know if I fully understand your question, but just do sum=0; and total=1; after you print out the final result. You should also consider doing a try/catch statement for robustness on the nextInt so that characters and strings don't break your program...
try {
n = input.nextInt();
}
catch (Exception e) {
System.out.println("Not a Number");
}

How do I iterate through an int

I get an "int cannot be dereferenced" It might be because .lenght on it, What else can I do to iterate through the int?
int num;
System.out.print("Enter a positive integer: ");
num = console.nextInt();
if (num > 0)
for (int i = 0; i < num.lenght; i++)
System.out.println();
for (int i = 0; i < num; i++)
Your num already is a number. So your condition will suffice like above.
Example: If the user enters 4, the for statement will evaluate to
for (int i = 0; i < 4; i++), running the loop four times, with i having the values 0, 1, 2 and 3
If you wanted to iterate over each digit, you would need to turn your int back to a string first, and then loop over each character in this string:
String numberString = Integer.toString(num);
for (int i = 0; i < numberString.length(); i++){
char c = numberString.charAt(i);
//Process char
}
If you wanted to iterate the binary representation of your number, have a look at this question, it might help you.
Note: though it might not be required, I would suggest you to use {}-brackets around your statement blocks, to improve readability and reduce chance of mistakes like this:
if (num > 0) {
for (int i = 0; i < num; i++) {
System.out.println();
}
}
IntStream.range(0, num).forEach(System.out::println);
Try the following code:
import java.util.Scanner;
public class IntExample {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = console.nextInt();
console.close();
if (num > 0) {
for (int i = 0; i < num; i++) {
System.out.println(i);
}
}
}
}
Using Integer.toString Method
int num = 110102;
String strNum = Integer.toString(num);
for (int i = 0; i < strNum.length(); i++) {
System.out.println(strNum.charAt(i));
}
Using Modulo Operator
`
int num = 1234;
while(num>0) {
int remainder = num % 10;
System.out.println(remainder);
num = num / 10;
}

Storing data in Arrays (Java)

I'm just a beginner in Java. Can someone please tell me how to arrange this program. In this program I want to store 10 marks in an array, and then output the ones that are equal to or greater than the average. Help would be appreciated.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
}
sum = sum + mark[c];
int average = sum / 10;
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}
You need loop the array twice. The first iteration sums all the elements and computes the average. And the other iteration outputs the elements that meet your constraints.
The code is below:
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
// The first iteration sums all elements
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
// This iteration outputs elements that meet your requirements.
for(int c = 0; c < 10; c++){
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}
}
You need to add another for loop to iterate your array after calculating the average. Here is the updated code with the required for loop:
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++) {
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++) {
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}
public class aver{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
int average;
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
}
for(int c = 0; c < 10; c++){
sum = sum + mark[c];
}
average = sum / 10;
for(int c = 0; c < 10; c++){
if(mark[c]>=average){
System.out.println(mark[c]);
}
}
}
}
sum = sum + mark[c];
statement must be inside your loop.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++)
{
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++)
{
if(mark[c]>=average)
{
System.out.print(mark[c]);
}
}
}
Just some modification in your code.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++){
if(mark[c]>=average)
System.out.print(mark[c]);
}
}
Explanation
You need to add each element to sum to get the total. So add each element within the for loop after taking input
you also need to check each element to compare with the average. So you need to iterate the array again to compare each element.

How to make Bubble Sort in Java to output the sorted numbers?

This is my code for the Bubble Sort. I cannot get the actual sorted values to output. The program reads the inputted numbers, but does not print it sorted.
I'm not sure what I have to do to make them sort.
Any advice or suggestions would be helpful.
package sortingalgorithm2;
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int[] num = new int[15];
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}
BubbleSort (num);
for (int i=0; i < num.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort(int[] num)
{
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;
}
}
}
Try this Bubble sort :
private static void BubbleSort(int[] num) {
for (int i = 0; i < num.length; i++) {
for (int x = 1; x < num.length - i; x++) {
if (num[x - 1] > num[x]) {
int temp = num[x - 1];
num[x - 1] = num[x];
num[x] = temp;
}
}
}
}
You are printing the actual numbers in the order the user entered. Try this instead:
int[] sortedNumbers = new int[15];
sortedNumbers = BubbleSort (num);
for (int i=0; i < sortedNumbers.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(sortedNumbers[i]+ " ");
}
public static int[] BubbleSort(int [] num)
{
int temp;
for (int i=1; i<num.length; i++)
{
for(int j=0; j<num.length-i; j++)
{
if (num[j] > num [j+1])
{
temp = num [j];
num [j] = num [j+1];
num [j+1] = temp;
}
}
}
return num;
}
Try this :
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
if (num[i] > num[j]) {
num[i] = num[i] + num[j] - (num[j] = num[i]);
}
}
}
you are passing the array variable num (which is not static) to BubbleSort()(which does not returns a value and shadows the global num variable with its own) and trying to use the same num variable to access your sorted array from your main method which is not right.
The genuine fix to this is to declare your variable num as static just before the main method( in the class declaration). So I have made the changes in the program and here is the solution.
import java.util.Scanner;
public class sol {
static int num [] =new int [15]; //declaring num as static in the class definition.
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
read.close();
/*for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}*/ //I have disabled this just to check with the sort method.
BubbleSort ();//no need to pass the array as it is static and declared as a //class variable hence can be used to by all the methods of that class
System.out.println("The sorted numbers are: ");
for (int i=0; i < num.length; i++)
{
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort()
{
for (int i=0; i < num.length; i++)// required changes in the looping
for (int x=0; x < num.length-i-1; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}

Categories

Resources