Why is the scanner function not working? - java

So this code takes the value of n and returns a list of divisors as well as the total number of divisors. If I remove the Scanner declaration and its assignment to int n and simply give int n a value, the code runs perfectly.
However, as it is, it returns this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Program.main(Program.java:25)
I have no idea what the problem is.
import java.util.Scanner;
public class Program{
static int n;
static int x = 1;
static int [] arr = new int[n];
static int q = 0;
static int g = 0;
static int p = 1;
static int count;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
while(x <= n){
arr [q] = p; //assigns value to each array index
g = n%arr[q]; // stores value of remainder
q++;
p++;
x++;
if (g == 0){ //counts and displays each time remainder = 0
count++;
System.out.println(q);
}
}
System.out.println(count + " Divisors");
}
}

The size of arr is declared when n still holds no value(before the size is inputted). Do this:
import java.util.Scanner;
public class Program {
static int n;
static int x = 1;
static int [] arr; //no size set
//...
//Other variables
//...
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
arr = new int[n]; //Now the size is set to the inputted number.
while(x <= n) {
//...
//Other code to find divisors
//...
}
}
}
You need to name the size of arr after you input the n, otherwise the size is set to 0, causing the ArrayIndexOutOfBoundsException.
This line:
arr[q] = p;
Is what actually caused the error. arr[q] couldn't hold a value, because there was no arr[q]. the array had no size, so it couldn't hold any members.

static int n;
...
static int [] arr = new int[n];
You do not give n a value, so it defaults to 0. Therefore, you initialize arr as an array of length 0. That is why you get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0. It's because your array is size 0, so even index 0 is out of bounds of the array.
If you don't know n until you read from the Scanner you should change your code to:
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int [] arr = new int[n];
...
}

Change your while condition from
while(x <= n)
to
while(x < n)
< means strict less than, so you start from 1, and not get the out of bounds
Edit:
Also as #CodingNinja said, you have to change the and define a int value to the size of the array, by default is 0:
public static void main(String[] args){
static int n;
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
static int [] arr = new int[n];
while(x <= n){
arr [q] = p; //assigns value to each array index
g = n%arr[q]; // stores value of remainder
q++;
p++;
x++;
if (g == 0){ //counts and displays each time remainder = 0
count++;
System.out.println(q);
}
}
System.out.println(count + " Divisors");
}

Related

Return Arrays From Method as a Parameter

public static void find( int[] numbers) {
int[] range = new int[5];
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>=10 && numbers[i] <= 20)
{
range[i]=range[i]+numbers[i];
}
}
}
I want to write a method that find the numbers between 10 and 20 in a array and assign them to another array. this is expected and this is what I got.
{ 0 0 0 } are between 10 - 20 how can I fix this ?
public static void read( int[] numbers) {
Scanner input = new Scanner(System.in);
for( int i=0; i<numbers.length;i++)
{
System.out.print("Number["+i+"] => ");
numbers[i] = input.nextInt();
}
input.close();
}
This is the read() method that reads numbers from user and assign to an array.
public static void print( int[] numbers, int[]range) {
System.out.println("Number = { "+ numbers[0]+" "+numbers[1]+" "+numbers[2]+" "+numbers[3]+" "+numbers[4]+" }");
System.out.println("{ "+range[0]+" "+range[1]+" "+range[2]+" } "+" are between 10 - 20 ");
}
And this is the print(x,y) method that prints the numbers and range arrays.
My main method is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5];
read( numbers );
int[] range = new int[5];
find( numbers );
print(numbers, range);
The numbers array must include 3 numbers between 10-20.
Solution
Change the return type of your function to int[]
precalculate the size of your ranges array with counter
store the values which are in your range in the range array
return the range array
Note dont use the i running variable also for your range array, if you do so when not every value is in your range the result array will have gaps meaning values with the value of zero.
In the read function you should return the readed-in values to use it then in your find function
public static int[] read(int size) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[size];
for(int i=0; i < size; i++)
{
System.out.print("Number["+(i+1)+"] => ");
numbers[i] = input.nextInt();
// to remove the new line character
input.nextLine();
}
input.close();
return numbers;
}
import java.util.*;
public class MyClass {
public static void main(String args[]) {
int[] values = MyClass.read(10);
int[] result = MyClass.find(values);
// result is now the return value of the find method
// you can parse it now to another method of your choice
System.out.println(Arrays.toString(result));
}
public static int[] find(int[] numbers) {
int counter = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 10 && numbers[i] <= 20) {
counter++;
}
}
int[] range = new int[counter];
int counter2 = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 10 && numbers[i] <= 20) {
range[counter2] = numbers[i];
counter2++;
}
}
return range;
}
public static int[] read(int size) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("Number[" + (i+1) + "] => ");
numbers[i] = input.nextInt();
// to remove the new line character
input.nextLine();
}
input.close();
return numbers;
}
}
1. You need to return the 'range' array in the 'find' function because otherwise, it isn't accessible.
2. You need another variable say 'j' to point to the indices of the 'range' array.
The same variable can't be used for both the 'numbers' array and the 'range' array.
3. It will be better to pass the size of the 'numbers' array through the 'read' function and then read the array using the 'read' function.
Functions:
find() function:
public static int[] find( int[] numbers) {
int[] range = new int[5];
int j = 0;
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>=10 && numbers[i] <= 20)
{
range[j]=range[j]+numbers[i];
j++;
}
}
return range;
}
read() function:
public static int[] read( int n) {
int[] numbers = new int[n];
Scanner input = new Scanner(System.in);
for( int i=0; i<numbers.length;i++)
{
System.out.print("Number["+i+"] => ");
numbers[i] = input.nextInt();
}
input.close();
return numbers;
}
print() function[Remains same]:
public static void print( int[] numbers, int[]range) {
System.out.println("Number = { "+ numbers[0]+" "+numbers[1]+" "+numbers[2]+" "+numbers[3]+" "+numbers[4]+" }");
System.out.println("{ "+range[0]+" "+range[1]+" "+range[2]+" } "+" are between 10 - 20 ");
}
Main function accordingly:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] numbers = read(n);
int[] range = find(numbers);
change(numbers);
print(numbers, range);
}

