Having trouble with in.nextDouble() - java

I'm trying to use the in.nextDouble() method in the below program designed to compute the average of a few numbers.
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double value;
int count = 0;
double sum = 0;
System.out.print("Enter a value, Q to quit: ");
while (in.hasNextDouble())
{
value = in.nextDouble();
sum = sum + value;
count++;
System.out.print("Enter a value, Q to quit: ");
}
double average = sum / count;
System.out.printf("Average: %.2f\n", average);
}
}
This code works although I don't understand why. When I first use while(in.hasNextDouble()) I haven't initialised in to anything so why does the loop work?

When you call in.hasNextXXX() when there is no input, the Scanner waits for input.
So, it waits for you to enter a value in the first case.
It will exit as soon as you enter something other than a double (and press enter).
The doc of Scanner#hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
This is true for all hasNextXXX() operations.

Related

Java Sum of numbers until string is entered

i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END
One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.
Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;

How do you use a method to calculate 1 array parameter of grades and returns the total of the array?

My schoolwork is asking me to write a Java program. I'm not getting something quite right.
Basically I have to create a Java method that gets a user to enter x amount of grades (users choice), store the grades in an array and then add the grades in the array up to be called in the main method.
Here's my code:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int [] storeGrades = new int[numberOfGrades];
}
public static int getTotalScore(int numberOfGrades[]) {
Scanner keyboard = new Scanner(System.in);
int getTotalScore;
int []storeGrades;
for (int i = 0; i < getTotalScore; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
int userGradeNumbers = keyboard.nextInt();
storeGrades[i] = userGradeNumbers;
sum += userGradeNumbers;
}
}
}
I'm getting an error at "sum" that it hasn't been resolved to a variable? It won't let me initialize sum within the for loop, nor the getTotalScore method. Why not?
First, get the grades. Then call the method to get the sum. Declare the sum and initialize it to 0 before your loop. Return it after. Like,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println(getTotalScore(storeGrades));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
Your code has the right intent about it, but some of the ordering of things is a little off and there are syntactical issues at the moment.
I would advocate splitting up your code into two methods (unless you're specifically prohibited from doing so based on the assignment). One method to get the grades from the user, and another to sum the grades. The reason for this, is that you end up trying to both store and sum the grades at the same time (which is technically more efficient), but that doesn't teach you how to calculate a running total by iterating over an array (which is likely the point of the lesson).
One other thing that I would call out (which may be beyond where you are in the course right now), is that when you're using a Scanner, you need to validate that the user has typed what you think they've typed. It's entirely plausible that you want the user to type a number, and they type "Avocado." Because Java is strongly typed, this will cause your program to throw an exception and crash. I've added in some basic input validations as an example of how you can do this; the general idea is:
1) Check that the Scanner has an int
2) If it doesn't have an int, ask the user to try again
3) Else, it has an int and you're good to proceed. Store the value.
One last thing about Scanners. Remember to close them! If you don't, you can end up with a memory leak as the Scanner continues to run.
Below is how I would have revised your code to do what you want. Shoot me a comment if something doesn't make sense, and I'll explain further. I left comments inline, as I figured that was easier to digest!
package executor;
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Initial prompt to the user
System.out.println("Hello Drews, how many total grades do you want to process?");
// This loop validates that the user has actually entered an integer, and prevents
// an InputMismatchException from being thrown and blowing up the program.
int numberOfGrades = 0;
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
// If the program makes it through the while loop, we know that the Scanner has an int, and can assign it.
numberOfGrades = keyboard.nextInt();
// Creating the array using the method getGrades().
int[] storedGrades = getGrades(numberOfGrades, keyboard);
// Calculating the total score using the method getTotalScore().
int totalScore = getTotalScore(storedGrades);
System.out.println("Total Score is: " + totalScore);
keyboard.close();
}
/**
* Asks the user to provide a number of grades they wish to sum.
* #param numberOfGrades the total number of grades that will be requested from the user.
* #param keyboard the scanner that the user will use to provide the grades.
* #return the summed grades as an int.
*/
public static int[] getGrades(int numberOfGrades, Scanner keyboard) {
int[] grades = new int[numberOfGrades];
// Asking the user i number of times, to enter a grade to store.
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ":");
// More input validation to ensure the user can't store "Cat."
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
int userEnteredGrade = keyboard.nextInt();
// Storing the user's entry.
grades[i] = userEnteredGrade;
}
return grades;
}
/**
* Sums all of the grades stored within an integer array.
* #param storedGrades the grades to be summed.
* #return the total value of summed grades.
*/
public static int getTotalScore(int[] storedGrades) {
int totalScore = 0;
for (int i = 0; i < storedGrades.length; i++) {
totalScore += storedGrades[i];
}
return totalScore;
}
}

I am trying to get user input until user enter 0 and then show maximum value among them in JAVA

