How to find the random index in an array? - java

Create 8 randomly generated integer values between 1 to 50. DONE
Display the series of values on screen. DONE
Users has to enter value. Find index & display.
if value cannot be found, display -none.

This is pretty easy. As you already completed step 1 and 2 you just have to ask the user for an input, search your array and output the index, if the input matches a value in the array.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int[] numbers = new int[8];
for(int i = 0; i < 8; i++) {
numbers[i] = random.nextInt(50) + 1;
System.out.print(numbers[i] + ", ");
}
System.out.print("\nInput value: ");
int input = scanner.nextInt();
boolean found = false;
for(int i = 0; i < numbers.length; i++) {
if(input == numbers[i]) {
System.out.println("Index: " + i);
found = true;
}
}
if(!found) {
System.out.println("none");
}
}

Related

The program don’t seem to work if there is a duplicate number in the array

If the user searches a number within the array, the system should print out the index that the number is located, if not it would print out search not found. As of now, it works only if there are no duplicate numbers in the array.
I tried removing the break but that would stop the program from printing the second index that also contains the search number.
Any help would be greatly appreciated, thank you!
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
array[0] = 6;
array[1] = 2;
array[2] = 8;
array[3] = 1;
array[4] = 3;
array[5] = 0;
array[6] = 9;
array[7] = 8;
System.out.print("Search for? ");
int searching = Integer.valueOf(scanner.nextLine());
for (int i = 0; i < array.length; i++) {
int input = array[i];
if (searching == input) {
System.out.println(searching + " is at index " + i);
break;
}
else if (searching != array[i] && i == (array.length - 1))
{
System.out.println(searching+" was not found!");
break;
}
}
}
Scanner scanner = new Scanner(System.in);
int[] array = {6,2,8,1,3,0,9,8};
System.out.print("Search for? ");
int searching = scanner.nextInt();
ArrayList positions=new ArrayList();
for (int i = 0; i < array.length; i++) {
int input = array[i];
if (searching == input) {
positions.add(i);
}
}
if(positions.size()>0) {
for(int x=0;x<positions.size();x++) {
System.out.println(searching+" is at index "+ positions.get(x));
}
}
else {
System.out.println(searching+" was not found!");
}
To receive an int with a scanner it is easier to use the nextInt () method. In the first for you can accumulate the positions where the number that is searched for in an arraylist matches, then you check that the arraylist is not empty and you print all the positions in which the number has been found. If the list is empty, the message of not found is printed.

Stop and print array from user input

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]);
}
}

array while loop output Java

Ok, i got this working while loop that lets the user insert random numbers, if the number is 0 or if the loops length has been achieved then it will stop, now i have to output all the numbers that was inputed and the amount of the inputs (example 1, 2, 3 amount = 3). How do i output the array? i only get 0 from the println.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0 || a1[i] == a1.length){
break;
}else{
tal += a1[i];
}
}//End of while
System.out.println("The inserted numbers are are: " + a1[i]);
}//
First of all, store tal in array and increment i every time you store. Finally iterate through array to print elements entered
import java.util.Scanner;
public class Tset {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0||i>=100){
break;
}else{
a1[i]=tal;
i++;
}
}//End of while
System.out.println("The inserted numbers are are: ");
for(int j=0;j<i;j++){
System.out.println(a1[j]+"\t");
}
System.out.println("amount is: " +i);
}//
}
Use an ArrayList instead of an array to collect the number input and then iterate over it to print them use its built-in lenght method to output the amount
I am not sure what you are trying to do, but this might help.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a1 = new int[100];
int i = 0;
int tal = 0;
int tmp;
do {
System.out.println("Insert number (0-end):");
tmp = scan.nextInt();
a1[i] = tmp;
tal += a1[i++];
} while (tmp != 0 && i < a1.length);
System.out.println("The inserted numbers are : ");
for (int j = 0; j < i-1; j++) {
if (j == i-2) {
System.out.print(a1[j] + ".");
} else {
System.out.print(a1[j] + ", ");
}
}
System.out.println("The sum is : " + tal);
}
Couple of issues:
You may want to put element you read into array like a1[i] = scan.nextInt(); and initializing tal as 0 and using a1[i] in if condition instead of tal.
You are not incrementing value of i and end's up overwriting the previous value.
Once you come out of loop, you just print 0th value of array which i think you entered 0 and came out of loop.
You can over come these as below:
Just after tal += a1[i]; increment value of i as:
i++;
Now to print your element, use a loop like:
System.out.print("The inserted numbers are are:");
for (int j=0; j<i; j++) {
System.out.print(" " + a1[j]);
}
System.out.println();

