I want to scan 20 integers from the user. Once the user enters a negative value, the scan stops.
After that, how can I add the positive values that the user entered into an array?
System.out.println("\nEnter up to 20 non-negative numbers:");
for(i = 0; i <= list20.length; i++) {
System.out.print("Number " + (i+1) + ": ");
input = scan.nextInt();
if(input > 0) {
input = input.list20[i] // How to add positive integer here??
}
else
break;
}
// first, zero out the array using whatever method you want
for(i = 0; i < list20.length; i++)
{
list20[i] = 0;
}
// then request the values
System.out.println("\nEnter up to 20 non-negative numbers:");
for(i = 0; i < list20.length; i++)
{
System.out.print("Number "+ (i+1) + ": ");
input = scan.nextInt();
if(input>=0)
{
list20[i] = input;
}
else
{
break;
}
}
// then total the non-negative values
int total = 0;
if(i >= 20) {
for(int value : list20)
{
if(value > 0) {
total += value;
}
}
}
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();
}
}
I have an issue. My lecturer wants me to make a loop, with an input of JOptionPane and an output of console. How can I use loop for JOptionPane and send an output through console.
Here's my code:
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
String a1 = JOptionPane.showInputDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++){
int a = Integer.parseInt(a1);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
I would try using a DO-WHILE loop with and an int[], example:
int size = 10;
int count = 0;
int[] yourNumbers = new int[size];
do {
yourNumbers[count] = Integer.parseInt(JOptionPane.showInputDialog(null,
"Your message here."));
count++;
} while (count < 10);
This way you can loop through and grab all the numbers. Then you can use a FOR-LOOP to cycle through and print what you need
System.out.println("Even Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 == 0) {
System.out.println(yourNumbers[i]);
}
}
System.out.println("Odd Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 != 0) {
System.out.println(yourNumbers[i]);
}
}
The problem with your current code is that you only ask the user one time to input a number but you actually seem to want 10 values. So you parse ten times the same value.
The solution is simple, put the dialog inside the loop (only changed the lines with comments):
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
// No return type, just a message
JOptionPane.showMessageDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++) {
// Dialog inside the loop, asking to
// input a number in every iteration
String value = JOptionPane.showInputDialog(null, "Type in "
+ (counter + 1) + ". value");
int a = Integer.parseInt(value);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
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.
This method allows the user to input the rainfall for every month of the year. I'm trying to prevent data less than zero from being stored in the array. I'm using a do-while loop, but I can't seem to figure out how to check if the input is less than zero. Thanks for your help guys, cheers!
public static double[] getRainFall()
{
double[] rainfallMonths = new double[12];
double[] rainfall = new double[12];
do
{
for(int x = 0; x < rainfallMonths.length; x++)
{
System.out.print("What is the rainfall for month #" + (x + 1) + ": ");
rainfallMonths[x] = keyboard.nextDouble();
rainfall[x] = rainfallMonths[x];
if(rainfallMonths < 0)
{
System.out.println("Input is Invalid");
}
}
}while(rainfallMonths < 0);
for(int count = 0; count < rainfallMonths.length; count++)
{
System.out.println("Rainfall Month #" + (count + 1) + ": " + rainfall[count]);
}
return rainfall;
}
Your logic is a little off, not to mention that you're trying to compare an array to an int...
First, the logic...
do
for x = 0 to rainfallMonths.length -1 do
... get input...
while value < 0
The problem here is, you've already assigned the input to all the elements of the array in the for-next loop, but then you are trying to validate the value that was input outside of the for-next which is likely never to return a valid result...and it's too late...
Instead, you want to reverse the logic...
for x = 0 to rainfallMonths.length -1 do
do
value = get input from user
while value < 0
rainfallMonths[x] = value
Next, rainfallMonths is a reference to an array, this isn't actually what you want to be checking against, you need to be checking against one it's values or elements, for example...
while (rainfallMonths[x] < 0);
And if none of that made sense...
public static double[] getRainFall()
{
double[] rainfallMonths = new double[12];
double[] rainfall = new double[12];
for(int x = 0; x < rainfallMonths.length; x++)
{
double input = 0;
System.out.print("What is the rainfall for month #" + (x + 1) + ": ");
do {
rainfallMonths[x] = keyboard.nextDouble();
rainfall[x] = rainfallMonths[x];
if(input < 0)
{
System.out.println("Input is Invalid");
}
} while (rainfallMonths[x] < 0);
}
for(int count = 0; count < rainfallMonths.length; count++)
{
System.out.println("Rainfall Month #" + (count + 1) + ": " + rainfall[count]);
}
return rainfall;
}
You might want to take a refresher on Arrays which should help ;)
double temp = -1;
for(int x = 0; x < rainfallMonths.length; x++)
{
System.out.print("What is the rainfall for month #" + (x + 1) + ": ");
temp = keyboard.nextDouble();
if(temp < 0)
{
System.out.println("Input is Invalid");
x--; //if you want the user to maybe try to repeat this month again?
}
else
{
rainfallMonths[x] = keyboard.nextDouble();
rainfall[x] = rainfallMonths[x];
}
}
I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.
public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("enter integers between 1 and 100: ");
int[] num = new int[100];
int data = input.nextInt();
while ((data = input.nextInt()) != 0) {
num[data]++;
}
for (int i = 1; i < 100; ++i) {
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
}
You need two separate loops: the first to gather the information, and the second to print the results:
int data = 0;
while ((data = input.nextInt()) != 0)
{
num[data]++;
}
for (int i = 0; i < 100; ++i)
{
if (num[i] != 0) { /* print num[i] */ }
}
Just loop over the num array after your while loop to print the counts.
for (int index = 0; index < num.length; index++) {
if (num[index] != 0)
System.out.println(data + " occurs " + num[data] + " time(s).");
}
You are printing an output every time an integer is read. Your program is behaving as expected.
To get what you want, you need to scan all the input before you produce any output.
Try this instead:
while (data != 0){
data = input.nextInt();
num[data]++;
}
for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.
while (input.hasNextInt()){
num[input.nextInt()]++;
}
it's so simple
int data = 0;
int[] num = new int[100];
int i = 0;
while (i < num.length) {
if ((data = input.nextInt()) == 0)
break;
num[i] = data;
i++;
}
for (i = 0; i < 100; ++i) {
int times = 0;
if (num[i] != 0) {
for (int j = 0; j < 100; j++) {
if (num[j] == 0) {
break;
} else if (num[i] == num[j]) {
times++;
}
}
System.out.println(num[i] + " occurs " + times + " times ");
} else {
break;
}
}