product of inputted numbers - java

new here and in java world and I am a student. I just keep getting a wrong product for this question.
Write a Java application that asks the user to input an integer between 1 and 9
inclusive, 10 times, and then prints their product. Your program should use a for loop.
When an integer less than 1 or larger than 9 is input, your application should disregard
it.
You should NOT use logical AND or logical OR operators.
here is what I have done so far:
import java.util.Scanner;
public class newtest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter;
int product = 1;
int number;
System.out.print("Enter number 1-9: ");
number = input.nextInt();
for (counter=1; counter<=10; counter++){
System.out.print("Enter number 1-9: ");
number = input.nextInt();
if (number<10){
if (number>0) product*=number;
else System.out.println ("number is disregarded");
}
else System.out.println ("number is disregarded");
}
product *= number;
System.out.println (product);
}
}

if (number<10){
if (number>0) product*=number;
else System.out.println ("number is disregarded");}
else System.out.println ("number is disregarded");
} product *= number;
System.out.println (product);
Your problem is here, remove the product *= number; that follows the outer if block.

Related

how do i implement user input in loop in the following code?

this is guess number programme using constructor but the issue which I am facing
is not able to express user input in loop.I tried to look for it but not good explanation.
import java.util.Scanner;
import java.lang.Math;
class guessnumber{
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public String userinput(int repeats,int rand){
String e;
e="that's it";
if(repeats<rand){
String z="choose higher number";
System.out.println(z);
}
else if (repeats>rand){
String z="choose lower number";
System.out.println(z);
}
return e;
}
public String iscorrect(){
String correct="correct number";
return correct;
}
}
public class guessthenumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
guessnumber gun = new guessnumber();
System.out.println("enter number ");
int number = sc.nextInt();
System.out.println("enter max and min number");
int min = sc.nextInt();
int max = sc.nextInt();
int o=gun.getRandomNumber(min,max);
System.out.println(o);
if (number < o || number > o) {
System.out.println(gun.userinput(number, o));}
else if(number==o){
String correct= gun.iscorrect();
System.out.println(correct);
}
}
}
I want to user to keep entering data till correct number is hit
Here's a solution that behaves like you're describing, and how your code currently behaves:
ask for a few numbers up front (minimum, maximum)
determine a random "target" number for the user to guess
ask the user to guess – if they're correct, show a message; if they're incorrect, ask for another guess
repeat until their guess is correct
A few things I did:
introduce a "getNumber()" helper that will make sure the numbers make sense – put some guardrails around what a user can enter to minimize unexpected results if user enters unexpected input
use a "while" loop, go forever – while (true)
if their guess matches the target, use break to stop the loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimum = getNumber(scanner, 0, "minimum");
int maximum = getNumber(scanner, minimum + 1, "maximum");
int target = (int) ((Math.random() * (maximum - minimum)) + minimum);
while (true) {
System.out.print("enter a guess: ");
int guess = scanner.nextInt();
if (guess == target) {
System.out.println("correct guess! the number was " + target);
break;
} else {
System.out.print("nope, please try again.. ");
}
}
}
static int getNumber(Scanner scanner, int minimumAllowed, String numberType) {
while (true) {
System.out.print("enter " + numberType + " number: ");
int minimum = scanner.nextInt();
if (minimum >= minimumAllowed) {
return minimum;
} else {
System.out.println("too small, must be at least " + minimumAllowed);
}
}
}
Here's a sample run:
enter minimum number: 1
enter maximum number: -3
too small, must be at least 2
enter maximum number: 5
enter a guess: 1
nope, please try again.. enter a guess: 2
nope, please try again.. enter a guess: 3
nope, please try again.. enter a guess: 4
correct guess! the number was 4
You can use while and break statements

Storing multiple values inside a while loop - Java

