Minimum value of an array [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I would like to write a program that reads an array of integers and finds the minimum value.
The first line contains the size of an array.
Output
An integer number representing the minimum in the input array.
Input:
5
5 1 4 2 3
My code:
import java.util.Arrays;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int[] c = new int[a ];
for (int i = 0; i < c.length; i++) {
c[i] = sc.nextInt();
}
Arrays.sort(c);
int b= c[0] > 0 ? c[0]: c[c.length -1];
for (int i =1; i < c.length - 1; i++){
if(c[i] < 0){
if(c[i] > b){
b = c[i];
}
}
else{
if (c[i] < b){
b= c[i];
}
}
}
System.out.println(b);
}
}
My output:
3
-1 -2 -3
What is wrong with my code?

You are making it more complicated than necessary. No need to sort the array. Just set a variable to be equal to the first value in the array. Then scan through the array setting the variable to the actual array element if it is less than the present variable value.

Related

readNumberAsArray assignment [closed]

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 3 years ago.
Improve this question
Write a readNumberAsArray method that takes an integer as a parameter and creates a new int array with that number as the length. Subsequently, a corresponding number of int values ​​should be read in with the aid of the IOTools and the array filled with them returned, whereby only single-digit numbers (0-9) should be taken into account as input. If the parameter is negative, the method should return null. For negative or two-digit value entries, the entered value should be replaced by 0. Use a for loop to read in the values. A text output when using the IOTools is not necessary.
My program is not working.
import Prog1Tools.IOTools;
package com.company;
public class Main {
public static void readNumberAsArray(int a) {
int [] a = new int[];
int a = IO.Tools.readInteger () ;
for int (a = 0 ; a<10 ; --a) {
System.out.println('0');
for (int a=0; a>10; a++) {
System.out.println(a);
for (int a=10; a=>10; a++) {
System.out.println('0');
}
}
}
// write your code here
}
}
I think you have to just implement what you're asked. Step by step. There's no special logic.
public int[] readNumberAsArray(int n) {
// negative or two-digit values should be replaced with 0
if (n <= 0 || n > 9)
return new int[0];
// creates a new int array with that number as the length
int[] arr = new int[n];
// corresponding number of int value should be read in with the aid of the IOTools
for (int i = 0; i < arr.length; i++)
arr[i] = IO.Tools.readInteger();
return arr;
}

