I wrote a code which calculates grades. But if I'm typing 9999 in the console, then the program should break without any output. How can I do this and which loop should I use? I tried it with a while loop but the program gives me still output.. this is my code with the while loop which doesn't work as it should. The Programm works except for the while loop. How can I do write this better?
import java.util.Scanner;
public class average {
public static double average (double [] grade ){
double sum = 0;
int number = grade.length;
for(int i = 0; i<grade.length; i++){
sum+=grade[i];
}
double average = sum / number;
return average;
}
public static void main (String [] args){
Scanner s = new Scanner(System.in);
System.out.println("How much grades you add?");
int number = s.nextInt();
while(number == 9999){
break;
}
double [] grade = new double [number];
System.out.println("Please enter : ");
for(int i = 0; i<grade.length; i++){
grade[i] = s.nextDouble();
}
System.out.println("My grades are: ");
for(int i = 0; i<grade.length; i++){
System.out.println(grade[i] + " | ");
}
System.out.println("");
System.out.println("My average: " +average(grade));
}
}
You are using a break, which immediately exits only the loop. If you want to quit the program, you should use if and return like this:
if(number == 9999) {
return;
}
This quits the program because with return, you exit the current function. The current function is main(), that's the program's main code. So, if you exit it, you will quit the program.
In functions with a return value (non-void functions) you need to specify the return value like this:
return 9999;
If you are on an other program thread, you need to call System.exit(0).
You don't need to break any loop, you just need to exit the program.
if (number == 9999) {
System.exit();
}
Related
The point of the program is to have a user input an amount of integers endlessly (until they enter something other than an integer), and for each integer the user inputs, it should check if the integer is greater than or less than the value entered.
The problem: When the program runs, everything is fine until reaching
number = scanner.nextInt();
At this point, the user inputs their integer, but never makes it inside the following if statements. I would love a hint instead of an answer, but I'll take what I can get.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
} while (true);
scanner.close();
}
}
Your minNumber and maxNumber declarations should be out side of the loop. Also, you need to initialize the values as below to get correct min and max comparison with the entered values only:
int minNumber = Integer.MAX_VALUE;
int maxNumber = Integer.MIN_VALUE;
In print statement instead of minNumber you are printing number!
It's not reaching the if statements, because if it did, the user input would update to the value entered I would think. It doesn't. It outputs the values initially declared.
You're not getting the right output and you have a hypothesis that the cause is the code not entering the if statements. Following the scientific method, the next step is to test your hypothesis.
If you put printouts inside the if statements you'll see that they are indeed running. That's not it. The mistake must be elsewhere. You should collect more evidence and develop a new hypothesis.
Hint: Try printing out the values of your variables at the beginning and end of each iteration. I've marked the places below. Are they what you expect them to be? You're going to see an anomaly that should point you in the right direction.
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
// Print number, minNumber, and maxNumber.
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
// Print number, minNumber, and maxNumber.
} while (true);
I am working on writing a program that follows these instructions:
Your little sister asks you to help her with her multiplication, and you decide to write a Java program that tests her skills. The program will let her input a starting number, such as 5. It will generate ten multiplication problems ranging from 5×1 to 5×10. For each problem she will be prompted to enter the correct answer. The program should check her answer and should not let her advance to the next question until the correct answer is given to the current question.
After testing ten multiplication problems, your program should ask whether she would like to try another starting number. If yes, your program should generate another corresponding ten multiplication problems. This procedure should repeat until she indicates no.
I have the code correct to ask for the multiplication part, but I can't quite figure out how to get the program to ask if the user wants to continue.
The following code has the program run through once:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
}
}
When I uncomment out line 21 the program returns:
Enter number you would like to attempt: 1
1 x 1 = 1
Would you like to do another problem? 1 x 2 = 2
Would you like to do another problem? 1 x 3 =
etc...
If I take the code from line 21 and put it outside of the for loop the program runs the for loop once and then jumps straight to the question.
How do I go about fixing this and successfully completing the instructions?
Here's how I'd do it:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args)
{
boolean wantsToContinue = true;
while(wantsToContinue)
{
wantsToContinue = mathProblem();
}
}
public static boolean mathProblem()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
boolean wantsToContinue;
//Ask if the user would like to do another problem here, set "wantsToContinue" accordingly
return wantsToContinue;
}
}
This is my first post.
Using a Scanner class, I'm trying to let user input to choose to repeat the program or quit. The thing is my Do loop statement repeats the program and does not exit even if the Do Loop is false and should exit the program.
// loop repeat or quit
do {
//initialize variable
int integer;
int x = 1;
int factorial = 1;
System.out.print("Please enter an integer \n");
integer = getInt.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = getString.next();
} while(quit != yes);
System.exit(0);
}
There were a few mistakes in your code, so I rewrote it a little bit and used the correct functions where you used incorrect ones.
public static void main(String args[])
{
// Scanner is used to take in inputs from user
Scanner scan = new Scanner (System.in);
String quit = "";
// loop repeat or quit
do {
//initialize variable
int integer = 0;
int x = 1;
int factorial = 1;
// User needs to enter integer, or it'll throw exception.
System.out.println("Please enter an integer");
integer = scan.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
// factorial = x!
while (x <= integer) {
factorial *= x;
x++;
};
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.println("do you want to quit? y or n");
quit = scan.next();
// if quit is NOT equal to y, we do it again
} while(!quit.equals("y"));
System.exit(0);
}
I hope the comments helps :)
I've edited your code and it now runs.
For future reference: include more comprehensive snippets so viewers of your code can more easily discover mistakes.
Problem: There is no way to guarantee the user only inputs y without any spaces . THe easy solution to this problem is to use the string method contains(). I've modified your loop so that if the user input y the program will exit and it now works. Let me know if this works and happy coding!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String quit ="";
do { //initialize variable
int integer; int x = 1; int factorial = 1;
System.out.print("Please enter an integer \n");
integer = in.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = in.next();
} while(!quit.contains("y"));
System.exit(0);
}
Shouldn't it be
while(quit != "y");
I also don't understand why you use System.out.print(); and then use \n when there's a perfectly good System.out.pritnln();
Also, since we're dealing with Strings the .nextLine(); is good enough for the Scanner. (You'll have to declare String quit as well.)
So I have this method for mean, my goal is to have the user enter one grade at a time, and the dialog box pops up after each grade is entered, after they are finished they hit okay with nothing or cancel and it populates the mean text field. I am having trouble figuring out how to put in the correct parameters for this method, as I need to parse the string they enter into a double array so that the method can properly calculate.
This is the method below:
public double getAverage (double [] gradeArray, int numElem) {
double sum = 0;
for (int i = 0;i < numElem; i++){
sum = sum + gradeArray[i];
}
return (sum / numElem);
}
Here is my code attempting to take the string and put it into the method. Clearly wrong, but I am having trouble wrapping my head around the whole thing. I am not sure how to get my numElem argument to be the correct number, as it changes depending on how many grades the user inputs.
This is my code for the button pushed to calculate:
private void btnGradesActionPerformed(java.awt.event.ActionEvent evt) {
int numElem = 0;
String s = "";
double[] gradesArray;
gradesArray = new double[25];
int i;
do {
s = (String)JOptionPane.showInputDialog(this, "Enter grades:", "Enter grades", JOptionPane.PLAIN_MESSAGE);
if (s == null || s.equals("")) {
if (s == null)
{
s = "";
}
String total2 = String.valueOf(avg);
txtMean.setText(total2);
} else {
for(i=0; i<25; i++)
{
gradesArray[i] = Double.parseDouble (s);
numElem++;
}
avg = getAverage (gradesArray, numElem);
}
} // end Do
while (!s.equals(""));
}
Keep track of how many grades the student has entered. You can do this with a variable that starts at 0 and gets incremented every time the student enters a grade correctly. You can then pass that value as numElem.
I think something like this is what you'd want to do:
s = ... //ask user to input number of grades here
numElem = Int.parseInt (s)
for(i=0; i<numElem; i++)
{
s = ... //prompt for next grade
gradesArray[i] = Double.parseDouble (s);
}
You can initialize gradesArray to be bigger as well to account for more possibilities, maybe 100 or something. Just make sure the numElem input isn't greater than the initialized size.
I'm having a problem with my while loop. The program asks the user for their name and after the user have made their input, the program asks how many times you would like to print the input.
I've been stuck on my while-loop for quite a time and can only make it work if I do something like: } while (antal > some random number)
package uppg2;
import java.util.Scanner;
public class Uppg2 {
public static void main(String[] args) {
Scanner name = new Scanner(System.in);
Scanner ant = new Scanner(System.in);
int antal;
String namn;
System.out.print("Whats your name?: ");
namn = name.nextLine();
System.out.print("How many times u wanna print ur name?: ");
antal = ant.nextInt();
do {
System.out.print(namn);
} while (????);
antal++;
namn = null;
antal = 0;
}
}
I personally would use a for loop like so:
for(int i = 0 ; i < antal; i++){
System.out.println(namn);
}
This would be rather a use-case for a for-loop like some others suggested. But when you insist on using a while loop:
int counter = 0; // a variable which counts how often the while loop has run
do {
System.out.print( namn ); // do what you want to do
counter++ // increase the counter
} while (counter < antal) // check if the desired number of iterations is reached
When you don't need the value of antal anymore when the loop is over, you can also do it without the counter variable and just reduce antal every loop and check if it has reached 0.
do {
System.out.print( namn );
antal--;
} while (antal > 0)
You could count antal down (antal--) until it is 1. Not sure if it is OK to destroy the value in antal though.
package uppg2;
import java.util.Scanner;
public class Uppg2 {
public static void main(String[] args) {
final Scanner in = new Scanner(System.in);
int antal;
String namn;
System.out.print("Whats your name?: ");
namn = in.nextLine();
System.out.print("How many times u wanna print ur name?: ");
antal = in.nextInt();
int i = 0;
while(i < antal){
System.out.print( namn );
i++;
}
in.close();
}
}
Tell me if that works. Basically, you need an increment counter to ensure that it only prints out the desired amount of times. Since we start counting at 0, we don't need to ensure that it goes till it equals the print time, but while it still is under it.
you would have to have a counter that is incremented inside of your do-while loop, and perform your comparison against that value
it would make your loop loop something like:
antal = ant.nextInt();
int i = 0;
do{
System.out.print( namn );
i++;
}while (i < antal);
note that because it's a do-while loop, you will always print the name at least once, even if the user enters zero. To prevent this, you would need to use a for or while loop, as described by other answerers, or use an if condition around the System.out.println call to check if antal is zero.
Also, if you don't care what antal is at the end, you can use TofuBeer's solution.
Here's a solution to a similar problem. See if you can't translate it into your problem:
// How many times to I want to do something?
int max = 40;
for (int i = 0; i < max; i++) {
// Do something!
}