NullPointerException when using Scanner.nextInt() [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am creating a program that calculates how many numbers between A and B are divisible by K. This program should allow the user to input first the number of test cases then get the corresponding A, B, and K values depending on the number of test cases.
Sample Input:
2
1
10
3
8
20
4
Output would be:
Case 1: 3
Case 2: 4
However, I keep getting a NullPointerException right after hitting enter after the second line. In this case, I only get to enter:
2
1
Here is the code:
import java.util.Scanner;
public class ABK {
public static void cases(int no, int[] first, int[] second, int[] div){
int[] outputs = null;
for(int i = 0; i < no; i++){
for(int x = first[i]; x <= second[i]; x++){
if(x%(div[i]) == 0)
outputs[i]++;
else continue;
}
}
for(int i = 0; i < no; i++){
System.out.println("Case " + (i+1) + ": " + outputs[i]);
}
}
public static void main(String[] args){
int noOfCases = 0;
int[] a = null, b = null, k = null;
Scanner scanner = new Scanner(System.in);
noOfCases = scanner.nextInt();
if(noOfCases < 0 || noOfCases > 1000){
System.out.println("Invalid number of cases. Only numbers from 1 to 100 are allowed.");
System.exit(0);
}
for(int i = 0; i < noOfCases; i++){
a[i] = scanner.nextInt(); //THIS IS WHERE THE NULLPOINTEREXCEPTION APPEARS
b[i] = scanner.nextInt();
k[i] = scanner.nextInt();
}
for(int i = 0; i < noOfCases; i++){
if(a[i] < 1 || a[i] > 1000){
System.out.println("Invalid value of a. Only numbers from 1 to 1000 are allowed.");
System.exit(0);
}
if(b[i] < 1 || b[i] > 1000){
System.out.println("Invalid value of b. Only numbers from 1 to 1000 are allowed.");
System.exit(0);
}
else if(a[i] > b[i]){
System.out.println("Invalid value of b. It must be larger than a.");
System.exit(0);
}
if(k[i] < 1 || k[i] > 1000){
System.out.println("Invalid value of k. Only numbers from 1 to 9999 are allowed.");
System.exit(0);
}
}
cases(noOfCases, a, b, k);
}
}
I've tried other "fixes" such as initializing the Scanner variable or using a new class that implements scanner.nextInt() but none worked for me.
Thank you in advance for your help.

You never instantiate a array. Therefore, you get an NPE when trying to access it.
The same exception will happen for b and k.
You can instantiate the arrays that way
a = new int[noOfCases];

Related

Limit number of input lines in Java?

I have a problem where I want to take input from the user, the user can insert 1 and up to 8 lines, and each line represents a case.
What I want is to stop the scanner when the user inserts 8 lines, Or if the user wants less than 8 he can press enter or a specific key to end the loop.
What I have done so far:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) { // here I want to check so that it don't exeed 8 lines
int e;
int m;
i = input.nextInt();
j = input.nextInt();
int num = 0;
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
}
}
The input should be two numbers in each line, one for i and one for j.
Input:
0 0
100 300
99 399
0 200
Output should be:
C1: 0
C2: 100
C3: 1
C4: 200
Hope this explains my problem.
Thanks in advance!
As #Abhishek suggested, you can use a counter variable:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
int linesParsed = 0;
while (linesParsed < 8 && input.hasNextLine()) {
// What are you using these variables for? You compute their
// values, but then you do not use them
int e;
int m;
// Where are these variables declared? It seems weird to have
// instance variables be named i and j
i = input.nextInt();
j = input.nextInt();
int num = 0;
// Unless i and j are being modified concurrently somewhere
// else in the code, this will result in an infinite loop
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
linesParsed++;
}
}

Why I am getting a RUNTIME ERROR when using Scanner in JAVA

Question:
Find the number of D, C, B and A grades for the last test on informatics, where n students from a class have successfully passed the test.
In this task, we use a 5-point grading system and are interested only in passing grades: from 2 to 5. They correspond to the letter grades in the following way: 5 is for A, 4 is for B, 3 is for C and 2 is for D. The program gets number n as input and then gets the grades themselves: one by one.
The program should output four numbers in a single line: the number of D, C, B, and A grades respectively.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scan = new Scanner(System.in);
int numStudents = scan.nextInt();
int marks;
int gradeA = 0;
int gradeB = 0;
int gradeC = 0;
int gradeD = 0;
for (int i = 0; i <= numStudents; i++){
marks = scan.nextInt();
if(marks == 5){
gradeA++;
} else if (marks == 4){
gradeB++;
} else if (marks == 3){
gradeC++;
} else if (marks == 1){
gradeD++;
}
}
System.out.println(gradeD);
System.out.println(gradeC);
System.out.println(gradeB);
System.out.println(gradeA);
}
}
ERROR:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
If you define numStudents as 5, then you should enter 6 (because of <= in your for loop)
for (int i = 0; i <= numStudents; i++){
This should be..
for (int i = 0; i < numStudents; i++){
When you enter 1 in stdin as first input, it will be numStudents. Now, you have to enter 2 inputs because of <=. So your stdin should be
1
2
3
Instead, better change <= to < in your code, so that you can enter 1 2
You get NoSuchElementException when you given only 1 2 in stdin with your code (with <=)
If there is no integer on the scanner, you will get this error. You have to put a condition. Try:
if(scan.hasNextInt()) {
marks = scan.nextInt();
}
I ran your code in editor fixing some minor issues in the loop and number of students check it worked fine with the input :
5
2 3 4 5 6
Here's the whole code block:
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
if(scan.hasNextInt() ){
int numStudents = scan.nextInt();
int marks;
int gradeA = 0;
int gradeB = 0;
int gradeC = 0;
int gradeD = 0;
for (int i = 0; i < numStudents; i++){
marks = scan.nextInt();
if(marks == 5){
gradeA++;
} else if (marks == 4){
gradeB++;
} else if (marks == 3){
gradeC++;
} else if (marks == 1){
gradeD++;
}
}
System.out.println(gradeD);
System.out.println(gradeC);
System.out.println(gradeB);
System.out.println(gradeA);
}
}
}
This is the output in this case:
0
1
1
1
For the D grade, the if condition should be else if (marks == 2).
You have put 1 instead of 2

How to make this programm to count the odd and even numbers in an array?(eclipse)

Thanks for the answers guys, didn't expect getting answers so fast.
Ok so in this code at the final stage it is meant to count how many odd and evens numbers there are in the array length you decide.
If you for example type in 10 it prints out 10 random numbers between the intervall of 0-999 and then it seperates the odd and even numbers
In the last stage it's meant to calculate how many odd and even numbers there are like ''out of the 10 numbers 4 of them were even numbers and 6 were odd numbers''
Right now in the last stage it just prints out numbers randomly and doesen't calculate how many odd and even numbers there are. I don't know how to fix it.
I have ran out of ideas about it so hopefully someone here can make it work properly.
import java.util.Scanner;
public class Uppgift4 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length;
while (true)
{
System.out.print(" \n\nHow many numbers do you want in the intervall 0-999?(turn off with -1 or 1000):");
length = scan.nextInt();
if (length>999)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
if (length<0)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
System.out.println("\n Here are the random numbers:");
int [] ar1 = new int[length];
for(int i = 0; i < length; i++) {
ar1[i] = (int)(Math.random() * 1000);
{
System.out.print(" "+ar1[i]);
}
}
System.out.println(" \n");
System.out.println(" Here are the numbers divided between even and odd numbers:");
System.out.print(" ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.print("- ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 != 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.println(" \n");
System.out.print(" Of the above numbers "+ length + " so ");
System.out.print("where ");
for(int evennumbers = 1 ; evennumbers < length ; evennumbers++)
{
if(ar1[evennumbers] % 2 == 0)
{
System.out.print(evennumbers+" ");
}
}
System.out.print(" of the numbers even and odd numbers were ");
for(int oddnumbers = 1 ; oddnumbers < length ; oddnumbers++)
{
if(ar1[oddnumbers] % 2 != 0)
{
System.out.print(oddnumbers+" ");
}
}
}
}
You need to count the number of even and odd number:
int even = 0;
int odd = 0;
// Loop through the final array
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
even++;
} else {
odd++;
}
}
Even simpler:
for(int i = 0 ; i < length ; i++)
{
odd += (ar1[i] % 2)
}
even = length - odd;
just make two global variables to count the odd and even and put them into the condition where you are checking for odd and even.
code
Why not just make use of bitwise AND and remove those conditionals like so:
int odd = 0;
int even = 0;
for(int i=0;i<length;i++){
odd+=ar1[i]&1;
even+=((ar1[i]+1)&1);
}
you can use this way , very simple
public static void main(String []args){
Integer[] arr = new Integer[] { 1,2,3,4,5};
int oddCount =0; int evenCount=0;
for ( int i=0; i< arr.length ;i++){
if( ( arr[i] % 2) == 0 )
evenCount++;
if( arr[i] % 2 != 0 )
oddCount++;
}
System.out.println( "oddCount in Array :" + oddCount + " EvenCount in Array : " + evenCount);
}

Java lottery using arrays

I have to create a lottery game where you randomly generate six winning numbers simulating a lottery. Ask the user to enter six numbers and see if they win the lottery!
I have done a lot of it, but now im stuck. I am really new to java so forgive me. When it prompts to ask for another number it does it but it still displays it for the self-made lottery picks that display. Also, when displaying the numbers for the computer made lottery picks they are the same numbers over again that repeat and aren't 6 numbers. The counter doesn't work as well it maybe a little thing but i can't figure it out. Thank you
package arraysIntroduction;
import java.util.Scanner;
public class sizeQuestion {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int [] user =new int [6];
int i;
//Fill user array
System.err.println("Welcome to Miwand's Lottery");
System.out.println("Please enter your 6 desiered number to enter the lottery");
System.out.println("Pick from 1 to 49");
for ( i=0;i<user.length;i++) // gets numbers until it equals 6
{
System.out.println("Number:");
user[i]= in.nextInt(); // Gets numbers from user
while (user[i] < 0 ) // if its a negative number tell user to enter again
{
System.err.println("Negative number, please enter again:");
user[i]=in.nextInt();
}
if (user[i] > 49) // if the number goes past 49 prompt again
{
System.err.println("Please enter numbers from 1 - 49");
}
}
//print out the numbers generated
for ( i=0;i < user.length; i++){
System.out.print(+user[i]+ " ");
}
System.out.println(" ");
int[] lottery = new int[6];
int guesses;
int counter=0;
int j;
int x;
{
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() *49 +1); // Random number created here.
for ( x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() *49 +1);// If random number is same, another number generated.
}
lottery[j] = randomNum;
}
}
//prints out computer generated numbers
for (i = 0; i < lottery.length; i++){
for (x = 0; x< j; x++){
System.out.print(lottery[i] + " ");
if (user[i] == lottery[x] ){
counter++;
}
}
}
}
if (counter < 2){
System.out.println("Try again!");
}
if (counter == 3){
System.out.println("3 numbers matched! You won $300!");
}
if (counter == 4){
System.out.println("4 numbers matched! You won 500!");
}
if (counter == 5){
System.out.println(" 5 numbers matched! You won $1000!");
}
else if (counter == 6){
System.out.println("JACCKKKPOOOOTTTTTTT!!!!!! YOU WIN 1 MILLION DOLLARS!");
}
}
}
I saw multiple problems in your program.
First, the printout problem can be solved by moving the print statement from inner loop to outer loop
for (i = 0; i < lottery.length; i++) {
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) {
if (user[i] == lottery[x]) {
counter++;
}
}
}
Also, you are not assigning the first random number correctly and it is always using the default, which is 0
Solution:
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() * 49 + 1); // Random number created here.
for (x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 49 + 1);// If random number is same, another number generated.
}
}
lottery[j] = randomNum;
}
Plus, you didn't check if counter is equal to 2
Solution:
if (counter <= 2) {
System.out.println("Try again!");
}
And, the logic in "If random number is same, another number generated." may not be correct, since it may generate the same number again. You need a while loop to generate a new number until it is not equal to any of the generated numbers.
Another thing about coding style is that for any "for loops"
This :
int i=0;
for (i = 0; i < length; i++)
Should be replaced by this:
for (int i = 0; i < length; i++)
As I already said in the comments, you should move the print statement from the inner loop to the outer loop.
Your code should look like this:
for (i = 0; i < lottery.length; i++) { // outer loop
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) { // inner loop
if (user[i] == lottery[x]) {
counter++;
}
}
}

why is it when i run this program after entering 10 numbers it gives me the first number occurs 100 times?

import java.util.Scanner;
public class Ex7_3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("This program that reads the integers between 1 and 100 and counts the occurrences of each");
int [] counts = new int [101];
System.out.println("Enter the integers between 1 and 100:");
int next = input.nextInt();
while (next != 0){
if(next >= 1 && next<= 100)
counts [next]++;
next = input.nextInt();
for(int i =0; i< counts.length;i++)
for(int j = 0; j <= 100; j++)
if(counts[next] > 1){
System.out.println(next + "occurs" + j + "times");
}
}
}
}
The solution should be like this?
Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
Your loop at the end doesn't make much sense to me. You probably want something like this
Scanner input = new Scanner(System.in);
System.out.println("This program that reads the integers between 1 and 100 and counts the occurrences of each");
int [] counts = new int [101];
System.out.println("Enter the integers between 1 and 100:");
int next = input.nextInt();
while (next != 0){
if(next >= 1 && next<= 100)
counts [next]++;
next = input.nextInt();
}
// Here's the change
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0) {
System.out.println(i + " occurs " + counts[i] + " times.");
}
}

Categories