Random Dice Generator

A run is a sequence of adjacent repeated values . Write a program that generates a sequence of random die tosses and that prints the die values, marking only the longest run. The program should take as input the total number of die tosses (ex 10), then print:
1 6 6 3 (2 2 2 2 2) 5 2
Im quite confused on how to compare each number in order to get the correct output. Maybe using an array to store the values. Any answers or input will be of help thank you!
import java.util.Random;
import java.util.Scanner;
public class Dice
{
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
public void DiceCount()
{
int count;
int sides = 6;
int number;
System.out.println("How many die? ");
count = keyboard.nextInt();
for(int i=0; i < count; i++)
{
number = generator.nextInt(sides);
System.out.print(number);
}
}
}
First, replace int number; with int[] numbers = new int[count];. Next, replace number = ... with numbers[i] = ....
This will give you an array of random numbers (don't print them yet!). As you generate your numbers, note how many equal numbers you get in a row (add a special counter for that). Also add variable that stores the length of the longest run so far. Every time you get a number that's equal to the prior number, increment the counter; otherwise, compare the counter to the max, change the max if necessary, and set the counter to 1. When you update the max, mark the position where the run starts (you can tell from the current position and the length of the run).
Now it's time to detect the longest run: go through the numbers array, and put an opening parenthesis where the run starts. Put a closing parenthesis when you reach the end of the run, and finish the printing to complete the output for the assignment.
import java.util.Random;
import java.util.Scanner;
public class Dice {
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
public void DiceCount() {
int sides = 6;
System.out.println("How many die? ");
int count = keyboard.nextInt();
int[] array = new int[count];
int longestLength = 1, currentLength = 1, longestLengthIndex = 0, currentLengthIndex = 1;
int currentNum = -1;
for (int i = 0; i < count; i++) {
array[i] = generator.nextInt(sides);
System.out.print(array[i] + " ");
if (currentNum == array[i]) {
currentLength++;
if (currentLength > longestLength) {
longestLengthIndex = currentLengthIndex;
longestLength = currentLength;
}
} else {
currentLength = 1;
currentLengthIndex = i;
}
currentNum = array[i];
}
System.out.println();
for (int i = 0; i < count; i++)
System.out.print((i == longestLengthIndex ? "(" : "") + array[i] + (i == (longestLengthIndex + longestLength - 1) ? ") " : " "));
}
}
Note: this will only take the first longest range. So if you have 1123335666 it will do 112(333)5666.
If you need 112(333)5(666) or 1123335(666) then I leave that to you. It's very trivial.
import java.util.Random;
public class Dice {
public static void main(String[] args) {
//make rolls
Random rand = new Random();
int[] array = new int[20];
int longestRun = 1;
int currentRun = 1;
int longestRunStart = 0;
int currentRunStart = 1;
System.out.print("Generated array: \n");
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(6); //add random number
System.out.print(array[i] + " "); //print array
if (i != 0 && array[i - 1] == array[i]) {
//if new number equals last number...
currentRun++; //record current run
if (currentRun > longestRun) {
longestRunStart = currentRunStart; //set index to newest run
longestRun = currentRun; //set above record to current run
}
} else {
//if new number is different from the last number...
currentRun = 1; //reset the current run length
currentRunStart = i; //reset the current run start index
}
}
//record results
System.out.print("\nIdentifying longest run: \n");
for (int i = 0; i < longestRunStart; i++) { System.out.print(array[i] + " "); } //prints all numbers leading up to the run
System.out.print("( "); //start parentheses
for (int i = longestRunStart; i < (longestRunStart + longestRun); i++) { System.out.print(array[i] + " "); } //prints the run itself
System.out.print(") "); //end parentheses
for (int i = (longestRunStart + longestRun); i < 20; i++) { System.out.print(array[i] + " "); } //all remaining numbers
}
}```

Taking User Input for an Array

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

Categories