While loop using Scanner method hasNext() fails to loop, exits unexpectedly - java

So I've been working on an assignment for school. It says to make a program that does the following:
1. Prompt user for input
2. Take input from user three times, store as floats
3. Pass variables to method minimum() which uses Math.min() to calculate the minimum.
4. Print the result
5. Prompt user again and loop until EOF is received
Well, I did that but it didn't feel like a challenge. I've modified the code so that it keeps prompting the user for input and adding elements to an ArrayList which gets passed to minimum() which returns a float that gets printed, then the program should prompt the user for input once more and it should loop again until an EOF is received.
// imports
import java.util.Scanner;
import java.lang.Math;
import java.util.ArrayList;
public class FindMin{
public static void main(String args[]){
// define vars
float x;
int iter = 1;
// create new instance of Scanner called input
Scanner input = new Scanner(System.in);
// create new instance of ArrayList called nums with Float elements
ArrayList<Float> nums = new ArrayList<Float>();
// print the instructions and prompt the user for a number
System.out.printf("%s\n %s\n %s\n",
"Type the end-of-file indicator to terminate",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.print("Enter a number: ");
// loop until EOF, then quit
while(input.hasNext()){ // get user input and exit if input is EOF
// assign input to x, add x as a new element of nums, then prompt user
x = input.nextFloat();
nums.add(x);
iter++;
System.out.print("Enter a number: ");
// loop until EOF, then calculate min
while(input.hasNext()){
x = input.nextFloat();
nums.add(x);
iter++;
System.out.print("Enter a number: ");
} // end while
// calculate min and set iter back to 1
System.out.printf("\n Minimum is: %f\n\n", minimum(nums));
iter=1;
// re-prompt user
System.out.printf("%s\n %s\n %s\n",
"Type the end-of-file indicator to terminate",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.print("Enter a number: ");
} // end while, should continue looping but doesn't
} // end method main
public static float minimum(ArrayList<Float> n){ // returns a float, takes an ArrayList with <Float> elements
// assigns element at index 0 of n to min
float min = n.get(0).floatValue();
// iterates through i and assigns min to Math.min() called with previous
// value of min and element at index i of n
for(int i=1;i < n.size();i++){
min = Math.min(min, n.get(i).floatValue());
} // end for
return min;
} // end method minimum
} // end class FindMin
The problem is that the outer loop exits unexpectedly. It's my understanding that input.hasNext() prompts the user for input and returns true if there is input, if not, it returns false. It doesn't seem to check for input though. Can someone tell me what's happening?

One problem that you have going there that is likely doing what you think is the nested whiles.
Basically, once the inner while loop terminates, because it has the same condition as the outer while loop, the outer loop will execute the code between the inner loop and the ending brace and then exit as well. You said it yourself in the comments in the code- once the EOF is given, both loops terminate.

Related

Introducing an array to store scores in Java

The question I am working on is:
Write a program that:
asks the user how many exam scores there are (and verifies that the user entered a positive integer), prompt the user for each real-valued score, one by one (as shown below in Sample program behavior / output: box), Calculate and output the average of the scores and count and output how many scores are greater than the average (as shown below in Sample program behavior / output: box).
Sample program behavior / output:
How many exams scores do you have to enter? 5
Enter score #1: 95.0
Enter score #2: 92.0
Enter score #3: 68.0
Enter score #4: 72.0
Enter score #5: 70.0
The average score is: 79.4
There are 2 scores larger than the average.
This is my code:
import java.util.Scanner;
public class testee {
public static void main(String[] args) {
int examnum = -1;
Scanner scan = new Scanner (System.in);
while (examnum<0) {
System.out.println("How many exam scores do you have to enter?");
examnum = scan.nextInt( );
}
for (int i=1; i<=examnum; i++) {
System.out.println("Enter score #" + i + ": ");
for (int a=1; a<=i; a++) {
a = scan.nextInt();
}
}
}
}
What I did produces the following output however my problem is that I need to store the scores that are input to later compute an average so inside my for loop I would need to store the scores as an array but I do not know how to approach that.
First prompt looks good however there is one small problem.
Hint: What condition would you use for your while loop if you wanted to ensure that the value entered was not less than 1 since zero would be rather non-productive?
It's always nice to inform the User of any invalid entry.
To place items into an Array you need to declare that array and initialize it to the proper size:
int[] scoresArray = new int[examnum];
Think about this, where do you think this line of code should be placed?
Hint: You need to ensure that the required array size is already properly established.
Why use two for loops when you can use only one? What can the second (inner nested) for loop do that the outer for loop just simply can't do?
Hint: Nothing! "Enter score #" + (i+1) + ": ". Of course in this case i (within the initialization section) would need to start from 0 and always be less than examnum (within the termination section).
If you want to add an element to your array, where do you think would be a great place in your code to do that?
Hint: int score = scan.nextInt(); scoresArray[i] = score;.
Things to consider:
When scores are being entered, do you think the User entries should be validated? What if the User enters one or more (or all) alpha characters instead of digits in any of your prompts that require an Integer value? Do you end up getting an InputMismatchException? How would you handle such a thing?
Yes, you can nest while loops within a for loop and visa-versa.

How do I increment variables within an if statement to be used in another statement?

I'm having troubles figuring out how to increment a variable through an if statement, and allow it to be registered if called upon in a different if statement. I'm currently working on an assignment that mimics a menu for inputs. As shown, the user inputs a specific command, and on A, B, or C, they enter 3 scores/values. A separate input could be F, and on this input, it's supposed to show how many failures for each company, A, B, C has.
System.out.print("\nPlease enter a command:"); //Starts command prompt
String menuPrompt = scanner.next(); //Takes next input and uses one of the following if statements
if (menuPrompt.equals("a")) {
double aNum1;
double aNum2; //initializes a score inputs
double aNum3;
System.out.print("\nEnter number 1:");
aNum1 = scanner.nextDouble();
System.out.print("\nEnter number 2:");
aNum2 = scanner.nextDouble(); //asking for inputs of test values of company a
System.out.print("\nEnter number 3:");
aNum3 = scanner.nextDouble();
if(aNum1 < -6.0 || aNum1 > 12.3) {
aFailure = aFailure + 1;
}
if(aNum2 < -6.0 || aNum2 > 12.3) {
aFailure = aFailure + 1; //checks to see if inputted value is a failure, if so, failure ticks up 1.
}
if(aNum3 < -6.0 || aNum3 > 12.3) {
aFailure = aFailure + 1;
}
There are two other similar lines of code alike to this one just for "b" and "c". I initialized aFailure, bFailure, and cFailure at the top of the class and set their values to 0. After the if statements for the a, b, c prompts, I have this:
} else if (menuPrompt.equals("f")) {
System.out.print("\nAzuview Failures: " + aFailure);
System.out.print("\nBublon Failures: " + bFailure); //Lists total failures for each company
System.out.print("\nCryztal Failures: " + cFailure);
I'm not sure exactly how these variables are supposed to be defined, or if my formatting is even correct, help?
When you initialized a variable in a loop it is reinitialized every time the loop run again. When you initialized it outside of the loop it stays the same variable even in the loop. The concept behind a for loop is base on that.
In this example, the count is going to be incremented in every update of the while loop
So the count is going to be set to 0 and goes up by 1 until it reaches 9 when it will exit the loop
var count = 0;
while(count <10){
count++;
}
but in this one every time is going to loop in it. It reinitialized your variable count to 0 and increment it to 1. So every loop a new count is created and set to 1
while(true){
var count =0;
count++;
}
My first response on stack hope it helps you understand the concept a little better :)
I'm fairly sure I fixed this, instead of initializing within a while loop, I initialized it outside of the while loop and it seemed to fix this, any input on explaining the concepts behind this would be awesome!

Created a two condition While loop, one condition works as should the other causes an infinite loop

so im still new to java programming and for this program i need to make a program that calculates change for a vending machine. It is based of a 5 cent increment between a value of 25 cents to a dollar. for this assignment if i use a loop to force the user to input a value in bounds i get extra credit, since i originally was going to scratch because i wasnt getting it but soon did im back to using it. only thing is for one of my conditions it creates an infinite loop of the output message and im not sure why. any advice would be appreciated
/** Carmine A
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
float changeGiven;
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
int userInput;
int itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in 5-cent increments \n"
+ "Do not enter a decimal point");
//user inputs value to be set to variable
userInput= keyboard.nextInt();
//System.out.println("You entered ." +userInput + " as the price");
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
while(userInput>25 && userInput<100){
System.out.println("Price is in bounds");
System.out.println("Please enter a valid amount between 25-100");
itemCost=keyboard.nextInt();
}
}
itemCost=userInput;
//print out item cost based off users input
System.out.println("You enetered: " + itemCost +" as the items cost");
}
}
update
ok took what you guys said and made this
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
thanks for the help! knew it was something dumb, but this is why i ask for help so i can learn
so i believe it is frowned upon if i made another thread for the same program so i will add to this one.
i have completed just about everything i need but am having a few issues.
1. for some reason after i compile and run my code "Change Due:" prints twice, i am unsure why since i only have it once in a print statement but i can be missing it.
2.i need to print out in a money format and for some reason i have tried different formatting options and none will round (i have a feeling it is but it is not displaying because of the second "Change due:" printing) but can be wrong
3. on line 55 i am receiving this message and not sure why C:\Users\finst\Desktop\Intro to Java\Labs\Lab2\lab2Test.java:55: error: incompatible types: possible lossy conversion from double to int
changeRemainder= (changeDue*(double)100);
this is what i currently have:
/** Carmine
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
double userInput;
double itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in
5-cent increments");
//user inputs value to be set to variable
userInput= keyboard.nextDouble();
//while loop to make sure input stays in bounds
while(userInput<(.25) || userInput>(1.00)){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1
dollar");
userInput=keyboard.nextDouble();
}
//print out item cost based off users input
System.out.println("You entered: " + userInput +" as the items cost");
System.out.println("You entered a dollar to pay with");
//algorithm to calculate change due
int quarters;
int nickels;
int dimes;
int pennies;
int changeRemainder;
double changeDue;
double dollar=1;
//calculates change due
changeDue= (dollar - userInput);
//System.out.printf("%.2f" + "\n" ,changeDue);
//System.out.println("Change due:" + changeDue);
//makes the remainder into a number that can be used
changeRemainder= (changeDue*(double)100);
//calculates the amount of each coin needed to make the change
quarters= (changeRemainder / 25);
changeRemainder= changeRemainder % 25;
dimes= (changeRemainder/10);
changeRemainder= changeRemainder%10;
nickels=(changeRemainder/5);
changeRemainder= changeRemainder%5;
pennies=(changeRemainder);
//output statement to print coin amounts
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
As userInput is never updated in the loop then its value does not change and it will potentially loop for ever.
Maybe you mean userInput=keyboard.nextInt(); but you do not need two loops anyway.
userInput=keyboard.nextInt();
while (userInput<25 || userInput>100) {
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
You don't need 2 while loops; just one will do. In any case, your while loop checks the 'userInput' variable, but that never changes in the while loop; you are updating the itemCost variable instead.
I would use a Boolean for your while loop, and create an if else statement within this to check for valid entry and calculate the change. Hope this helps!
boolean end = true;
while (end) {
//retrieve user input of cost and assign value to variable
//create an if statement check if the value is valid
if(itemCost >=25 && itemCost <=100){
//retrieve user input for change entered
//calculate change for the user and display it
//end loop
end = false;
} else {
//invalid entry
end = false;
}
}

I need the input of the user to not skip the value 100

I'm currently working on a program for an O Level project where I have chosen to make a class management system. In my method class, I have various methods which control different functions of my program, such as one which collects the name of the students or one which displays a histogram of the student's grades. However, I have discovered a flaw in one of my methods. This is the method that lists the names of the students, one by one (which are saved in an array from a method that is executed before this method) and asks for the students marks. Here, the user is able to enter any number, which is inconvenient, considering that numerical grades normally range from 0-100. I have tried the following code but I have reached a predicament. The code does in fact stop the user from entering a mark over 100, but instead of allowing the user to re-enter a correct mark, it skips over to the next student, leaving the previous student without a mark. The following is said code:
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
marks[g] = Keyboard.readInt();
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
break;
}
}
}
Help would be very much appreciated and thank you in advance :)
Apologies if my English is not very good.
You almost got it - you need to read in your while-loop instead of breaking without reading. Also a do-loop would be more appropriate for not having to set an initial invalid value.
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
do {
System.out.println("Kindly enter a number that is less than 100");
marks[g] = Keyboard.readInt();
} while(marks[g]<0||marks[g]>100);
}
}
Set marks[ g ] to a number that isn't allowed before the loop, like - 1 then check the keyboard input inside of the while loop,
(and set It there every time as long as the while loop isn't stopped,
marks[g] = Keyboard.readInt();
and don't break the loop, as the loop would end anyways when the input is valid
The valid answers has to get into the array sequentially.
Use this simple trick to reset index [g] to the previous value
then you will overwrite the marks[g] value until you get a valid one:
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
g--; // Resetting index to previous value
break;
}

Break a while loop without using If or Break

I need to create a program that uses while to find the volume of a cylinder. I need the while loop to break if the user inputs a negative value for the height. My code looks like this:
double sentinel=1, h=1, v=0, r, count=0; // declares all variables needed
final double PI=3.14159;
boolean NotNegative=true;
while(NotNegative){// && count==0){ // while both the height is positive AND the total times run is 0
System.out.print("Enter height (Use negative to exit): "); // has the user input the height
h=Double.parseDouble(br.readLine());
sentinel=h; // save sentinel as the inputted height
while(sentinel>0){
System.out.print("Enter radius: "); // have the user input the radius
r=Double.parseDouble(br.readLine());
v=PI*(r*r)*h; // find the volume
System.out.println("The volume is " + v); // print out the volume
count++; // increase the count each time this runs
NotNegative=true;
sentinel=-1;
}
}
Any help?
You can throw an Exception which you catch and ignore. This is bad idea as
if and/or break is more efficient and simpler.
it's slow
it's confusing.
However, since you are using a while loop, which is like using an if & break, you can do the following.
NotNegative = h >= 0;
Add the following code inside the while(NotNegative){, after reading the input.
NotNegative = h >= 0;

Categories