Can't figure why my program doesnt work - java

import java.util.Scanner;
public class pointSystem {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int points;
int total = 0;
final int judges = 5;
System.out.println("Give points: ");
for(int i=0;i<judges;i++)
{
System.out.println("Give judge's "+ (i+1) + " points: ");
points = scanner.nextInt();
if(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}
System.out.println("Total points are "+total);
}
}
So it's totally a simple program where it asks the user to input points for 5 judges in total and then sums up the points at the end. But points can only be inserted between 0-20, if it goes outside of the range, it gives an error telling us to input again and continues to do so until we have give a valid input.
Now the program works pretty well except for a point that if I enter "22" for example, it asks again like intended but if I enter "22" once again, it lets it pass and skip to next judge.
How can I make it to keep asking until I have given a valid input before it moves to next judge? Please give a small explanation if you fix my code.
Also I'm supposed to make a small edit that when it sums up the points at the end, it minus the highest and lowest score away, summing up only the points between. So if the points are "3,5,8,9,20" it will take "3 and 20" away and only sums up "5,8 and 9" making it 22.

In your code, you have an if statement to check the input, but if your input doesn't pass your program will accept your next input without checking it.
To fix this, don't progress your program until your input is valid using a while loop, like this:
while(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}

Related

Why is my program printing two statements including of my previously entered number?

'So question was to find pytho triplet using the number inputted but number has to be greater than one and natural.
The error I am facing is that suppose I enter -4, then it runs method again and asks me to enter number again and I enter suppose 9 but while printing final statement, it prints triplets of both -4 and 9. How can I fix it as I only want triplet of 9 to be printed?
import java.util.*;
public class Pythagorean_Triplet
{
private static int a;
public static void main(String[]args) //main method
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to find Pythagorean Triplet : ");
int a=sc.nextInt();
if(a<2) //our program only works on natural numbers greater than 1
{
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
main(args);
}
double p1= 2*a;
double p2=Math.pow(a,2) - 1;
double p3=Math.pow(a,2) + 1;
System.out.println("");
System.out.println(p1 + ", " + p2 + " and " + p3 + " form a 'Pythagorean Triplet'");
}
}
You are calling the main method again (recursive call) so after you entered "9" the main(args); call returns and print the output for the first input.
So you should ask for a new number until you get a correct input.
import java.util.Scanner;
public class PythagoreanTriplet {
public static void main(String[]args) //main method
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number to find Pythagorean Triplet : ");
int a = sc.nextInt();
while(a<2) //our program only works on natural numbers greater than 1
{
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
System.out.println("Please retry with a number greater than 1 : ");
a = sc.nextInt();
}
double p1= 2*a;
double p2=Math.pow(a,2) - 1;
double p3=Math.pow(a,2) + 1;
System.out.println("");
System.out.println(p1 + ", " + p2 + " and " + p3 + " form a 'Pythagorean Triplet'");
}
}
Calling a method doesn't stop the current method from executing. When the method you call completes, the current method continues.
For example, when you do this:
System.out.println();
You are calling a method. That method performs its logic, completes, and then this code continues on to the next statement. So when you do this:
main();
The same exact thing happens. The method performs its logic (in this case accepts your new input and produces output), completes, and then this code continues on to the next statement. That next logic is to produce the rest of the output.
Basically, recursion is the wrong tool for this job. Instead, loop over reading the input until correct input is received. Perhaps something like this:
Scanner sc = new Scanner(System.in);
int a = 0;
while (a < 2) {
// your loop logic
}
Notice how a is initialized to something that will cause us to enter the loop. Then in the loop is the operation we want to repeat, where we will continually ask for input until a is a valid value:
Scanner sc = new Scanner(System.in);
int a = 0;
while (a < 2) {
System.out.println("Enter number to find Pythagorean Triplet : ");
a = sc.nextInt();
if (a < 2) {
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
}
}
There are different ways to structure it. In this approach I've repeated the a < 2 logic. Another approach might ask outside the loop then re-ask within the loop, repeating the nextInt() logic. How you structure it generally comes down to the UX you want in the prompts and personal preference on how to organize the logic.
But overall the point here is that you want a loop, not recursion.
Since none of the above answers are accepted as the answer to your problem, i guess you actually want to work with recursion. Following is a representation of what your program currently does with the your example inputs.
what we need to do now, is to stop the first 'main()' call from printing its output. to achive that, we can simply 'return' after calling 'main()' the second time, or put the block of code which prints the output into the 'else' block of your if statement. your program would then look something like this:
using 'return' to stop wrong outputs
import java.util.*;
public class Pythagorean_Triplet
{
private static int a;
public static void main(String[]args) //main method
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to find Pythagorean Triplet : ");
int a=sc.nextInt();
if(a<2) //our program only works on natural numbers greater than 1
{
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
main(args);
return;
}
double p1= 2*a;
double p2=Math.pow(a,2) - 1;
double p3=Math.pow(a,2) + 1;
System.out.println("");
System.out.println(p1 + ", " + p2 + " and " + p3 + " form a 'Pythagorean Triplet'");
}
}
using 'else' to stop wrong outputs
import java.util.*;
public class Pythagorean_Triplet
{
private static int a;
public static void main(String[]args) //main method
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to find Pythagorean Triplet : ");
int a=sc.nextInt();
if(a<2) //our program only works on natural numbers greater than 1
{
System.out.println("");
System.out.println("Your number is not a natural number or is 1");
System.out.println();
main(args);
} else {
double p1= 2*a;
double p2=Math.pow(a,2) - 1;
double p3=Math.pow(a,2) + 1;
System.out.println("");
System.out.println(p1 + ", " + p2 + " and " + p3 + " form a 'Pythagorean Triplet'");
}
}
}