Product of array elemetns [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I wanted to see better code/logic of the below questions from you guys.
Que: Say, there are two arrays - Input and Output array. Taking 4 elements in input array. O/p array will also have length of same as Input array. Output should have - first index value should product of all values from the rest of indexes except first. Similarly, second index value should have product of all other values from the rest of indexes except second. Likewise, the product should go till output array get the same length as that of input's. I have written code but I wanted to see different answers from different viewers. More customized and use of library functions is helpful. Customizing my code also is welcome.
System.out.println("Enter the size of the array..");
scan1 = new Scanner(System.in);
int n = scan1.nextInt();
int[] arr = new int[n];
System.out.println("Enter the array elements..");
for (int i = 0; i<n; i++)
arr[i] = scan1.nextInt();
System.out.println("Array is.." +Arrays.toString(arr));
int[] arr1 = new int[arr.length];
for (int i = 0;i<arr.length;i++){
int sum = 1, j = 0;
while (j<arr.length){
if(i==j)
System.out.println("I and J are equal");
else
sum = sum * arr[j];
j++;
}arr1[i] = sum;
}
System.out.println(Arrays.toString(arr1));`

Why is my code not executing the break statement? [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 8 years ago.
Improve this question
I'm writing a program where I have to write back out the numbers I am given until I get the number 42.
For example:
Input:
5
6
4
42
1
0
Output
5
6
4
So far, I have tried this:
package com.logical01;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of elements: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 0; i < n_Elements; i++) {
array[i] = in.nextInt();
}
for (int i = 0; i < n_Elements; i++) {
if (i == 42) {
break;
}
System.out.println("\n"+array[i]);
}
}
}
However, this program does not work; it writes back the same values out (rather than stopping when there's a 42).
You need to change from
if(i == 42)
to
(if array[i] == 42)
i holds the value while iterating.
You need to change the loop to this:
for(int i=0; i<n_Elements; i++){
if(array[i]==42){
break;
}
This is because you want to iterate through the array and check if the value at index i is 42,
e.g. array[4] = {1,2,42,3};
Then the loop iterates through the array and:
array[0] == 42 false
array[1] == 42 false
array[2] == 42 true therefore -> break;

Adding Elements in an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
items_arr = 4;
System.out.println("The elements in the array are: ");
for (int x = 0; x < items_arr; x++)
System.out.println("Array[" + x + "]=" + array[x]);
System.out.print("\n");
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
for (s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
for (s = 0; s < items_arr; s++)
System.out.println("Array[" + s + "]=" + array[s]);
break;
The output is. The elements are
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Enter an element to Insert: 5
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Array [4]= 0
when I insert 5 it posts 0
any suggestions please.. thanks!
To insert in to the array you shuould be doing follwoing operation
array[s]=input
Two notes here
Arrays are fixed length, and you should be checking the array length before inserting values in to that,other wise you will get ArrayIndexOBException. Safer to sue List/Set
As better coding practise, and to improve the readablity, you should be enclosing the conditional/loop statements (such as if or for) - see eg below
eg: 1
for (int x = 0;x<items_arr;x++) {
System.out.println("Array["+x+"]="+array[x]);
}
eg 2:
for(int s = 0; s < items_arr; s++) {
if (array[s] == input) {
break;
}
}
You have not inserted 5 in your array,
do something after items_arr++
array[ items_arr] = input;
If you do not insert any thing then by default every element is 0
You should be using a Collection type; I would recommend an ArrayList - that is -
List<Integer> al = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
al.add(i);
}
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
al.add(input); // And so on...
You are not updating/inserting the array with the new input.
for(s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
just replace the above code with
array[ items_arr] = input;
items_arr++;

Random numbers in java does not work properly [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to create a lottery program that creates four random numbers, each between 0 and 9 (inclusive). This program asks user to guess four numbers and compares each user guesses to four random numbers and displays the won message as:
No matches 0 points
Any one digit matching 5 points
Any two digits matching 100 points
Any three digits matching 2,000 points
All four digits matching 1,000,000 points
My program runs but it has some logic errors. For example,the output should be:
Random numbers:2 3 3 4
Guess numbers: 1 2 5 7-->1 matching digit
Guess numbers: 3 5 7 3-->2 matching digits
Guess numbers: 3 3 3 1-->2 matching digits
Guess numbers: 3 3 3 3-->2 matching digits
public class Lottery
{
public static void main(String[] args) {
final int LIMIT=10;
int totalCount=0;
int totalPoint;
Random random=new Random(); //creating object of random class
Scanner input=new Scanner(System.in);//creating object of scanner class
//declaring two arrays
int[] guessNumber= new int[4];
int[] randomNumber=new int[4];
for(int i=0;i<4;i++)
{
randomNumber[i]=random.nextInt(LIMIT);//returns value between 0 to 9(inclusive)
}
for(int i=0;i<4;i++)
{
System.out.println("Enter your first guess number from 0 to 9:");
guessNumber[i]=input.nextInt();
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (randomNumber[i] == guessNumber[j])
{
++totalCount;
break;
}
}
}
if(totalCount == 1)
{
totalPoint=5;
}
else if(totalCount == 2)
{
totalPoint=100;
}
else if(totalCount == 3)
{
totalPoint=2000;
}
else if(totalCount == 4)
{
totalPoint=100000;
}
else
{
totalPoint=0;
}
//dispalying points
System.out.println("You have earned " +totalPoint+ "points!!");
}
}
Looks to me like the problem is that once you've matched a particular digit, you ought to be removing it from circulation so that multiple guesses of the same value don't count as matches. One solution is to use an ArrayList for the randomNumber's and remove them when there's a match. If you replace what's between your // declaring two arrays comment and your totalPoint assignment with the following it seems to do what you requested in terms of your example.
int guess;
ArrayList<Integer> randomNumber = new ArrayList<Integer>();
for (int i = 0; i < 4; i++) {
randomNumber.add(random.nextInt(LIMIT));
}
for (int i = 0; i < 4; i++) {
System.out.print("Enter your guess number from 0 to 9: ");
guess = input.nextInt();
for (int j = 0; j < randomNumber.size(); ++j) {
if (randomNumber.get(j) == guess) {
++totalCount;
randomNumber.remove(j);
break;
}
}
}
input.close();
Note that I've chosen to process each guess as it's read rather than store them in an array and process them later.
It looks like your overall logic is fine.
If I understand correctly, you just want a different output.
Use something like this for your output.
String guessNumbers = "";
String randomNumbers = "";
for (int i = 0; i < 4; i++){
randomNumbers += randomNumber[i]+" ";
guessNumbers += guessNumber[i]+" ";
}
System.out.println("Random numbers: "+randomNumbers);
System.out.println("Guess numbers: "+guessNumbers+" --> # of matching digits "+totalCount);
System.out.println("You have earned " +totalPoint+ " points!!");
This is what it now prints:
Random numbers: 2 9 7 4
Guess numbers: 7 4 5 2 --> # of matching digits 3
You have earned 2000 points!!

Categories

Resources