I'm trying to store the sum of 2 numbers inside a while loop so that once the loop ends multiple sums can be added up and given as a total sum, however I am rather new to Java and am not sure how to go about doing this.
I'm trying to use an array but I'm not sure if it is the correct thing to use. Any help would be greatly appreciated.
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
Int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[0]=AddedNum;
TotalNum[1]=;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
System.out.println("The total sum of all the numbers you entered is " + TotalNum);
}
}
There is a data container called ArrayList<>. It is dynamic and you can add as many sums as you need.
Your example could be implemented like this:
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> listOfSums = new ArrayList<>();
int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
listOfSums.add(AddedNum);
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
// Then you have to calculate the total sum at the end
int totalSum = 0;
for (int i = 0; i < listOfSums.size(); i++)
{
totalSum = totalSum + listOfSums.get(0);
}
System.out.println("The total sum of all the numbers you entered is " + totalSum);
}
}
From what I see, you come from a background of C# (Since I see capital letter naming on all variables). Try to follow the java standards with naming and all, it will help you integrate into the community and make your code more comprehensible for Java devs.
There are several ways to implement what you want, I tried to explain the easiest.
To learn more about ArrayList check this small tutorial.
Good luck!
Solution with array:
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
int Num1, Num2, AddedNum;
String answer;
int count = 0;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[count]=AddedNum;
count++;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
int TotalSum = 0;
for(int i = 0; i <count; i++ ) {
TotalSum += TotalNum[i];
}
System.out.println("The total sum of all the numbers you entered is " + TotalSum);
}
}
This solution is not dynamic. There is risk that length of array defined on beginning will not be enough large.

Is there a way to have a System.out.print print something different once in a loop?

I'm very new to coding, and one of my projects was to create a program that uses a while loop to ask a user for test grades and find the average. The problem I have is that when it asks for the first grade, my instructor wants it to also print out "Enter -1 when you're finished" along with the first grade only. He wants the results to look something like this.
Test grade1? (Enter -1 when you are finished): random grade
Test grade2? random grade
Test Grade3? random grade
The average of your test grades is: average of all grades
Currently, I have the first grade as a separate line of code that asks the user and it is not in the loop. Is there any way to combine it into the loop and still have it to ask "Enter -1 when you're finished" but for only the first test grade?
P.s Sorry if my code is very messy I'm still not very good at it.
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Test grade 1? (Enter -1 when you're finished): ");
int grade1 = scan.nextInt();
int i = 2;
int testCounter = 1;
int sum = 0;
boolean flag = true;
while(flag) {
System.out.print("Test grade " + i + "? ");
int grades = scan.nextInt();
if (grades == -1){
flag = false;
break;
}
sum = grade1 + grades;
grade1 = sum;
i++;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double)sum/testCounter);
}
}
You can just check with an if statement whether it's the first test and display the additional message if that's the case.
Also you can get rid of the i variable and use testCounter in it's place. You also don't need the flag, just using break is enough.
At the end of the loop the testCounter will be off by one so you have to decrement by one when calculating the average ((testCounter - 1)).
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCounter = 1;
int sum = 0;
while (true) {
System.out.print("Test grade " + testCounter + "? ");
if (testCounter == 1)
System.out.print("(Enter -1 when you're finished): ");
int grade = scan.nextInt();
if (grade == -1) {
break;
}
sum += grade;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double) sum / (testCounter - 1));
}
}

Build a java app that asks the user to input a series of grades between 0-100

Im extremely new at Java programming and my professor asked us to write a program that can:
Show each grade by the letter. (Ex: A, B, C, D, F)
Show the Minimum & Average grade of the class
Show the number of people who passed the exam (70+ is passing)
I have been trying to use arrays and if else statements to solve this but Im not making much progress. Can you guys please help me out?
I know I'm not good at coding, but here is something I am trying.
I also would like to incorporate if else statements in my code to make things simpler.
Thank you so much in advance.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String[] args)
{
double[] grades = new double[10];
int sum
Scanner scan = new Scanner (System.in);
System.out.println ("Number of students: " + grades.length);
for (int index = 0; index < grades.length; index++)
{
System.out.print ("Enter number " + (index+1) + ": ");
grades[index] = scan.nextDouble();
}
}
}
Finding the minimum value is done by using a for loop just like your current one and using:
min = Math.min(min, grades[index]);
The average can be found just by finding the sum inside the loop:
sum += grades[index];
And then divide by the number of values.
The number of grades 70+ can be found with an if statement inside the loop:
if (grades[index] >= 70) {
numPassing++;
}
Each of these operations can also be done using DoubleStream from Java 8:
double min = Arrays.stream(grades).min().orElse(0.0);
double avg = Arrays.stream(grades).average().orElse(0.0);
long numPassing = Arrays.stream(grades).filter(grade -> grade >= 70).count();
Okay I modified the code a bit, plus I didn't used any functionalities provided in java so that you can understand the flow control and logic as being a newbie to java.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String[] args)
{
double[] marks = new double[10];
char[] grades=new char[10];
int[] numGradeStudent={0,0,0,0,0};
int min=0,avg=0,minIndex=0;
Scanner scan = new Scanner (System.in);
System.out.println ("Number of students: " + grades.length);
for (int index = 0; index < grades.length; index++)
{
//Taking marks then applying grades and counting no. of students
System.out.print ("Enter number " + (index+1) + ": ");
marks[index] = scan.nextDouble();
if(marks[index]>90)
grades[index]='A';
if(marks[index]>75 && marks[index]<=90)
grades[index]='B';
if(marks[index]>65 && marks[index]<=75)
grades[index]='C';
if(marks[index]>55 && marks[index]<=64)
grades[index]='D';
else
grades[index]='E';
//Setting up graded students down from here
if(grades[index]=='A')
numGradeStudent[0]++;
if(grades[index]=='B')
numGradeStudent[1]++;
if(grades[index]=='C')
numGradeStudent[2]++;
if(grades[index]=='D')
numGradeStudent[3]++;
if(grades[index]=='E')
numGradeStudent[4]++;
}
min=numGradeStudent[0];
for(int i=0;i<5;i++){
if(numGradeStudent[i]<min){
min=numGradeStudent[i];
minIndex=i;
}
}
System.out.println("Min grade of class is:"+ grades[minIndex]);
for(int i=0;i<10;i++){
if(marks[i]>70)
System.out.println("Student "+(i+1)+" passed.");
}
}
}

Using the while loop to ask user their input in JAVA

I have like 3 hours trying to solve this simple problem. Here is what I am trying to accomplished: Ask the user to enter a number, and then add those numbers. If the users enters five numbers, then I should add five numbers.
Any help will be appreciated.
import java.util.Scanner;
public class loopingnumbersusingwhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input;
System.out.println("How Many Numbers You Want To Enter");
total = kb.nextInt();
while(input <= kb.nextInt())
{
input++;
System.out.println("How Many Numbers You Want To Enter" + input);
int input = kb.nextInt();
}
}
}
Your current code is trying to use input for too many purposes: The current number entered, the amount of numbers of entered, and is also trying to use total as both the sum of all numbers entered and the amount of numbers to be entered.
You'll want 4 separate variables to track these 4 separate values: how many numbers the user will entered, how many they entered so far, the current number they entered, and the total.
int total = 0; // The sum of all the numbers
System.out.println("How Many Numbers You Want To Enter");
int count = kb.nextInt(); // The amount of numbers that will be entered
for(int entered = 0; entered < count; total++)
{
int input = kb.nextInt(); // the current number inputted
total += input; // add that number to the sum
}
System.out.println("Total: " + total); // print out the sum
Add this code after you take how many numbers the user wants to add:
int total;
for(int i = 0; i < input; i--)
{
System.out.println("Type number: " + i);
int input = kb.nextInt();
total += input;
}
To print this just say:
System.out.println(total);
import java.util.Scanner;
public class LoopingNumbersUsingWhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input=0;
int total = 0;
System.out.println("How Many Numbers You Want To Enter");
int totalNumberOfInputs = kb.nextInt();
while(input < totalNumberOfInputs)
{
input++;
total += kb.nextInt();
}
System.out.println("Total: " +total);
}
}
You seem to be asking how many numbers twice.
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter");
int howMany = kb.nextInt();
int total = 0;
for (int i=1; i<=howMany; i++) {
System.out.println("Enter a number:");
total += kb.nextInt();
}
System.out.println("And the grand total is "+total);
}
What you should pay attention to:
name classes in CamelCase starting with a big letter
initialize total
don't initialize input twice
show an appropriate operand input request to your user
take care of your loop condition
don't use one variable for different purposes
which variable should hold your result?
how to do the actual calculation
Possible solution:
import java.util.Scanner;
public class LoopingNumbersUsingWhile {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter: ");
int total = kb.nextInt();
int input = 0;
int sum = 0;
while (input < total) {
input++;
System.out.println("Enter " + input + ". Operand: ");
sum += kb.nextInt();
}
System.out.println("The sum is " + sum + ".");
}
}

Categories