Inputing strings into an array - java

I'm a beginning programmer with the assignment to create a program that prompts the user to enter the number of elements that will then be stored into a String array. The second part of the assignment is to then list the array in ascending order. But I'm kind of stuck of the first part. If the user enters that there will be 3 elements after the 3rd string is entered I get an out of bounds exception. Below is the code.
import java.util.*;
public class arrays
{
public static void main(String[]arg)
{
Scanner input = new Scanner(System.in);
//Read user input.
System.out.print("How many Elements? ");
int num = input.nextInt();
String array[]= new String[num];
for (int i = 1 ; i <= num; i++ )
{
System.out.print("Enter element "+ i +": ");
array[i] = input.next();
}
System.out.println(array);
}
}

The array index starts at 0 so your loop should look like this:
for (int i = 0 ; i < num; i++ )
{
System.out.print("Enter element "+ (i+1) +": ");
array[i] = input.next();
}
Note that I also added +1 in the System.out.print to show "user friendly" output (e.g. "Enter element 1:" instead of "Enter element 0:" for the first element).
Another option would be to subtract 1 while accessing the array, which would allow you to keep the existing System.out.print line:
for (int i = 1 ; i <= num; i++ )
{
System.out.print("Enter element "+ i +": ");
array[i - 1] = input.next();
}
Although I feel that this is slightly less common practice.

Arrays in Java are numbered starting with zero, which means, your array of length 3 has this valid indices:
array[0]
array[1]
array[2]
I guess that's enough to send you on the right track ;-)

Start with i = 0 and go up to i < num, because in the example with three your array starts at 0 and goes up to 2, so it's no wonder that there's an out of bounds exception. That should fix the error.

you get the error because array index starts with 0. You should change your loop into this:
for (int i = 0 ; i < num; i++ )

change to array[i-1] = input.next();

Related

Having problems with writing a method to find the index of the biggest integer in my ArrayList

I am having problems in creating a method that will find the index of the biggest integer.
I have tried creating plenty of methods but I was only recently introduced to finding the index of a value in a list, and I still am unable to find the best, let alone a working way. By index I assumed that it is the position of the value within the list given (please correct me if I am wrong).
My Current Code:
import java.util.ArrayList;
import java.util.Scanner;
public class FindBiggest2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> integerList = new ArrayList<Integer>();
System.out.println("Enter any amount integers (0 to stop): ");
int integer = input.nextInt();
while(integer != 0) {
integerList.add(integer);
integer = input.nextInt();
}
input.close();
if(integerList.size() == 0) {
System.out.println("list is empty");
return;
}
System.out.println("\nThe integers entered are: ");
// displaying ids
for(int i=0; i<integerList.size(); i++)
System.out.print(integerList.get(i)+" ");
System.out.println();
// finding biggest id
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++)
if(bInt < integerList.get(i))
bInt = integerList.get(i);
System.out.println("The biggest integer in the array is: "+ bInt);
}
}
My current output (Example):
Enter any amount of integers (0 to stop):
1
2
3
4
5
6
0
The integers entered are:
1 2 3 4 5 6
The biggest integer in the array is: 6
These are my requirements of my output:
The output of the program should firstly display all integers, and then
indicate the biggest integer among them as well as the index of the biggest integer in the 1D
array.
So your index in this loop:
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) // i = index
if(bInt < integerList.get(i))
bInt = integerList.get(i);
would be i. Along with int bInt, you'll want an int maxIntegerIndex to hold that value until the for loop concludes.
One stylistic choice I'd suggest that you can feel free to ignore is using curly braces to explicitly declare what code is running in a loop / if statement. This will prevent issues later on in code reading and execution where it appears code should run but isn't. It'll save you a lot of time tracking down seemingly broken code down the road and costs almost nothing.
I am having problems in creating a method that will find the index of
the biggest integer.
In the same way that you are storing the largest value, also store the value of "i" in a separate variable:
// finding biggest id AND the index where it was found
int index = 0;
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) {
if(bInt < integerList.get(i)) {
bInt = integerList.get(i);
index = i;
}
}
System.out.println("The biggest integer in the array is: "+ bInt);
System.out.println("It was found at Index: "+ index);

How to traverse through a one dimensional array in java [duplicate]

