Unknown runtime error in java - java

I want to create a class that simulates registers of a market and the project requires that after the user gives us how many registers he wants , he must give a string in the form below:
for exaple : 0 0 0 1 1 1 2 2 2 3 3 5 5 6 6
which means that 3 customers entered the store at monent 0 , 3 customers entered the store at moment 1 etc.
Here is my code:
import java.util.Scanner;
import java.io.*;
public class QueueSimulation
{
public static void main(String[] args)
{
int a;
int i = 0;
String input;
Scanner s = new Scanner(System.in);
int A[] = new int[10000];
System.out.println("This programs simulates a queue of customers at registers.");
System.out.println("Enter the number of registers you want to simulate:");
a = s.nextInt();
while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");
a = s.nextInt();
}
int fifo[] = new int[a];
System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.
Enter : ");
input = s.nextLine();
while(s.hasNext()){
while(s.hasNextInt()){
A[i] = s.nextInt();
i++;
}
s.close();
}
s.close();
}
}
The code compiles fine , but when i run it, something goes very wrong with the 2 while loops and the programs nevers end or stop. Complile if you have the time and you will understand. I dont know maybe i placed the close() method somewhere wrong? Please help.

You are missing a s.next(); in the given code.
while(s.hasNext()){
while(s.hasNextInt()){
A[i] = s.nextInt();
i++;
}
// here s.next() is missing...
s.close();
}
Please add the s.next(); statement before the end of second-while loop of your program for proper iteration of your program...

Related

iterate over two vectors with some conditions up to ten times

I have two vectors, vectorName and vectorNum, I need to iterate over them asking for input up to ten times or until nothing is entered, the problem is that when I reach the 10th loop it asks for vectorName an 11th time and then throws IndexOutOfBoundsException
this is my code:
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int nameQuantity = 0;
int numQuantity = 0;
String vectorName[] = new String[10];
int vectorNum[] = new int[10];
System.out.println("enter name or enter nothing to end");
vectorName[nameQuantity] = read.nextLine();
if (vectorName[nameQuantity].length()==0) {
System.out.println("end");
}else {
nameQuantity++;
while(nameQuantity<11) {
System.out.println("enter a number from 1 to 12");
int num = read.nextInt();
if (num<=12 && num>=1) {
vectorNum[numQuantity] = num;
numQuantity++;
System.out.println("enter name or enter nothing to end");
read.nextLine();
vectorName[nameQuantity] = read.nextLine();
if(vectorName[nameQuantity].length() == 0 || numQuantity == 10) {
for (int n = 0; n<=numQuantity-1; n++) {
System.out.print("\n " + vectorName[n] + " "+ vectorNum[n]);
}
nameQuantity = 11;
}else {
nameQuantity++;
}
}else {
System.out.println("number must be from 1 to 12");
}
}
}
}
}
I tried changing the vector size to 11 which worked but as a result it saves an 11th name which I don't need since I expect it to ask only up to ten times the names and numbers.
I also tried changing the do while to a while, the same thing happens.
Start of 1st Iteration:
nameQuantity = 1
numQuantity = 0
Start of 2nd Iteration:
nameQuantity = 2
numQuantity = 1
...
Start of 10th Iteration:
nameQuantity = 10
numQuantity = 9
Calling vectorName[nameQuantity] will cause the IndexOutOfBoundsException at this point, since vectorName has a size of 10, meaning the last index is 9.
I'm not sure why you're asking for the user to enter a name, then starting a loop where you ask for a number and then ask for a name.
Your logic:
Receive name from user
If name is empty
Stop
Else
Loop 10 times:
Receive number from user
If name is empty or received 10 numbers
Stop
Why not just have everything in a loop where you ask for a name first, and if a name was provided, ask for a number?
Loop 10 times
Receive name from user
If name is empty
Stop
Else
Receive number from user

Java do-while loop executes only 2 runs [duplicate]