Use multiple methods in Java

How to use multiple methods in a code? First it asks for the size of an array, then for the numbers of the element. One method is rounding numbers with a special rule.
Second method is a void method which modifies the array. Third method is making a new array with the modified values and returns to this array.
package tombtombbekerekit;
import java.util.Scanner;
public class TombTombbeKerekit {
public static int round(int osszeg)
{
int last_Digit = osszeg % 10;
if(last_Digit < 3)
return osszeg - last_Digit;
else if(last_Digit > 7)
return osszeg + (10 - last_Digit);
else
return osszeg - (last_Digit) + 5;
}
public static void roundSelf(int [] numbers)
{
int[] array = numbers;
for (int i = 0; i < array.length; i++)
return;
}
public static int [] roundNew(int [] numbers)
{
int [] newArray = new int[numbers.length];
return newArray;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Kérem az összegek számát: ");
int size = sc.nextInt();
System.out.println("Kérem az összegeket: ");
int [] array = new int[size];
for (int i = 0; i < array.length; i ++)
{
array[i] = sc.nextInt();
}
int [] kerek = roundNew(array);
System.out.println("Kerekítve: ");
for (int i = 0; i < kerek.length; i++)
System.out.println(kerek[i]);
}
}
You should write your own function. Just find the rule for the rounding. You can use n%10 to get the last digit of an integer named n.
I've written something but haven't tested it, I believe it should work. Check it out:
public int weirdRounding(int n)
{
int last_Digit = n % 10;
if(last_Digit < 3)
return n - last_Digit;
else if(last_Digit > 7)
return n + (10 - last_Digit);
else // the last digit is 3,4,5,6,7
return n - (last_Digit) + 5;
}
Note: You should probably make this code more readable if you're going to use it. For example define int LOWER_BOUND = 3 and int UPPER_BOUND = 7 instead of using '3' and '7', you could also wrap the ugly expressions with functions (e.g. roundUp, roundToFive ..). #Magic_Numbers_Are_Bad

How Arrays.sort function works?

I am new to java programming and i am trying to sort arrays using Arrays.sort() function. After using Arrays.sort(array),I am printing the final sorted array.
For example:
Input : 1 3 2 4
Output comes as : 0 0 0 0.
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n,temp,count;
int[] array = new int[MAX_SIZE];
n = input.nextInt();
for(int i = 0 ; i < n ; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for(int i = 0 ; i < n ; ++i) {
System.out.print(array[i]+" ");
}
}
}
You have initialized you array to hold 20 integers but you input only 5. Hence the first 15 elements will be 0 followed by the numbers you have inputted once the array is sorted.
To fix the issue you can initialize the array with n instead of MAX_SIZE as shown below:-
n = input.nextInt();
int[] array = new int[n];
Set the size of the array to match what your input should be, not to the maximum allowed size:
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, temp, count;
n = input.nextInt();
if (n > MAX_SIZE) {
//handle error somehow
}
int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; ++i) {
System.out.print(array[i] + " ");
}
}
}
When you initialize an array in Java it gets default value of 0 for primitive int:
int[] array = new int[MAX_SIZE];
The fact that you are not seeing your desired input of 1,2,3,4 is a separate problem with your Scanner code.

if condition get skipped for calculating average in a loop based on some condition