This question already has answers here:
Finding the minimum value of int numbers in an array (Java)
(10 answers)
Closed 5 years ago.
This is my first question on this site.
Anyways i'm making a program that will prompt the user for how many grades to enter. Then prompt the user to enter grades between 0 and 100 and store them in a array. Finally traverse the array to find the highest grade entered and display it to the user.
The problem i'm encountering is i have no clue on how to traverse through an array to compare two indexs in a array.
import java.util.*;
public class HighestGrade {
public static void main(String[] args) {
//Declare and Initialize Arrays and Scanner
Scanner scan = new Scanner(System.in);
int num = 0;
int[] array1;
int highestgrade = 0;
//Prompt user on how many grades they want to enter
System.out.print("How many grades do you want to enter: ");
num = scan.nextInt();
array1 = new int[num];
for(int i = 0; i < array1.length; i++){
System.out.print("Enter grade out of 100: ");
array1[i] = scan.nextInt();
}
//Traverse the array to find the highest grade entered
for (int i = 0; array1[0] < array1[i]; i++){
System.out.print("Higher");
}
//Display the results to the user
System.out.print("The highest grade is " + highestgrade + ".");
//Close scanner
scan.close();
}
}
To traverse through an array you can use a loop. For loop or while loop or do while loop.
To traverse through an array and keep track of the highest value you can maintain a variable and update it after each iteration if a value larger than that is encountered.
Speaking in terms of code..
int max = arr[0];
for ( int i = 0; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
System.out.println("Largest is : "+max);
Hope this helps..!!
Also you can use Recursion to traverse an array. But it is not recommended as it will lead to stack related issues..
Another approach to get the highest value without traversing can be seen like this..
Step 1 : Sort the array in ascending order
Step 2 : Highest value will be at the end of the array, Use it as highest value
In codes..
Arrays.sort(arr);
System.out.println("Highest Value is : "+arr[arr.length - 1]);
To traverse the array you need to change your for loop like this:
for (int i = 0; i < array1.length; i++){
// do something with array1[i]
}
Is actually what you already did to fill it. Just do the same to use its values. But there is an alternative to get the highest value, you can use Arrays.sort:
Arrays.sort(array1); // sort values in ascending order.
System.out.println(array1[array1.length-1]); // get the element in the last position (the greatest)

Negative Arrays and Error Messages

//MY TASK IS TWO MERGE TO ARRAYS INTO ASCENDING ORDER.Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int one[]= new int[10000];
int two[]= new int[10000];
int lengthShort=0;
int lengthLong=0;
int a =0;
int b =0;
System.out.println("Enter the values for the first array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<one.length && scan.hasNext(); i++){
one[i] = scan.nextInt();
a++;
if(one[i]<0){
one[i]=0;
break;
}
}
int length1 = a-1;
System.out.println("Enter the values for the second array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<two.length && scan.hasNext(); i++){
two[i] = scan.nextInt();
b++;
if(two[i]<0){
two[i]=0;
break;
}
}
int lengthTwo = b-1;
int mergeOne[] = new int[length1];
for (int i = 0; i<mergeOne.length; i++){
mergeOne[i]=one[i];
}
int mergeTwo[] = new int[lengthTwo];
for (int i = 0; i<mergeTwo.length; i++){
mergeTwo[i]=two[i];
}
System.out.println("First Array:");
for(int i=0; i<mergeOne.length; i++){
System.out.print(mergeOne[i] + " ");
}
System.out.println("\nSecond Array:");
for(int i=0; i<mergeTwo.length; i++){
System.out.print(mergeTwo[i] + " ");
}
if(mergeOne.length<=mergeTwo.length){
lengthLong = mergeTwo.length;
lengthShort = mergeOne.length;
}
else if(mergeOne.length>=mergeTwo.length){
lengthShort = mergeTwo.length;
lengthLong = mergeOne.length;
}
int merged[] = new int[length1 + lengthTwo];
for(int i = 0; i<lengthShort; i++){
if(i==0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i] = mergeOne[i];
merged[i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i] = mergeTwo[i];
merged[i+1]= mergeOne[i];
}
}
else if(i>0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i+i] = mergeOne[i];
merged[i+i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i+i] = mergeTwo[i];
merged[i+i+1]= mergeOne[i];
}
}
}
if(mergeOne.length<mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeTwo[k];
}
}
if(mergeOne.length>mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeOne[k];
}
}
for(int i = 0; i<merged.length; i++){
if((i+1)==merged.length)
break;
if(merged[i]>merged[i+1]){
int temp = merged[i+1];
merged[i+1]=merged[i];
merged[i]= temp;
}
}
System.out.println("\nMerged array in order is: ");
for(int i = 0; i<merged.length; i++){
System.out.print(merged[i] + " ");
}
}
}
//My code compiles in drjava but I have two issues:
1) It doesn't order the numbers in ascending order
2) When I run it through the site I have to submit this on it gives me the message as follows:
Runtime Error
Exception in thread "main" java.lang.NegativeArraySizeException
at Main.main(Main.java:281)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
You'll need to rethink your merge algorithm. Suppose you input arrays are
1 5 10 50 100 500
2 4 6 8 10 12 14 16
You'll need to repeatedly decide which element is smaller to put into the output. So after selecting N elements, your output will look like
1 2 4 5 6 8 10 10 12 14
And you will need to have indexes pointing at the place in the input arrays you'll need to look at next:
1 5 10 50 100 500
^^
2 4 6 8 10 12 14 16
^^
As you can see, the indexes could be at very different places in the input arrays. However, your code does a lot of this:
if(mergeOne[i]<=mergeTwo[i]){
which means it's only comparing elements from the input that are in the same location. This doesn't work, and trying to swap elements in the output after the fact isn't good enough to get the job done.
Basically, instead of having one index and comparing the elements of the two input arrays at the same index, you'll need two indexes. I'll let you take it from there, but I think you can figure it out.
(And I have no idea why you're getting NegativeArraySizeException.)

loop is cut one element of the array

The problem is :
Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents.
My code :
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-1 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
The error is :
----jGRASP exec: java Q1
Enter a number :
4
4
16
65536
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q1.main(Q1.java:16)
----jGRASP wedge2: exit code for process is 1.
why it says that?
And the number by user printed twice!
a[i+1] = Math.pow(2,a[i]); // issue here
When i=a.length-1, i+1 is a.length. So there is no index value match in this array.
Suggestion:
Create an array witch has lenght= a.length+1
double powArray[] =new double[a.length+1];
Now
powArray[0]=a[0];
for(int i=1;i<powArray.length;i++){
powArray[i]=Math.pow(2,a[i-1]);
}
Issue is on line.16 as per compiler : a[i+1] = Math.pow(2,a[i]); The problem is indexes are not properly matched here.So it gives ArrayIndexOutOfBound Exception.Here i=a.length-1, i+1=a.length.So it is giving ArrayIndexOutOfBound Exception.
You should check that your index is not negative and not higher than the array length before accessing an array item.
Refer this : Avoiding index out of bounds exceptions
Concentrate on below portion of your code, its easy and you'll feel good if you figure out yourself:
for ( ;i<=a.length-1 ; i++) // check from where i starts and where it ends
{
a[i+1] = Math.pow(2,a[i]); // check what value of i would be here on each iteration
System.out.println((int)(a[i]) );
}
Also you could use a debugger and check every iteration
Few things to look upon here.
You have written a[0]= num ; which means the first value in the array is the same as the number entered by the user. Thus, you can see the number printed again. Thus,
a[0] = 1; // initial value has to be 1, contrary to what you've used
Next, your loop to generate the array values needs to be fixed. When you have i+1, the array index goes out of bounds in the last iteration, where your i is a.length - 1. Thus change your loop to something like this
for (int i = 1; i < a.length; i++) {
a[i] = Math.pow(2, a[i-1]);
}
Now, print the array values in a separate loop, as the previous loop won't print the value of the first index of the array.
for (int i = 0; i < a.length; i++) {
System.out.println((int)a[i]);
}
Change the upper limit to a.length-2 .Rest code remain same
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-2 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
int num ;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ; //Assign First Element To Array
double prev = a[0];
for(int i=1;i<a.length;i++){
a[i] = Math.pow(2,prev);
prev = a[i];
}
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Output
Enter a number :
3
3.0
8.0
256.0
Just change the loop to :
for(;i < a.length-1;i++)
since when you assign 4 as a length for a[]..
you have a[0],a[1],a[2],a[3]... 4 slots.
Now a.length gives 4.
so for your a[i+1] for i=a.length-1 (i.e 3 ) .. a[i+1] = a[4]... which is out of the array bound for you array.
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
for ( ;i<a.length ; i++) {
a[i] = Math.pow(2,i);
System.out.pri``nt((int)a[i]+ " ");
}
}
}

