I am attempting to fill an array with floating point numbers using a method. Every time I run my program it does not capture the first number entered.
How can I correct my code so it captures the first user input?
Thanks!
public static void main(String[] args)
{
//Read user input into the array
final int INITIAL_SIZE = 8;
double[] inputs = new double[INITIAL_SIZE];
Scanner in = new Scanner(System.in);
System.out.println("Please enter the number of credits for a course, Q to quit:");
double credits = in.nextDouble();
int currentSize = 0;
while (in.hasNextDouble())
{
if (credits <= 0)
{
System.out.println("All entries must be a positive number.");
}
else
{
// Grow the array if it has been completely filled
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = in.nextDouble();
currentSize++;
}
}
System.out.println(Arrays.toString(inputs));
}
Prolem is You did not store first user entry, so it's not showing to you
Scanner in = new Scanner(System.in);
System.out.println("Please enter the number of credits for a course, Q to quit:");
--> double credits = in.nextDouble();
You have taken the value from user but did not stored it in inputs
If you want to take value of credit from user and want to store credit in inputs then you should do:
double credits = in.nextDouble();
inputs[0] = credits ;
int currentSize = 1;
The problem might be in this line : inputs[currentSize] = in.nextDouble();
You are storing the first value in credits but not assigning it to inputs array.
Related
I am suppose to ask the user for how many integers they want to enter, and then use a loop to create a prompt message for each integer, so that the numbers can be entered. Each integer that is entered is stored in an array.
However, every time I run the code, an error appears. The code doesn't repeat during the loop, and it looks like this:
Please enter the number of values you would like to enter:
1
Please enter for index value of 0:
-Error-
I can't figure out why the loop and array aren't working, thank you!
```public static void main(String[] args) {
//create and label variables
int intCount, n, x;
//create a scanner that will accept the user's input and figure out how many
numbers the user wants to enter
Scanner Inputnumber = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to
enter:");
n = Inputnumber.nextInt();
Inputnumber.close();
//create a integer array to store the numbers
int [] integers;
integers = new int [n];
//create a while loop to continuously ask the user for what numbers they
want to enter
for (intCount = 0; intCount < n; intCount++){
Scanner InputInt = new Scanner(System.in);
System.out.println("Please enter for index value of "+intCount+": ");
x = InputInt.nextInt();
integers [intCount] = x;
InputInt.close();
}```
Refer this
You don't need to use two separate Scanner Objects.
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
// create and label variables
int intCount, n, x;
// create a scanner that will accept the user's input and figure out how many
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to enter:");
n = input.nextInt();
// create a integer array to store the numbers
int[] integers;
integers = new int[n];
// create a while loop to continuously ask the user for what numbers they
for (intCount = 0; intCount < n; intCount++) {
System.out.println("Please enter for index value of " + intCount + ": ");
x = input.nextInt();
integers[intCount] = x;
}
input.close();
}
}
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 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);
...
else if(choice == 3) {
ArrayList<Integer> shares = new ArrayList<Integer>();
System.out.print("Type in quantity: ");
int quantity = Integer.parseInt(reader.nextLine());
System.out.println("Enter total quantity either as a single number or many numbers by pressing enter after each: ");
while (reader.hasNextInt()) {
int share = reader.nextInt();
shares.add(share);
}
System.out.println("Enter total price: ");
Scanner reader1 = new Scanner(System.in);
double price = Double.parseDouble(reader1.nextLine());
int sum = 0;
System.out.println((price*quantity)/sum);
for(Integer d : shares){
sum += d;
return;
}
Here I am trying to calculate a single value out of 3 value (price*quantity)/sum this is the main formula but sum value is calculated by first entering a series of integers which are then summed and used in the main formula.
The problems:
I can not make the While loop to stop when user enters Null value, I only managed to make it stop when user enters a letter instead of a number
Currently when i run this program I get a result Infinity why ?
Because you are checking reader.hasNextInt(), which returns false for non integer input only.
If you want to take input until end of file, you can do this way:
String input = null;
while(!(input = sc.nextLine()).isEmpty()) {
int share = Integer.parseInt(input);
shares.add(share);
}
You are getting Infinity since you are dividing by sum whose value is zero.
I think you might be trying to do this:
int sum = 0;
for(Integer d : shares){
sum += d;
}
System.out.println((price*quantity)/sum);
Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}