The Equals Function does not Work When it is In While Loop

I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
There are two places where there is a problem:
The first one sc.nextInt() method - which only reads the int
value by keeps current reading buffer on the same line. So to
ignore/skip everything what is after int on the input line (which is
probably \n or \r\n if you only enter the number) you have to
use sc.nextLine().
The second one is sc.next() method - which
only reads first token(or simply word) from your line. That is
probably why you only get "less" value assigned to response
and that will never be .equals to "less than". So you will
have to replace sc.next() one with sc.nextLine() and remove
unnecessary sc.nextLine() from the next line.
Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.
If my explanation is still not clear have a look at the code I have modified for you below:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}

GPA calculator assistance

Hi I was wondering if I could get some help with a GPA calculator.
What it needs to do is:
The input will consist of a sequence of terms, e.g., semesters.
The input for each term will consist of grades and credits for courses taken within that term.
For each term, the user will type in an integer that represents the number of courses
taken within that term.
Each course is specified by a String letter grade and an int number of credits, in that order, separated by white space. 5. If the user types in -1 for the number of courses taken in a term, then the program must print a final overall summary and then terminate.
DO NOT prompt for any input. Thus, after you run your program in BlueJ, type Ctrl-T to force the Terminal window to pop up.
As always, follow the input / output format depicted in the Sample runs section.
Shown below is the error message I get and the code I have, thank you for any assistance in advance or tips I could try.
Terminal window and error message:
import java.util.Scanner;
/*
*
*
*/
public class Prog2 {
public static void main(String args[]) {
Scanner numberInput = new Scanner(System.in);
int numberofClasses = numberInput.nextInt();
Scanner input = new Scanner(System.in);
String [] grade = new String[5];
int [] credit = new int [5];
double totalCredit = 0.0;
double realGrade = 0.0;
double result = 0.0;
while (numberofClasses > 0)
{
for (int x = 0; x < numberofClasses; x++ )
{
grade[x] = input.next();
credit[x] = input.nextInt();
}
for(int x=0;x < numberofClasses; x++ ){
if(grade[x].equals("A+")){
realGrade=4.0;
}
else if(grade[x].equals("A")){
realGrade=4.0;
}
else if(grade[x].equals("A-")){
realGrade=3.67;
}
else if(grade[x].equals("B+")){
realGrade=3.33;
}
else if(grade[x].equals("B")){
realGrade=3.00;
}
else if(grade[x].equals("B-")){
realGrade=2.67;
}
else if(grade[x].equals("C+")){
realGrade=2.33;
}
else if(grade[x].equals("C")){
realGrade=2.00;
}
else if(grade[x].equals("C-")){
realGrade=1.33;
}
result = result+realGrade*credit[x];
totalCredit=totalCredit+credit[x];
}
System.out.println("Summary for term:");
System.out.println("----------------------------------");
System.out.println("Term total grade points: " + result);
System.out.println("Term total credits:" + totalCredit);
System.out.println("GPA:"+result/totalCredit);
}
// This block is getting used later please ignore
System.out.println("Final Summary:");
System.out.println("----------------------------------");
System.out.println(" Overall terms");
System.out.println(" Total grade points: " + result);// this needs to be all );
System.out.println(" Total credits" + totalCredit);//This needs to be all );
System.out.println("Cumulative GPA:"+result/totalCredit);
}
}
When your while loop ends, numberofClasses still contains the value that was entered before the while loop started the first time. Specifically, after you output the line:
GPA=3.0588...
you hit the end of the loop, then return to:
while (numberofClasses > 0)
which is true. The next "3" that you enter doesn't go into numberofClasses, it is picked up by
grade[x] = input.next();
Then the "A" is picked up by
credit[x] = input.nextInt();
which throws an exception since it's not an integer.
All you need to do is ask for the number of classes again at the end of the while loop:
System.out.println("GPA:"+result/totalCredit);
numberofClasses = numberInput.nextInt();
}
Output:
5
A 3
B 2
C 4
A 5
C 3
Summary for term:
----------------------------------
Term total grade points: 52.0
Term total credits:17.0
GPA:3.0588235294117645
3
A 3
B 5
C 1
Summary for term:
----------------------------------
Term total grade points: 81.0
Term total credits:26.0
GPA:3.1153846153846154
i recommend looking into whether your compiler or IDE has a "debug" feature. It is a very helpful tool, and lets you watch how your program goes through your code
Just a tip...
When you ask for input, print what you're asking for first. When I launched your program I had no idea what to do. Try adding System.out.println("input number of classes you took");before you prompt for that number.
Here is what is wrong. (If you printed what you're asking for first, this would be more apparent).
after your program displays the stats, you enter 5. Yet your program is actually still on this line grade[x] = input.next(); on line 22 i believe.
when you enter 5, your scanner is expecting a letter. and an exception is thrown.
you need to consider how you escape this loop here. while (numberofClasses > 0) perhaps use an if statement? otherwise your program loops for forever, never asking for a new class number

Squaring and totaling in java

So the challenge is to prompt the user to enter an integer value "count". Next
prompt them to enter "count" more values. Then square each value entered and add it to a main
value sum.Then display the sum of the square of all the numbers entered.
An example of the build output is like :
Please enter an integer value: 3
Please enter 3 numeric values:
7 8 3.5
The sum of the squares of each of these numbers is: 125.25
I'm still new to learning code, so I'm a bit lost at how to square multiple values on a single user input and also totaling them up. Can anyone offer some help?
import java.util.Scanner;
public class Assign2 {
public static void main(String[] args) {
sum_squares();
}
public static void sum_squares(){
Scanner in = new Scanner(System.in);
System.out.println ("Please enter an integer value:");
int count = in.nextInt();
System.out.println ("Please enter" + count + "more values:");
int square = in.nextInt();
}
}
You need to add a for-loop after:
System.out.println ("Please enter" + count + "more values:");
The for-loop should run for count times, and each time the loop is run, it should ask the user for an input. You can then take that input and square it (remember - squaring is as easy as multiplying a number by itself! 2 * 2 = 4, or 2-squared) Once you have the squared number, add it to a sum variable which you will have created before the for-loop. Then just print out the sum after the for-loop.
Here is a great tutorial on for-loops!

In java, in this program it suddenly stops running properly at a certain point of code? but it compiles? any ideas what could be the issue?

import java.io.IOException;
import java.util.*;
public class task2 {
public static void main (String [] args) throws IOException {
int a;
int b;
String y;
String x;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number A:");
a = input.nextInt();
System.out.println("\nPlease enter number B:");
b = input.nextInt();
System.out.println("\nLastly, enter A if you wish it to be the dividor and/or subtractor, or if you wish it to be B, please enter B :"); //stops running properly here...
y=input.nextLine();
System.out.println("\nWhat would you like to do? Multiply (*), Divide (/), Subtract (-) or Add (+)? Please enter the symbol of which process you would like to have completed:");
x=input.nextLine();
if (y=="b"+"B") {
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + a*b);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + a/b);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + a+b);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (a-b));}}
else
if (y=="a"+"A"){
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + b*a);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + b/a);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + b+a);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (b-a));}}
}
}
I dont know why it stops but where indicated by "//" the program suddenly stops letting me input information and does not continue the processes i want it to do. I wont bother explaining the program in detial because i believe it is fairly obvious from the code itself what i want to do.
Thanks in adavance for all the help!
Use
input.next();
not
input.nextLine();
Since nextLine() skips over the input and sets the scanner to the NEXT line and returns a string representation of what was skipped. Your program throws the errow because the NEXT line does not exist
Your string comparisons are incorrect--you need to compare strings using the equals() method, like x.equals("*") in order for any of them to work. (This is a pretty common mistake, so even though it's homework, freebie :)
There's no loop, so it'll stop after the first time "through"; this may or may not be what you want.

Categories