I want to take the average while value in column A is lower than its next value and value in column B is the same as its next value. The average is taken from column C value based on column A value as column C index. Following is the data sample:
columnA,B,C
0,0,0.36
1,0,0.23
2,0,0.14
3,1,0.41
4,1,0.44
5,2,0.16
6,2,0.03
7,2,0.09
Following is my current code:
import java.io.*;
import java.util.*;
public class dtw_post {
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
int x = 655;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
while(scannerFile.hasNextLine()){
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[x];
for(int i = 0; i<N; i++)
{
a[i]=Integer.parseInt(lineVector[0]);
b[i]=Integer.parseInt(lineVector[1]);
c[i]=Double.parseDouble(lineVector[2]);
}
System.out.println((dtw_post.lookup(a,b,c)));}
}
static String lookup (int[] a, int[] b, double[] c){
int j=0; int i=0;
String[] final_result = new String[c.length];
while(i < a.length-1){
if (a[i] < a[i+1] && b[i] == b[i+1]) {
double[] d = {c[a[i]],c[a[i+1]]};
double sum = 0;
int number = 0;
for (double val : d) {
++number;
sum += val;
}
double e = sum/number;
final_result[i] = String.valueOf(e);
i++;
}
else {
final_result[i] = String.valueOf(c[a[i]]);
i++;
}
}
String result = final_result[j]; j++;
return result;
}
}
I expect it to output 0.243 in the first line as the average of 0.36,0.23,and 0.14. I figure that the problem is in the if condition in the lookup method. It seems to skip the if and run the else condition only. My current code output column C exactly as it is. What went wrong in my if condition loop? Thank you for your time.
The first issue is you are parsing the file wrong. You are parsing the file line by line in a while loop. But you are creating new a, b and c arrays for each line. Move the initialization out of the for loop :
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
int x = 655;
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[x];
int i = 0;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
while (scannerFile.hasNextLine()) {
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
a[i] = Integer.parseInt(lineVector[0]);
b[i] = Integer.parseInt(lineVector[1]);
c[i] = Double.parseDouble(lineVector[2]);
++i;
}
System.out.println((dtw_post.lookup(a, b, c)));
}
Based on that you will only get an average of two consecutive values. You also need to rethink the lookup function. Increase the sum until the value in b changes and then calculate the average and print it. E.g
static String lookup(int[] a, int[] b, double[] c) {
String result = "";
double sum = c[a[0]];
int consecutive = 1;
for (int i = 1; i < a.length - 1; ++i) {
if (a[i - 1] < a[i] && b[i - 1] == b[i]) {
sum += c[a[i]];
++consecutive;
} else {
result += String.valueOf(sum / consecutive) + '\n';
sum = c[a[i]];
consecutive = 1;
}
}
return result;
}
Ad a side note, you should also consider StringBuilder for concatenating strings in a loop
In your if condition you required that a[i] is less than a[i+1], shouldn't it be a[i] greater than a[i+1]?
So the if should be:
if(a[i]>a[i+1] && b[i]==b[i+1]){
....
You are processing only one line of the file at a time. The loop reads one line from the file and splits it to get values for a,b,c. Then it copies these values into EVERY cell in the corresponding arrays, and then calls lookup. Since every value of a is the same, if statement is never true.
What you want to do is fill in each successive cell in a,b,c with the next line read, and call lookup outside the while loop. What I think you want is:
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[N];
int i = 0;
while(scannerFile.hasNextLine()){
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
a[i]=Integer.parseInt(lineVector[0]);
b[i]=Integer.parseInt(lineVector[1]);
c[i]=Double.parseDouble(lineVector[2]);
i++;
}
System.out.println((dtw_post.lookup(a,b,c)));
}

how to return positive values of original array into a new array

I'm supposed to declare a 15 integer array and return a second array containing the positive integers of the original array. I'm having trouble returning the second array from the method.
import java.util.Scanner;
public class array4
{
public static void main(String [] args)
{
int [] num = new int[15]; int [] positives = new int [15];
getInput(num);
positives = getPositives(num);
printResults(num, positives);
}
public static void getInput(int [] num){
int x;
Scanner kbd = new Scanner(System.in);
System.out.println("Enter 15 integers");
for(x = 0; x < 15; x++)
num[x] = kbd.nextInt();
}
public static int getPositives(int [] num){
int position = 0;
int [] positive = new int [15];
for(int i =0; i < num.length; i++){
if(num[i] >=0) {
positive[position] = num[i];
position++; }}
return positive;
}
public static void printResults(int [] num, int [] positives){
System.out.println("You entered"); int x;
for(x = 0; x < num.length; x++)
System.out.println(num[x]);
System.out.println("Your positive integers are ");
for(x = 0; x < positives.length; x++)
System.out.println(positives[x]);}}
It is public static int[] getPositive(). The return type is an array of integers, but you declared it as int.
In getPositive you are returning an int rather than an int[]
I think your approach is flawed though.
If you create an ArrayList and put the positive numbers in there, then turn that list into an Array, you won't have any empty places in your array.
You need to declare getPositive to return an array:
public static int[] getPositive(int [] num){
Also, you don't need to initialize positive in the main() method. That just allocates an array the will be discarded.
Your method must return integer array and not a single integer value. Here is modified piece of code :
public static int[] getPositive(int [] num){
int position = 0;
int [] positive = new int [15];
for(int i =0; i < num.length; i++){
if(num[i] >=0) {
positive[position] = num[i];
position++; }}
return positive; // Wont give compilation error now
}

Categories