I am a beginner to java and don't know to write a program using loops that prompt the user to enter a number till user does does not enter 0.
When user enter 0 then system should display MAX number among user input
QUE 2
Write a program to ask the user to enter a sequence of numbers (double type). The numbers are separated by the return key (and give a prompt for each enter). The user ends the sequence by entering a 0. Then output the maximum number of all the entered numbers. Here is an example (the part in italic is the user’s input): Please enter a sequence of numbers, separated by return, and then end this sequence with a 0 at last: 25
Next number: 35.6
Next number: 112.112
Next number: 0
The maximum among your enters is 112.112
import java.util.Scanner;
public class Q3
{
public static void main(String[] args[])
{
double n;
// double i;
double MAX=0;
System.out.println("Please Enter the number: ");
Scanner Kb = new Scanner(System.in);
n = Kb.nextDouble();
if(n>0){
System.out.println("Please Enter the number: ");
n = Kb.nextDouble();
return;
}
else if(n==0) {
if (MAX>0){
MAX=n;
return ;
}
}
return;
}
}
Keep track of the max and each time a user inputs a number check if it is greater than that max
import java.util.Scanner;
public class Q3 {
public static void main(String... args) {
double max = 0;
System.out.println("Please enter the number: ");
Scanner kb = new Scanner(System.in);
double number = kb.nextDouble();
while (number != 0) {
if (max < number) {
max = number;
}
number = kb.nextDouble();
}
System.out.print("The max is " + max);
}
}
Since zero is the terminal character then negative input can be essentially ignored and the initial value of max as zero is acceptable.
Note that nextDouble can throw an InputMismatchException if the user decides to give you input that can not be parsed to a double.
using Collections.max ,
List<Double> doubleList = new ArrayList<>();
System.out.println("enter a number :");
Scanner kb = new Scanner(System.in);
while (kb.hasNext() ) {
double input = kb.nextDouble();
if(input == 0){
break;
}
doubleList.add(input);
}
System.out.println("Max Value Entered : " + Collections.max(doubleList));
Scanner sc = new Scanner(System.in);
double max = 0;
while(true){
double number = sc.nextDouble();
if(max<number){
max = number;
}
else if(number==0){
break;
}
}
System.out.print(max);

Collecting two integers in a loop to take a weighted average (without an array)

I'm working on an assignment where I need to ask the user for console input for how many items they have, then ask them for two integers (earned and max possible) which I can then calculate the weighted average. It needs to be done with a loop, not an array for this assignment. I have figured out how to gather the number of items and one of the integers, but I don't know how to gather multiple integers within a for loop. Here's the method I have so far:
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
I am able to tally the sum of earned scores with this method, but not the maximum possible scores so that I can take a weighted average.
Thanks!
You need to read the user input (only) integers in a loop and sum each values(weighted and score). You could return one of the sums with something like the following:
public int returnSum() {
Scanner keyboard = new Scanner(System.in);
boolean isValid = false;
int sum1;
while (*NotAtEndOfInput or Some Condition to Signal End of Input*) {
System.out.print("Please enter score: ");
try {
num = keyboard.nextInt();
sum1+=num;
} catch (InputMismatchException ex) {
//In case user enters anything else than integer, catch
//the exception and let the program move ahead to let the user enter again.
System.out.println("Wrong input. Ony integer input will be processed.");
//discards anything which is not int
keyboard.nextLine();
}finally{
//close input stream to avoid memory leak.
keyboard.close();
}
}
return sum1;
}
You will need to read and sum the other number similarly. Hope this helps.

How many integers, addition of integers

import java.util.Scanner;
public class InputLoop
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer to continue or a non integer to finish");
while (scan.hasNextInt())
{
System.out.println("Enter an integer to continue or a non integer to finish");
int value = scan.nextInt();
System.out.print("user: ");
}
scan.next();
{
System.out.println ("You entered");
System.out.println ();
}
}
}
Where it says 'you entered' I have to have how many Integers have been input, for example '3' and then the total of the integers added together for example '56'. I don't know how to do this, how can I implement this?
Maintain a List<Integer> and add to this list every time the user enters an integer. The number of integers added will therefore simply be list.size(). With what you're doing currently, there is no way to access the user's old inputs.
You can alternatively use variables that store the total and the count (which will work fine in this case), but in my opinion using the List approach will give you much greater flexibility if you ever decide to update/revise this code, which is something you should bear in mind as a programmer.
List<Integer> inputs = new ArrayList<Integer>();
while (scan.hasNextInt()) {
...
inputs.add(scan.nextInt());
}
...
Just keep a variable named count and a variable named sum.
And change your code in the while loop to:
int value = scan.nextInt();
sum += value;
count++;
In the end you can output both after the while loop ends.
By the way you don't need to put those curly braces { } after scan.next();
They're unrelated, and will always be executed independently of scan.next();
So just change it to:
scan.next(); //I presume you want this to clear the rest of the buffer?
System.out.println("You entered " + count + " numbers");
System.out.println("The total is " + sum);
have a count variable, declared at the beginning of main and increment it.
you can also mantain a sum variable in the same way.
while (scan.hasNextInt())
{
System.out.println("Enter an integer to continue or a non integer to finish");
int value = scan.nextInt();
count++;
sum += value;
System.out.print("user: ");
}
scan.next();
{
System.out.println ("You entered");
System.out.println (count);
}
For what you want to output, you don't need to keep a history of the user's input. All you need are a running total and a count. You also don't need the last call to scan.next() or to enclose the last println calls in a separate block.
public class InputLoop
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer to continue or a non integer to finish");
int total = 0;
int count = 0;
while (scan.hasNextInt())
{
System.out.println("Enter an integer to continue or a non integer to finish");
int value = scan.nextInt();
total += value;
++count;
System.out.print("user: ");
}
System.out.println ("You entered " + count + " values with a total of " + total);
}
}

Categories

Resources