Removing the 0 value from a sorted Array?

I was wondering if there was a way to remove the default "0" value I get when I run the following code:
Scanner scan = new Scanner(System.in);
int [] x = new int[4];
for ( int i = 1; i < x.length; i++ )
{
System.out.println( "Enter number " + i + ": ");
x[i] = scan.nextInt();
}
Arrays.sort(x);
System.out.println(Arrays.toString(x));
}
The output is as follows
[0, i[1], i[2], i[3]]
Of course, all the array values here are actually the numbers entered into the console.
The code is WORKING. It successfully sorts any numbers into the correct order, however, there is always this nasty 0.
I'm not looking to remove ALL 0's (I want the user to be able to enter 0 and have it show up) - -I just don't want the default 0. Any ideas?
Array indexes in Java are 0-based, not 1-based. So start iterating from 0 instead of from 1 and you should be good:
for ( int i = 0; i < x.length; i++ )
for ( int i = 0; i < x.length; i++ )
When you allocate an array of size 4, you're allocating four ints: i[0],i[1],i[2], and i[3]. Because Java is fairly friendly, it sets all four of these to 0. So what you're seeing on the output is [i[0],i[1],i[2],i[3]] (in sorted order). The sort isn't adding the 0, it was already there. If you only want 3 numbers, then you should allocate an int[3] rather than an int[4]. And then, to go along with that, when you ask for number 1, store it in i[0]. The simplest change to do this would be to simply change the top line to
int [] x = new int[3];
and the later line to
x[i-1] = scan.nextInt();
The change suggested by other answers is the more common, one, though. Most programmers would have i go from 0 to 2 and then output i+1 when talking to the user.
The following code should work:
Scanner scan = new Scanner(System.in);
int[] x = new int[3];
for (int i = 0; i < x.length; i++)
{
System.out.println( "Enter number " + i + ": ");
x[i] = scan.nextInt();
}
Arrays.sort(x);
System.out.println(Arrays.toString(x));
The problem was, as others have pointed out, that your int i should start at 0, not 1.

Categories

Resources