The user enters 10 numbers. After that, the program asks the user to enter the index number they want to retrieve like the example below.
How do I ask the user to input an index number and print the array in that specific index number?
This is my code so far
public class ArrayElement {
public static void main(String[] args) {
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i<10; i++){
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
}
}
public static void main(String[] args) {
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i<10; i++){
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is "+Array[index]);
}
Output : Element at index 6 is 42
you can get the element of a particular index of an array as follows
int element = Array[index];
Related
Question:
I need to create an array that holds 1000 integers ranging from 1-100. I then need to ask the user for an input and find out if the number the user has input is present in the array. If its not, then I have to output the message that it is not in the array.
I populated the array with random numbers, just need to find out how to search for the number in the array. I tried using a while loop to condition the for loop, but cant because the random generator and searcher would be in the same loop. Is there a way to linearly search for the number?
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] numbers = new int[1000];
System.out.println("Please enter a number: ");
int n = Integer.parseInt(reader.nextLine());
for(int i = 0; i < 1000; i = i + 1)
{
numbers[i] = (int)(Math.random()*100);
}
}
}
Try this
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] numbers = new int[1000];
boolean found = false;
System.out.println("Please enter a number: ");
int n = Integer.parseInt(reader.nextLine());
for(int i = 0; i < 1000; i = i + 1)
{
numbers[i] = (int)(Math.random()*100);
}
for(int i =0; i < 1000; i++){
if(numbers[i] == n){
found = true;
System.out.println(numbers[i] + " Appears first at index " + i);
break;
}
}
if(!found){System.out.println("Number " + n + " is not in the list");}
}
I am trying to sort a numeric array in ascending and descending order. I am beginner so using the following link Sort an array in Java . I am trying to get input from user as array's elements.
public class SortingofString {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int Array1[];
// String Array2[];
System.out.println("How many numaric elements: ");
int n = input.nextInt();
int[] array1 = new int[n];
int number=input.nextInt();
for(int i=0; i<n; i++){
System.out.println("Enter number:");
array1[i] = number;
System.out.println("Original numeric array : "+Arrays.toString(Array1));
Arrays.sort(Array1);
System.out.println("Sorted numeric array : "+Arrays.toString(Array1));
}
}
}
The error occurs when i pass my array_name Array1 in first toString function.System.out.println("Original numeric array : "+Arrays.toString(Array1));
Error says Initialize variable Array1 . How can i resolve this error?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//int Array1[];
System.out.println("How many numaric elements: ");
int n = input.nextInt();
int arr[] = new int[n];// solve 1st problem
for (int i = 0; i < n; i++) {
System.out.println("Enter number: " +(i+1));
int number = input.nextInt();
arr[i]=number;//init array by user input data
}
System.out.println("Original numeric array : " + Arrays.toString(arr));
Arrays.sort(arr);
System.out.println("Sorted numeric array : " + Arrays.toString(arr));
}
you also need 2 import
import java.util.Arrays;
import java.util.Scanner;
Move (and rename) Array1 behind reading n:
System.out.println("How many numaric elements: ");
int n = input.nextInt();
int[] array1 = new int[n];
And maybe use the entered number:
int number = input.nextInt();
array1[i] = number;
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0" which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[i]);
++j;
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[i] + " ");
}
}
}
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.
Here I fix your code.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
//for 5 inputs you need loop
for(;i<NUM_VALS;i++){
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
}
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[j]);
//++j; //no need to increment as you already did in for loop
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
}
}
}
Here is a solution using the collections framework:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final List<Integer> numbers = new ArrayList<>();
System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
while (scnr.hasNextBigInteger()) {
final int n = scnr.nextInt();
System.out.println("Parsed: " + n);
numbers.add(n);
}
System.out.println("Done reading user input.");
System.out.println("Your input: " + numbers);
Collections.reverse(numbers);
System.out.println("Your input reversed: " + numbers);
}
}
I have provided you with a solution. This is a clean way of doing it.
nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<Integer>();
//Simple loop that will read 5 user inputs
//and add them to the input list
for(int i = 0; i < 5; i++){
input.add(scanner.nextInt());
}
//print the 5 values
for(Integer val : input){
System.out.println(val);
}
//reverse the 5 values
Collections.reverse(input);
//print the 5 values again, but they are now reversed
for(Integer val : input){
System.out.println(val);
}
}
I have to read strings from the user based on a number n and store n strings in n different variables. I'm stuck with how to put them into different strings. Please help me out.
This is my code:
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
for (int i=0; i<=b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}
So if b = 5, i have to input 5 strings from the user and store them in 5 different string variables. I'm able to take it from the user but not able to assign them into different variables. Can u please help me out?
Thanks.
If you know exactly the number of input then use an Array, if not use a ArrayList
With Arrays
String []inpupts = new String[b];
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs[i] = in.nextLine();
}
With ArrayList
List<String> inpupts = new ArrayList<String>();
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs.add(in.nextLine());
}
From your code (<= b) I am assuming you just started learning Java. Therefore, I edited your solution and am proposing the following, if this is okay?
public static void main(String[] args) {
int b;
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
//necessary to do due to Enter key pressed by user
in.nextLine();
String s[] = new String[b];
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s[i] = in.nextLine();
// You can check at the same time if this is what you entered
System.out.println("I have received this sring: "+s[i]+"\n");
}
Create an array and store it in an array like below:
String s[] = new String[b];//use b+1 if you need b+1 entries
for (int i=0; i<b; i++) {//use <=b is you need b+1 entries
System.out.println("Enter a string: ");
s[i] = in.nextLine();
}
You can then access your values as:
for (int i=0; i<b; i++) //use <=b is you need b+1 entries
System.out.println("Entered string was : " + s[i]);
}
Solution :
You can use something like this.
You can change your code as :
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
in.nextLine(); // To get a new line
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}
This program is working but not the way that I'd like. I am able to calculate the max, but I have to first define the number of arguments. I would like to be able to put in a variable number of arguments, then return the max.
How can I do?
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
int n=cin.nextInt();
int max=cin.nextInt();
for(int i=2; i<=n; i++){
int num=cin.nextInt();
if(num>max) max=num;
}
System.out.println(max);
}
I guess you want to get max without giving the number of inputs as the first argument.
read line as a string
tokenize and covert the numbers to integer (convert to float if you allow floating point numbers)
calc max
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
String input=cin.nextLine();
String[] numbers = input.split("\\s");
int max = Integer.parseInt(numbers[0]);
for(int i=1; i<numbers.length; i++){
int num=Integer.parseInt(numbers[i]);
if(num>max) max=num;
}
System.out.println(max);
}
This is my guess, you can tell me if this is what you want to do.
public static void main(String[] args) {
//Your tokenizer
Scanner scanForNumbers = new Scanner(System.in);
//First prompt for number of numbers
System.out.print("Print the Number of Numbers to Enter:");
int numberOfNumbers = scanForNumbers.nextInt();
System.out.println();
int maxOfNumbers = 0;
int tempNum = 0;
//making number of numbers the max iterate till you get there.
for(int index = 0 index < numberOfNumbers; index++){
//Prompt for a number
System.out.print("Enter another Number");
tempNum = scanForNumbers.nextInt();
System.out.println();
//if it is bigger, set a new max.
if(tempNum > maxOfNumbers){
maxOfNumbers = tempNum;
}
}
System.out.println("The Bigger Number is : " + maxOfNumbers);
}