This question already has answers here:
Java: Infinite loop using Scanner in.hasNextInt()
(4 answers)
Closed 3 years ago.
I am trying to do a simple program where the user selects a number 1,2,3 for a simple calculation. The program will continue to run unless the user types in '0' when asked on the menu. The same menu will be presented to the user as long as they select 1, 2 or 3.If the user was to select 0, the program will terminate.
The code I have:
import java.util.Scanner;
public class QuadraticSolving {
public static void main(String[] args) {
// Declarations
int user;
double a;
double b;
double c;
int num1;
int num2;
Scanner in = new Scanner(System.in);// Create scanner in
do{
System.out.print("Press 0 to exit, 1 for Multiplication Solving, 2 for Sum or 3 for Print Message:");// main menu
user = in.nextInt();
}
while(user == 0);
{
if(user == 1)// multiplication solver
{
System.out.print("Enter a:");
a = in.nextDouble();
System.out.print("Enter b:");
b = in.nextDouble();
System.out.print("Enter c:");
c = in.nextDouble();
System.out.println(a*b*c);
}
else if(user == 2)// addition
{
System.out.print("Enter an integer:");
num1 = in.nextInt();
System.out.print("Enter another integer:");
num2 = in.nextInt();
System.out.println(num1 + num2);
// System.out.println(allSum(num1,num2));
System.out.print("");
}
else if (user == 3)// welcome statement
{
System.out.println("Welcome to IT");
}
else
{
System.out.println("Bye");
break;
}
System.out.print("Press 0 to exit, 1 for Multiplication Solving, 2 for Sum or 3 for Print Message:");
user = in.nextInt();
}
}
After the first run through the menu, it works perfectly. During the 2nd run, it always terminates the program, no matter what choice you pick.
Outcome example here
Whenever I enter '0' for all the runs it turns into an endless loop. The only way I can stop it is by ending the execution of the code.
Endless example here
I don't understand why the program only runs perfectly the first time and the 2nd run it terminates on its own. Also, I don't get why it goes into an endless loop when the user enters '0'. Any explanation as to why this happens? (Sorry for bothering, I am new to programming. Thanks)
It enters in a endless loop when the user types 0 because the while expression is checking if the typed number is equal to 0 and not different
And it is running ok on the first time because the code that runs after the while is not repeating, it only executes once, that code should be inside here
do {
.
. // Here you scan
. // Here you paste the logic
.
} while (user != 0);

Cannot get input in simple output program in Java

I will keep this short and simple, here's the program-
class Sample{
private int n;
public void getDetails(){
Scanner y=new Scanner(System.in);
n=y.nextInt();
System.out.println("Entered 'n' = "+n);
}
public void displayDetails(){
int i,j;
int arr[]=new int[n];
Scanner x=new Scanner(System.in);
for(j=0;j<n;j++) {
arr[j] = x.nextInt();
System.out.println("Entered element = "+arr[j]);
}
System.out.println("Entered array: ");
for(i=0;i<n;i++)
System.out.print(arr[i]+" ");
}
}
public class TestClass {
public static void main(String[] args) {
Sample obj = new Sample();
obj.getDetails();
obj.displayDetails();
}
}
This simple program just takes number of elements(n) and the elements of array(arr[]) as input in different methods.
When the input is given in interactive mode, everything works fine. Here's the console output-
5
Entered 'n' = 5
1 2 3 4 5
Entered element = 1
Entered element = 2
Entered element = 3
Entered element = 4
Entered element = 5
Entered array:
1 2 3 4 5
But when I give it as Stdin input(or all input at once), it just takes the number of elements(n) and ignores my array input(arr[]). Here I had to give the array elements again. Console output-
5
1 2 3 4 5Entered 'n' = 5
1
Entered element = 1
2
Entered element = 2
3 4 5
Entered element = 3
Entered element = 4
Entered element = 5
Entered array:
1 2 3 4 5
I have no idea what is happening. Is it a bug? Please help
Part of the problem is that you are creating multiple scanners. Create one scanner and use it everywhere, like so:
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
Sample obj = new Sample();
obj.getArraySize();
obj.displayDetails();
}
}
class Sample{
private int arraySize;
Scanner scanner = new Scanner(System.in);
public void getArraySize(){
System.out.print("Enter size of array: ");
arraySize = scanner.nextInt();
System.out.println("Entered array size = " + arraySize);
}
public void displayDetails(){
//Create an integer array of size arraySize
int intArray[] = new int[arraySize];
//Repeatedly request integers for the array
for( int i=0; i<arraySize; i++) {
int nextInt = scanner.nextInt();
intArray[i] = nextInt;
System.out.println("Entered element = " + intArray[i]);
}
//Print out the entered elements
System.out.println("Entered array: ");
for( int i=0; i<arraySize; i++) {
System.out.print(intArray[i]+" ");
}
scanner.close();
}
}
console output:
Enter size of array: 5
Entered array size = 5
5 4 3 2 1
Entered element = 5
Entered element = 4
Entered element = 3
Entered element = 2
Entered element = 1
Entered array:
5 4 3 2 1
You still need to check that the next value is actually an int. If you put a different type of value in there, like a letter, it will crash. See these links for additional details:
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Java Multiple Scanners
Why is not possible to reopen a closed (standard) stream?
You areusing scanner to take userinput.
Scanner y=new Scanner(System.in);
In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() doesn’t not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().
In BufferReader class there is no such type of problem. This problem occurs only for Scanner class, due to nextXXX() methods ignore newline character and nextLine() only reads newline character. If we use one more call of nextLine() method between nextXXX() and nextLine(), then this problem will not occur because nextLine() will consume the newline character.
Please check this SO link it has good explaination.

