I am tasked with several objectives in my assignment, I am to read a file, which i believe I did correctly, and from that file of integers, put it into an array. It wont let me compile the code, it comes up with an error at smallest. So, how do I printout the method of the min?
public class jlrogers2 {
public static void reader(int[] arr) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("numbers.txt"));
int i = 0;
while(scanner.hasNextInt())
{
arr[i++] = scanner.nextInt();
}
}
public static int minnimum(int[] arr){
int smallest =arr[0];
for (int i = 1; i>arr.length; i++){
if (arr[i] > smallest)
{
smallest= arr[i];
System.out.println(smallest);
}
}
return smallest;
}
public static void main(String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
System.out.println(minnimum(smallest)) // here is my issue }
}
}
Change for (int i = 1; i>arr.length; i++) to for (int i = 0; i<arr.length; i++)
And also your logic to find smallest is wrong. Actually you are finding the largest.
To find smallest put it as
if(arr[i] < smallest ) inside for loop
Change the main as
public static void main(String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
int arr[] = new int [200];//change this according to the requirement
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
reader(arr);
System.out.println(minnimum(arr));
}
}
There seem to be many problems with your code:-
->First as others have pointed change for (int i = 1; i>arr.length; i++) to for (int i = 1; i<arr.length; i++)
-> variable int smallest used, is not a class level variable and also is never locally declared in main()
-> method minimum() is never called from main, also method reader() seems to be not called
-> close the scanners after use, call scanner.close() at method end
Make some changes hence:-
-> main() would now look like:-
public static void main(String [] args) throws FileNotFoundException
{
int[] arr=new int[100];
reader(arr);//call this to populate arr[]
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
System.out.println(minnimum(arr));
}
in.close();
}
To find smallest element you need to change your loop like this:
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
Related
I am creating this code where I am supposed to prompt the user for a maximum of 5 integer numbers. I should store the 5 integers in an array by asking the user to enter them until the array is full or the user exits by entering -99. Then I should print out all the values of the array and calculate the average. The problem is that when I scan and store the values it shows me a null value of 0 of the fifth number instead of the number itself and it does not count it with the sum. This is the piece of code I've been working with:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num==-99 || i==4){
for(int k=0; k<i+1; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/i);
cond = true;
}
number[i] = num;
i++;
}while(!cond);
}
This is the input : 1 2 3 4 5
Every number is on a separate line
This is the output:
run:
1
2
3
4
5
1
2
3
4
0
2.5
number[i] = num;
is what adds the number the user entered to the array. If they enter -99, it's in the correct place. If they've simply entered all 4 however, it is in the wrong place. Also, you have it so it is actually dividing by the wrong number. Something like this should work:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num!=-99){
number[i] = num;
i++;
}
if(num==-99 || i==5){
for(int k=0; k<i; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/(i));
cond = true;
}
}while(!cond);
}
Also, do while loops are really ugly, and you can do it much smoother with just two for loops:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] number = new int[5];
double sum = 0;
int num=0,i;
for(i=0;i<5&&num!=-99;i++){
num = scan.nextInt();
number[i] = num;
}
for(int k=0;k<i;k++){
System.out.println(number[k]);
sum+=number[k];
}
System.out.println(sum/(i+1));
}
This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 6 years ago.
This is my first time with arrays.
I should prompt the user to enter 5 array values and then display them in random order.
I am quite confused, since it's my first time doing this.
Anyway, my code is here.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length - 1; i--) {
int j = (int) (Math.random() * (i + 1));
myArray[i] = input.nextInt();
System.out.println("The numbers are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
int temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
System.out.println("The numbers, shuffled, are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
}
}
}
Thank you everyone for your support.
A - Explanation
Let's say you take the input values in order as {'1','2','3','4','5'}. What shuffling is corrupting the order randomly, so you have to change the position of elements randomly.
In the demo code,
swapArrayElement swaps the elements those that positions are passed as parameters.
getRandom returns a random value between 0 and the range which passed to the method as a parameter.
shuffleArray shuffles the array by changing the positions of elements randomly. Please notify that there is an additional boolean isShuffled[] array and it is boolean because we have to keep the track of positions whether they are shuffled or not.
isArrayShuffled method, checks that if all positions are shuffled or not.
B - Demo Code
import java.util.Scanner;
public class Test {
public static final int ARRAY_LENGTH = 5;
public static void main(String[] args) {
int myArray[] = new int[ARRAY_LENGTH];
Scanner input = new Scanner(System.in);
System.out.println("Please enter 5 numbers: ");
for(int i = 0; i < myArray.length; i++)
myArray[i] = input.nextInt();
System.out.println("\nThe numbers are: ");
printIntArray(myArray);
shuffleArray(myArray);
System.out.println("\nThe numbers, shuffled, are: ");
printIntArray(myArray);
input.close(); // no memory leaks!
}
// method for printing array
public static void printIntArray(int[] array) {
for(int i = 0; i < array.length; i++)
System.out.printf("%2d ", array[i]);
System.out.printf("%n"); // use %n for os-agnostic new-line
}
// method for shuffling array
public static void shuffleArray(int[] array) {
int range = array.length;
boolean isShuffled[] = new boolean[range]; // store which positions are shuffled
while(!isArrayShuffled(isShuffled)) {
int positionSrc = getRandom(range);
int positionDst = getRandom(range);
swapArrayElement(array, positionSrc, positionDst);
isShuffled[positionSrc] = true;
isShuffled[positionDst] = true;
}
}
public static int getRandom(int maxRange) {
return (int)(Math.random()*maxRange);
}
public static void swapArrayElement(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static boolean isArrayShuffled(boolean[] isShuffled) {
for(int i = 0; i < isShuffled.length; i++)
if(isShuffled[i] == false)
return false;
return true;
}
}
C - Demo Output
Please enter 5 numbers:
1 2 3 4 5
The numbers are:
1 2 3 4 5
The numbers, shuffled, are:
4 2 5 1 3
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void shuffle(int[] arr) {
Random rnd = ThreadLocalRandom.current();
for (int i = arr.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int t = arr[index];
arr[index] = arr[i];
arr[i] = t;
}
}
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("Enter " + (i + 1) + ". number: ");
myArray[i] = input.nextInt();
}
System.out.println("The numbers are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
shuffle(myArray);
System.out.println("The numbers, shuffled, are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
}
}
I've been asked to do the following problem:
Implement a method that accepts an array of integers as input and returns the sum of all of the elements in the array as output.
this is what i have(the entire program):
import java.util.*;
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}
every time I try to call the method "sum" in the main method it gives me an error. I have tried every possible way I've seen on the internet to call the method. I'm not sure how I'm supposed to call it or if it is an issue because I have an array passed to the method.
Someone please help! and if you see that i've done something incorrectly, please let me know! thanks
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
// this works
System.out.println("sum is " + sum(array));
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}
I am new at java programming and am working on an exercise where the user is to input ints into an array and then stop the user input by entering a negative int value. All works well except the array prints 0 beyond the user input. So if a user enters 5 values and then one negative value only the five values should print not the user input values and 95 0s.
Any assistance would be greatly appreciated.
Here is my code:
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array [i] < 0)
{
break;
}
}
for (int i =0; i<array.length; i++)
{
System.out.println(array[i]);
}
}
When you declare an int in Java, it will default to 0 if you do not specify a value for it. When you declare your array,
int array[] = new int [100];
You are essentially making an array of 100 0's. You can see a small example of this by running the following code:
public static void main(String[] args) throws Exception {
int array[] = new int [1];
System.out.println("The value of i is: " + array[0]);
}
What you could do, is store the negative value into your array, and then stop printing if you reach that value.
for (int i =0; i<array.length; i++){
if(array[i]<0){
break;
}
System.out.println(array[i]);
}
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
int totalValuesEntered = 0;
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array[i] < 0)
{
totalValuesEntered = i;
break;
}
}
System.out.println("Your entries are:");
for (int i =0; i<totalValuesEntered; i++)
{
System.out.println(array[i]);
}
}
You are looping 100 times no matter what on the last loop, and you are saving the userinput no matter what they enter.
In order to achieve what you want. Declare a new integer enteredValues to count how many values the user entered before exiting.
public static void main(String str[]) throws IOException {
Scanner scan = new Scanner(System. in );
int array[] = new int[100];
System.out.println("Enter values up to 100 values, " +
"enter a negative number to quit");
int enteredValues = 0;
for (int i = 0; i < array.length; i++) {
int userInput = scan.nextInt(); //save nextInt to a variable
if (userInput >= 0) {
array[i] = userInput;
enteredValues++;
} else{
break;
}
}
for (int i = 0; i < enteredValues; i++) {
System.out.println(array[i]);
}
}
A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented