Why I am getting a RUNTIME ERROR when using Scanner in JAVA - 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

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++;
}
}

asking a user to reenter data in a 2d array - java

Good afternoon,
I'm writing a program that asks a user to enter two numbers into a 2d array. The 1st number needs to be between 1 and 20 and the second number needs to be between 1 and 5.
I've written the part to take the input from the user
import java.util.Scanner;
public class store {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[][] maxtrix = new double[4][2];
for (int i = 0; i < maxtrix.length; i++) {
System.out.print("Enter the amount of apples (1-20) and oranges (1-5) for bag " + (i+1) + ": ");
for (int j = 0; j < maxtrix[i].length; j++) {
maxtrix[i][j] = input.nextDouble();
}
}
The question I have is what would be the best way to ask the user to reenter the data if they are outside the given ranges. I have used a do while before to ask a user to reenter if they input is outside the range but can't seem to figure it out within a 2d array.
Thanks for any tips or hints in advance.
Try this... I intentionally kept 2 nested loops as you did. You can also enter apples and oranges separately to simplify this.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[][] maxtrix = new double[4][2];
boolean areApplesEntered = false, areOrangesEntered = false;
for (int i = 0; i < maxtrix.length; i++) {
areApplesEntered = false;
areOrangesEntered = false;
for (int j = 0; j < maxtrix[i].length; j++) {
double apples, oranges;
if (areApplesEntered == false) {
do {
System.out.println("Enter the # of apples between 1 and 20 for the bag ["+(i+1) +"] -->");
apples = input.nextDouble();
} while (apples < 1 || apples > 20);
maxtrix[i][j] = apples;
areApplesEntered = true;
} else {
do {
System.out.println("Enter the # of oranges between 1 and 5 for the bag ["+(i+1)+"] -->");
oranges = input.nextDouble();
} while (oranges < 1 || oranges > 5);
maxtrix[i][j] = oranges;
areOrangesEntered = true;
}
}
}
}
You might want to set up some while loops to check for your conditions:
System.out.println("Please enter the number of apples (from 1 to 20): ");
while (input.hasNextDouble()) {
double temp = input.nextDouble();
if (temp < 1 || temp > 20) {
System.out.println("\nThe number of apples must be a number in [1..20]. \nPlease enter a valid amount: ");
continue;
}
else {
matrix[0][0] = temp;
break;
}
}
System.out.println("Please enter the number of oranges (from 1 to 5): ");
while (input.hasNextDouble()) {
double temp = input.nextDouble();
if (temp < 1 || temp > 5) {
System.out.println("\nThe number of oranges must be a number in [1..5]. \nPlease enter a valid amount: ");
continue;
}
else {
matrix[0][1] = temp;
break;
}
}
I am assuming by your post that you are just entering two numbers total..

I am getting unexpected output from this code:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int i = 0;
int x;
x=input.nextInt();
int y;
y=input.nextInt();
while(i<y){
for ( i = 1; i <=y; i=i+x) {
for ( int j = i; j <=(i+(x-1)); j++) {
if(x%2==0 && y%3==0)
{
System.out.print((j-1)+" ");
}
else
System.out.print(j+" ");
}
System.out.println();
}
}
Sample input:
3 99
This is the output I am supposed to get :
1 2 3
4 5 6
7 8 9
10 11 12
...
97 98 99
But when I give my input as
4 99
The output I get is :
0 1 2 3
4 5 6 7
....
96 97 98 99
I am not supposed to start with 0.
What is wrong in my code?
I tried to rewrite your code a little so that it isn't so messy. Is this what you want to achieve?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=input.nextInt();
int y=input.nextInt();
for (int i = 1; i < y + 1; i++) {
System.out.print(i + " ");
if (i % x == 0){
System.out.println();
}
}
input.close();
}
Scanner input=new Scanner(System.in);
int i = 1;
int j = 0;
int x;
x=input.nextInt();
int y;
y=input.nextInt();
for( i = 1; i <=y; i++) {
System.out.print(i);
System.out.print(" ");
j++;
if(j == x){
System.out.println();
j = 0;
}
}
you can use this code to output as you expect.
Your first output is going to be a 4 because at that time x = 3 and y = 99. Neither are even so your else block will be hit. Change if(x%2==0 && y%3==0) to if(x%2==0 || y%3==0) and you will get 0 for the first output. That won't totally fix your problem but it will get you on the right path.
You begin j=1 (because i = 1 the first time you enter the loop)
and if x%2 == 0 (which is the case) you print j-1
of course you will begin with 0, I don't see why you're surprised.
if you want to avoid that, just print :
(j-1)==0 ? "" : j-1 + " "

How can I write this same statement using for loops instead of while loops?

The idea here is to learn how to apply different methods to the same problem in order to learn and see the differences
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
input = new Scanner(System.in);
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
int i = k;
while (i <= j)
{
if (i%2 == 0)
{
System.out.println(i);
}
i++;
}
I am trying this, but it is clearly wrong, how can I fix it, or where should i look?
for(i<=j;i % 2 ==0;i++)
{
System.out.println(i);
}}
When doing conversion from one loop to the other, it will be much easier if we first understand the intention of the original loop. From what you have:
while (i <= j){
if (i%2 == 0)
System.out.println(i);
i++;
}
In plain English, it means:
From the lower bound input to the upper bound input, print out all the even numbers (inclusive of zeroes).
Now based on that, we write a for-loop.
for(int x=k, x<=j; x++) //k is lower bound, j is upper bound
if(x % 2 == 0) //if current number is even or 0
System.out.println(x); //print that number
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
input = new Scanner(System.in);
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
int i = k;
for (;i <= j;i++) {
if (i%2 == 0) {
System.out.println(i);
}
}
Translated in for loop.
for (int i = k; i <= j; i++) {
if (i%2 ==0) {
System.out.println(i);
}
}

NullPointerException when using Scanner.nextInt() [duplicate]

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

Categories