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..
Related
How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!
import java.util.Scanner;
public class LuhnAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine();
int i = 0;
char chk = nums.charAt(15);
while(!nums .equals("") ) {
if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
}
int sum = 0;
for( i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if ( i % 2 == 0 ) {
num = num * 2;
if ( num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if ( sum2 == chk2) {
System.out.println("Number is valid.");
}
else {
System.out.println("Number is not valid. ");
}
System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
nums = input.nextLine();
}
System.out.println("Goodbye!");
input.close();
}
}
You can include your code that you only want done if the length ==16 in an if statement.
Meaning, instead of:
if (nums.length != 16) {
//code if there is an error
}
//code if there is no error
you can do:
if (nums.length == 16) {
//code if there is no error
} else {
//code if there is an error
}
(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine().trim();
if (nums.length() == 0) {
break; //exits while loop
}
if (nums.length() != 16) { //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
continue; //goes back to the beginning right away
}
//still here, process the number
char chk = nums.charAt(15);
int sum = 0;
for (int i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if (i % 2 == 0) {
num = num * 2;
if (num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if (sum2 == chk2) {
System.out.println("Number is valid.");
} else {
System.out.println("Number is not valid. ");
}
}
System.out.println("Goodbye!");
input.close();
}
}
The program needs to ask the user how many courses it took which is the number of elements in the array. Then it needs to identify which grades are below 65 and print those and then identify which grades are above 90 and print those. Right now, the output just prints 0,1,2,3,4,5 after asking the user for how many courses they took and their grade in each of the course.
import java.util.Scanner;
import java.util.ArrayList;
public class StudentApplication {
public static void main(String[] args) {
Scanner Number = new Scanner(System.in);
System.out.print("How many courses did you take during the school year: ");
int x= Number.nextInt();
int grades[] = new int[x];
for (int courses =1; courses<=x; courses++) {
System.out.print("Enter your grade for that course: ");
Number.nextInt();
int y = Number.nextInt();
}
for (int counter = 0; counter < grades.length; counter++) {
if (counter < 65) {
System.out.print(counter);
}
if (counter >90) {
System.out.print("\n"+counter);
}
}
}
}
Is this what u want?
Scanner sc = new Scanner(System.in);
System.out.print("How many courses did you take during the school year? : ");
int takeCoursesNum = sc.nextInt();
int grades[] = new int[takeCoursesNum]; // array number start "0" ~ ex) { [0], [1], [2] }
for (int i = 0; i < takeCoursesNum; i++) {
System.out.print("Enter your grade for that course : ");
int grade = sc.nextInt();
grades[i] = grade;
}
for (int i = 0; i < takeCoursesNum; i++) {
if (grades[i] < 65) {
System.out.println("below 65 : " + i);// System.out.println : auto change line. no need \n.
}
if (grades[i] > 90) {
System.out.println("above 90 : " + i);
}
}
I hope it is. Happy Codinging :)
Trying to make a program that uses a partially filled array. The beginning of the code deals with getting user input for the array size and getting them to enter a value to be placed in the array. Then I want the values to be sorted as they are entered.
public static void main(String[] args)
{
int userInput;
int[] userArray;
int numElements;
int index;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of values in array (5 to 10): ");
userInput = keyboard.nextInt();
while (userInput < 5 || userInput > 10)
{
System.out.print("Enter number of values in array (5 to 10): ");
userInput = keyboard.nextInt();
}
System.out.println(); //Space, for neatness
userArray = new int[userInput];
for (int item: userArray)
System.out.print(item + " ");
System.out.print("\nEnter an integer value: ");
userInput = keyboard.nextInt();
int numElements = 0;
int index = 0;
if (numElements == userArray.length - 1)
System.out.println("The array is full.");
else
{
while (index < numElements && userArray[index] < userInput)
{
if (userArray[index] != 0) //Shift the array to the right, and add value at the current index as to not overwrite values.
{
for (int i = numElements; i > index; i--)
userArray[i] = userArray[i - 1];
userArray[index] = userInput;
}
userArray[index] = userInput;
index++;
numElements++;
System.out.print("Updated array: ");
for (int item: userArray)
System.out.print(item + " ");
System.out.println("\nEnter an integer value: ");
userInput = keyboard.nextInt();
}
}
}
Having trouble with my output. After I enter a value, the program terminates. For example (I print the empty array on purpose):
Enter number of values in array (5 to 10): 5
0 0 0 0 0
Enter an integer value: 5
Sorry for the lack of comments.
This part of your statement is always FALSE!
index < numElements
index and numElements are both 0 initially. Thus your while loop just skips and is done.
try replacing the last part of your code by this :
int numElements = 0;
while (numElements < userArray.length ) {
System.out.print("\nEnter an integer value: ");
userInput = keyboard.nextInt();
//insert into the first column
userArray[0] = userInput;
// order the table
for (int i=0 ;i<=(userArray.length-2);i++)
for (int j=(userArray.length-1);i < j;j--)
if (userArray[j] < userArray[j-1])
{
int x=userArray[j-1];
userArray[j-1]=userArray[j];
userArray[j]=x;
}
numElements++;
}
System.out.print("Updated array: ");
for (int item: userArray)
System.out.print(item + " ");
System.out.println("\nEnter an integer value: ");
userInput = keyboard.nextInt();
System.out.println("The array is full.");
I'm a beginner Java programmer writing a program that calculates the average of a set of positive integers. First, it queries the user for the amount of integers to be entered. Then, it collects the integers from the user and outputs the calculated average. I'm having trouble handling the exceptions. When the user tries to enter a negative number to be averaged, the exception is correctly displayed, but it doesn't correctly continue the for-loop to collect the appropriate amount of numbers. For example, below is an example output:
Please enter the number of integers to be averaged: 5
Enter a number: 1
Enter a number: 2
Enter a number: -3
NegativeIntegerException: N must be a positive integer.
Enter a number: 3
Enter a number: 4
The average is: 0.0
It correctly threw the exception, but didn't continue to fill the 5 integers. Only the other 4 that were valid.
Below is the code:
import java.util.*;
class NegativeIntegerException extends Exception {
public NegativeIntegerException()
{
super("N must be a positive integer.");
}
}
public class intAverage {
public static void main(String[] args)
{
int N = 0; //number of integers to be averaged
int[] numbers = null; //array to hold integers
int sum = 0;
int newInt;
double average;
Scanner keyboard = new Scanner(System.in);
int x = 1; //for do-while loop #1
int z = 1; //for do-while loop #2
do {
try {
System.out.print("Please enter the number of integers to be averaged: ");
N = keyboard.nextInt();
numbers = new int[N]; //setting size of array
x = 2;
}
catch (Exception e) {
System.out.println("N must be a positive integer");
}
} while (x == 1);
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
try {
throw new NegativeIntegerException();
}
catch(NegativeIntegerException e) {
System.out.println(e);
}
}
newInt = numbers[i];
}
z = 2;
} while (z == 1);
for(int y = 0; y < N; y++) //calculate average
{
sum = sum + numbers[y];
}
average = sum / N;
System.out.println("The average is: " + average);
}
}
When you print out the exception, subtract 1 from i, and continue. This will basically restart the iteration.
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
try {
throw new NegativeIntegerException();
}
catch(NegativeIntegerException e) {
System.out.println(e);
// Ignore this input
i--;
continue;
}
}
numbers[i] = newInt;
}
z = 2;
} while (z == 1);
Note that you don't need to throw an exception for this to work - you could just as easily say:
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
System.out.println("NegativeIntegerException: N must be a positive integer");
// Ignore this input
i--;
continue;
}
numbers[i] = newInt;
}
z = 2;
} while (z == 1);
This is more readable, too.
I have this code:
import java.util.Scanner;
public class PositiveNegative { public static void main(String[] args) {
int numbers, plus = 0, minus = 0;
int count = 0;
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while(numbers != 0)
{
total += numbers;
if(numbers > 0)
plus++;
if(numbers < 0)
minus++;
}
System.out.println("The number of positives is: " +plus);
System.out.println("The number of negatives is: " +minus);
System.out.println("The number of total is: " +total);
}
}
The problem with is that I try to run it and type the numbers but it does nothing. I want it so that when you type 0 it stops taking numbers and starts processing the code. What should I do?
Try this:
import java.util.Scanner;
public class PositiveNegative {
public static void main(String[] args) {
int numbers = 0, plus = 0, minus = 0;
double total = 0;
do{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = Integer.valueOf(scan.nextLine());
total += numbers;
if (numbers > 0)
plus++;
if (numbers < 0)
minus++;
}
while (numbers != 0);
System.out.println("The number of positives is: " + plus);
System.out.println("The number of negatives is: " + minus);
System.out.println("The number of total is: " + total);
}
}
Put your Scanner in the while loop so that everytime loop start it will ask for User input.
You need to update numbers or your loop will run for ever. And I recommend using braces (and an else). Something like,
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while (numbers != 0) {
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
}
Alternatively, you could use a do-while loop. Then you only need one copy of the prompt. Like,
do {
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
} while (numbers != 0);
You have to modify numbers each time to make it work in your while.
So, in your existing code, just comment out numbers = scan.nextInt(); and use below--
// numbers = scan.nextInt(); //comment out this call
while ((numbers = scan.nextInt()) != 0) {
....
this will give you desired output--
Enter an integer (0 to quit): 9
4
-9
1
0
The number of positives is: 3
The number of negatives is: 1
The number of total is: 5.0