GPA calculator assistance

Hi I was wondering if I could get some help with a GPA calculator.
What it needs to do is:
The input will consist of a sequence of terms, e.g., semesters.
The input for each term will consist of grades and credits for courses taken within that term.
For each term, the user will type in an integer that represents the number of courses
taken within that term.
Each course is specified by a String letter grade and an int number of credits, in that order, separated by white space. 5. If the user types in -1 for the number of courses taken in a term, then the program must print a final overall summary and then terminate.
DO NOT prompt for any input. Thus, after you run your program in BlueJ, type Ctrl-T to force the Terminal window to pop up.
As always, follow the input / output format depicted in the Sample runs section.
Shown below is the error message I get and the code I have, thank you for any assistance in advance or tips I could try.
Terminal window and error message:
import java.util.Scanner;
/*
*
*
*/
public class Prog2 {
public static void main(String args[]) {
Scanner numberInput = new Scanner(System.in);
int numberofClasses = numberInput.nextInt();
Scanner input = new Scanner(System.in);
String [] grade = new String[5];
int [] credit = new int [5];
double totalCredit = 0.0;
double realGrade = 0.0;
double result = 0.0;
while (numberofClasses > 0)
{
for (int x = 0; x < numberofClasses; x++ )
{
grade[x] = input.next();
credit[x] = input.nextInt();
}
for(int x=0;x < numberofClasses; x++ ){
if(grade[x].equals("A+")){
realGrade=4.0;
}
else if(grade[x].equals("A")){
realGrade=4.0;
}
else if(grade[x].equals("A-")){
realGrade=3.67;
}
else if(grade[x].equals("B+")){
realGrade=3.33;
}
else if(grade[x].equals("B")){
realGrade=3.00;
}
else if(grade[x].equals("B-")){
realGrade=2.67;
}
else if(grade[x].equals("C+")){
realGrade=2.33;
}
else if(grade[x].equals("C")){
realGrade=2.00;
}
else if(grade[x].equals("C-")){
realGrade=1.33;
}
result = result+realGrade*credit[x];
totalCredit=totalCredit+credit[x];
}
System.out.println("Summary for term:");
System.out.println("----------------------------------");
System.out.println("Term total grade points: " + result);
System.out.println("Term total credits:" + totalCredit);
System.out.println("GPA:"+result/totalCredit);
}
// This block is getting used later please ignore
System.out.println("Final Summary:");
System.out.println("----------------------------------");
System.out.println(" Overall terms");
System.out.println(" Total grade points: " + result);// this needs to be all );
System.out.println(" Total credits" + totalCredit);//This needs to be all );
System.out.println("Cumulative GPA:"+result/totalCredit);
}
}
When your while loop ends, numberofClasses still contains the value that was entered before the while loop started the first time. Specifically, after you output the line:
GPA=3.0588...
you hit the end of the loop, then return to:
while (numberofClasses > 0)
which is true. The next "3" that you enter doesn't go into numberofClasses, it is picked up by
grade[x] = input.next();
Then the "A" is picked up by
credit[x] = input.nextInt();
which throws an exception since it's not an integer.
All you need to do is ask for the number of classes again at the end of the while loop:
System.out.println("GPA:"+result/totalCredit);
numberofClasses = numberInput.nextInt();
}
Output:
5
A 3
B 2
C 4
A 5
C 3
Summary for term:
----------------------------------
Term total grade points: 52.0
Term total credits:17.0
GPA:3.0588235294117645
3
A 3
B 5
C 1
Summary for term:
----------------------------------
Term total grade points: 81.0
Term total credits:26.0
GPA:3.1153846153846154
i recommend looking into whether your compiler or IDE has a "debug" feature. It is a very helpful tool, and lets you watch how your program goes through your code
Just a tip...
When you ask for input, print what you're asking for first. When I launched your program I had no idea what to do. Try adding System.out.println("input number of classes you took");before you prompt for that number.
Here is what is wrong. (If you printed what you're asking for first, this would be more apparent).
after your program displays the stats, you enter 5. Yet your program is actually still on this line grade[x] = input.next(); on line 22 i believe.
when you enter 5, your scanner is expecting a letter. and an exception is thrown.
you need to consider how you escape this loop here. while (numberofClasses > 0) perhaps use an if statement? otherwise your program loops for forever, never asking for a new class number

Displaying loop in JOptionPane

I'm a beginner in Java programming, and I have an assignment on while loops.
The assignment was to have windows open up with the numbers 1-10 on display.
The first two, I got down. The third one was to have the user enter a number 'x', and the next window was to show all integers between 1 and 'x' using a while loop.
As I have it coded now, each loop iteration pops up in it's own window, instead of all at once, in one window.
TL;DR I want to have 1 window with 10 loops, not 10 windows with 1 loop each.
JOptionPane and while loops were in the handouts and notes he had us take, but no mention of how to combine them.
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text=JOptionPane.showInputDialog("Please enter a number: ");
int f,x;
f=0;
x=Integer.parseInt(text);
while (f<=x)
{//What am I doing wrong between here
JOptionPane.showMessageDialog(null, f);
f++;
}//and here?
}
}
I believe that you wish to print out all numbers from x that are less than or equal to f in a single DialogBox and not every time the loop iterates.
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text = JOptionPane.showInputDialog("Please enter a number: ");
int f, x;
//if you wish to loop from 1 to x then f must start at 1 and not 0 because in your loop you print out f before it increases thus it would be 0.
f = 1;
x = Integer.parseInt(text);
StringBuilder sb = new StringBuilder();
while (f <= x)
{
//rather than show a message dialog every iteration append f and a new line to a StringBuilder for later use.
sb.append(f).append("\n");
//JOptionPane.showMessageDialog(null, f);
f++;
}
//string builder has a "\n" at the end so lets get rid of it by getting a substring
String out = sb.substring(0, sb.length() - 1);
JOptionPane.showMessageDialog(null, out);
}
}

Categories