I'm trying to ask user to type how many numbers will be inputted and enter the values then add all the values.
import java.util.Scanner;
public class sum {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
int counter = 1;
int values = 0;
int times;
System.out.println("How many numbers will you input?: ");
times = sc.nextInt();
while(counter == times){
System.out.println("Enter your number: ");
values = values + sc.nextInt();
counter ++;
}
System.out.println("Your sum is " + values);
}
}
Your logic for the while loop is incorrect.
while(counter == times)
will only be true if counter and times have the same value. So if you would want to input two numbers, your while loop wouldn't even get executed. What you want is for the while loop to run until counter == times. So, your logic should be
while(counter != times)
Furthermore, you should start your counter at zero, instead of one. This is because it now means that you already inputted one number, which you didn't.
Alternatively, you could use the following snippet
while (sc.hasNextInt()) {
values += sc.nextInt()
}
This simple loop will go through all the integers inputted in the command line one by one, until there is no next integer (you type for example a letter).
In that case, you don't need to ask the user how many numbers he/she will input, as you will check it yourself.
Related
I was given the task of splitting my program which which allows the user to enter an array of numbers and after an odd number between 1 and 10 to check whether the odd number is a factor of each of the 5 numbers in the array. I keep on trying out different ways but none seem to work. Could someone help me out or send a sample of how I should sort it? This is the program:
import java.util.Scanner;
public class CheckboxExample{
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = new int[10];
System.out.println ("Please enter 10 random numbers"); // prompts the user to enter 10 numbers
int num; // declares variable num
try{
for (int i = 0; i < 10; i++) {
array[i] = s.nextInt(); // array declaration
}
}catch (Exception e){
System.out.println ("You have an error");
}
System.out.println ("Please enter an odd number between 1 and 10");
try{
num = s.nextInt ();
if (num % 2 == 0){
do{
System.out.println ("\nYour number is even, enter an odd one");
num = s.nextInt ();
}while (num % 2 == 0);
}
if (num < 0 | num > 10){
do{
System.out.println ("Your number is outside of the range, try again");
num = s.nextInt ();
}while (num < 0 | num > 10);
}
for (int i = 0; i < 5 ; i++){
if (array[i] % num == 0) {
System.out.println("Your number is a factor of " + array[i] );
}
}
}catch (Exception e){
System.out.println ("error");
}
}
}
A method should ideally be responsible for one task. In your case you should think about the different things your code try to do and organize them in a sense that each of the methods you call does one thing of the list of things you try to do.
As an example: As far as I understand your code does the following things:
Read an array of 10 values
Read an odd number
Verify the number is odd
Verify the number is in range
Calculate if the number is a factor of one of the 10 numbers in the array
Now one possible approach would be to separate your code in 5 methods that do exactly these things.
At first you call the method that reads the 10 numbers.
Then you call the method to read the odd number.
3. and 4. are actually part of reading the number, since you need to retry on an invalid input, so you could write your method for inputting the odd number in a way that it uses the methods for verifying the input.
Finally when you have all the valid input, you call the method which produces your result (ie. if the number is a factor of the numbers in the list).
A general outlier for your code could look like:
public class CheckboxExample {
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = readInputArray();
int number = readOddValue();
calculateFactors(array, number);
}
private int[] readInputArray() {...}
private int readOddValue() {...}
private void calculateFactors(int[] array, int number) {...}
//additional methods used by readOddValue which verify if the value is actually odd
}
Please note that this is just one way to split your code into methods and there are several ways to design and implement each of these methods.
I did look at the threads pertaining to randoms and implemented them into this assignment but I have 2 questions.
1) I need my program to generate random numbers (and print them) and count the iterations. I have counting the iterations down but I don't know why the random numbers don't print out. Does it have something to do with my guess = 0? Here's an example if I'm not clear.
Example:
Enter a number: 13
85
89
73
94
13
This took 5 tries
2) I have no clue why my program always ends up stuck at one number for the answer. The program immediately ends after entering the number 86.
import java.util.*;
public class FeelingLucky {
public static void main (String [] args) {
Scanner sc = new Scanner (System.in);
int tries = 0;
int guess = 0;
Random random = new Random(1);
int num = random.nextInt(100) + 1;
System.out.print("Pick a number between 1 and 100:");
while (guess != num) {
guess = sc.nextInt();
tries++;
}
System.out.println("It took " + tries + " tries to match");
sc.close();
}
}
Random(1) uses seed in constructor which is always the same. Use just Random() - no parameter constructor.
import java.util.*;
public class FeelingLucky {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tries = 0;
int guess = 0;
Random random = new Random(); // No seed
int num = random.nextInt(100) + 1;
System.out.print("Pick a number between 1 and 100:");
while (guess != num) {
guess = sc.nextInt();
tries++;
}
System.out.println("It took " + tries + " tries to match");
sc.close();
}
}
See Java random always returns the same number when I set the seed?
You've called nextInt() on the Random object only once, so you've only generated the one random number. Inside your loop you call nextInt() on the scanner, which is reading from System.in, so your program is halting and waiting for the user to input a number again each time around the loop.
If you want the user to enter a single number once, and then Random to keep generating numbers until they match, you'd need to swap which one is called inside the loop. To print the random numbers being generated, you'd need to add a print statement inside the loop that prints that current number.
while (guess != num) {
num = random.nextInt(100) + 1;
guess = sc.nextInt();
System.out.printf("you guessed: %d the number was %d%n",guess, num);
tries++;
}
This one will print out each time, and guess a new random number each time.
I am trying to have an output where the entered numbers in the loop are all printed out as separate numbers. Example: Entered numbers: 10, 15, 1, 25.
Here is my code:
import java.util.Scanner;
public class SumofNumbersAbove0 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
int input;
for (input = 0; input >= 0;) {
number = number + input;
System.out.print("Enter number: ");
input = scan.nextInt();
}
System.out.println("Entered Number: " + input);
System.out.println("The sum: " + number);
}
}
I get the sum of all the numbers correctly. But all I get for entered numbers is the final one.
Move your print of input into the loop where each value of input is actually present. Where you have it you only get the last input
for (input = 0; input >= 0;) {
number = number + input;
System.out.print("Enter number: ");
System.out.println("Entered Number: " + input);
input = scan.nextInt();
}
System.out.println("The sum: " + number);
Issue:
In your code the two variables you have input and number (which should rather be named sum) are solving very different purpose. input is acting a transient pedestrial where the user-entered values come and land. From there the value is added into number and then come another user-entered value which lands onto the same pedestrial thereby knocking-off the previous value.
Thus when you print input at the bottom of your code, the value you find is the one which came last to the pedestrial (which in your case is some integer < 0)
Solution: What you want is to perform an operation (print) on each of the input values. You can do either of the following-
Perform the operation before losing the value. I mean print the value in the loop itself. Adding the value to number is another operation you are already doing before losing the value
Persist all the input values. Here you need to have some bigger pedestrial which can accomodate all the incoming user-entered value without knocking-off previous values. Once you have all the them you can revisit the values and operate on them. printing them could be one operation and accumulating their values in another variable number could be another.
Hope that helps
I am having difficulties with finding all possible odd numbers for my program. I am required to use a while loop to find all the odd numbers but i am not sure how to print it out. I dont know if im doing anything wrong in this block while((num1+num2)%2==0) because that was just a guess. Outline of the program is to get the user to enter 2 numbers that is an even multiple of the other number. I am not sure how that part either. After finding 2 numbers that is an even multiple of the other number, i am supposed to display all the odd numbers between the two numbers. Thanks alot in advance.
import java.util.Scanner; //imports the java utillity scanner
public class MyPrompter{
public static void main(String[] args){
System.out.println("Odd number display");
Scanner input = new Scanner(System.in); //scans for user input and stores in "input"
int num1,num2; //declares the variables i need for the pgrm
try{ //try statement to check for user input errors
System.out.println("Please enter your first number: ");
num1 = input.nextInt(); //stores input for the first number
System.out.println("Please enter your second number: ");
num2 = input.nextInt(); //stores input for the second number
while((num1+num2)%2==0){ //while loop to find all the odd numbers between the 2 numbers
System.out.println();
}
}
catch(java.util.InputMismatchException e){ //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid ROUNDED NUMBER!");
}
}
}
How about something like this:
int num1 = 10;
int num2 = 50;
int current = num1;
while (current < num2) {
if (current % 2 != 0) {
System.out.println(current);
}
current++;
}
Set current to equal num1, continue the loop while current is less than num2. For each iteration check if current is odd and output it if it is. Increment current by one.
User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}