What is wrong with the formatting in my Java code? [duplicate] - java

This question already has an answer here:
Why am I getting an exception?
(1 answer)
Closed 6 years ago.
I've been told that there are problems with my formatting, at the end. However, I can't figure out what that would be...The error messages are at the end of the code.
PLEASE DON'T BE AMBIGUOUS WITH YOUR ANSWERS AND TELL ME WHAT TO FOCUS ON OR REVIEW (LIKE FORMATTING).I NEED CONCRETE THINGS TO CHANGE. Thank you!!
Here's the code:
public static void main(String[] args)
{
double pennies = 0.01; //number of pennies
double totalPennies = 0.01; //the variable that is added to
int maxDays; //number of days the loop will double the pennies to
int day = 0; //the variable used to count each day in the loop
//Create a String variable for user input with a console window.
String input;
//Create a scanner object for keyboard input into the console.
Scanner keyboard = new Scanner(System.in);
//Ask user for the number of days to count.
input = JOptionPane.showInputDialog("Enter the maximum number of days worked in your pay period"
+ " and I will tell you how much money you made. Please enter at least 1.");
maxDays = Integer.parseInt(input); //this makes the user's string input into
//an integer data type
//Input Validation
while(maxDays < 1)
{
System.out.println("You have entered a number that "
+ "is less than 1. \nPlease enter a number that is at"
+ " least 1 or more:");
maxDays = keyboard.nextInt();
}
//next we have the first loop that will only execute if the user enters at least 1
while(maxDays >= 1)
{
//here's the chart
System.out.println("Day Day's Income Total "); //titles for the chart
System.out.println("----------------------------------"); //34 dashes/spaces
System.out.println("1 $0.01 $0.01 "); //the first day
//this next nested loop will do the actual counting and add to the chart with
//each iteration
for(day = 2; day <= maxDays; day++)
{
pennies = pennies * 2; //double pennies
totalPennies += pennies; //add the new value of pennies to the running total
//add information from each iteration to the chart
System.out.printf("%10.0d" + "$%18.0f" + "$%6.0f", day, pennies, totalPennies );
}
}
}
Here are the error messages:
Exception in thread "main" java.util.IllegalFormatPrecisionException: 0
at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2984)
at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2729)
at java.util.Formatter.parse(Formatter.java:2560)
at java.util.Formatter.format(Formatter.java:2501)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at assignment4PenniesForPay.assignment4PenniesForPay.main(assignment4PenniesForPay.java:65)
Line 65 is the formatting line.

%10.0dis expecting an integer, but you're adding a decimal place in there.

Related

Use while loop to print as many times as requested by user

Hello I am stuck on a programming assignment for class. The assignment is to make a program that can count different loops. I have the prompt user input code correct I think I just can't figure out how to make it print my message the amount of times that I have entered.
I want the second while loop to print something like
Row 1 - Hello
Row 2 - Hello
Row 3 - Hello
Row 4 - Hello
For the number that I put as the input.
Thank you for the help in advance.
import java.util.Scanner;
public class CountingLoops
{
public static void main(String[] args)
{
String message; // First message prompt
String inputString; // For reading input.
double numRows; // Number to be asked.
double rowNumber = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the message you want to print? ");
message = keyboard.nextLine();
System.out.print("Enter how many times you want your message to be printed. Enter the value from 1-20:" );
numRows = keyboard.nextDouble();
while (numRows > 20 || numRows < 1)
{
System.out.print("Number was not between 1-20. Try Again.");
System.out.print("Enter how many times you want your message to be printed. Enter the value from 1-20: ");
numRows = keyboard.nextDouble();
}
while (numRows <= 20)
{
System.out.println("Row " + rowNumber++ + " - " + message);
rowNumber = keyboard.nextDouble();
rowNumber++;
}
}
}
What do you mean by "a program that can count different loops". Currently the bottom while loop is an infinite loop since numRows isn't being updated. Here's what I believe can solve your issue:
while (numRows > 0)
{
System.out.println("Row " + rowNumber++ + " - " + message);
rowNumber++;
numRows--;
}
Since it is an assignment, I won't provide the code. But all the problem with your code is in the last while loop.
First, you don't even change the value of the variable numRows and of course, you cannot exit the while loop.
Second, you don't need to read another input during this while loop since all the input is done at the beginning.
Third, you added rowNumber twice in your code and obviously, it is incorrect and it should be changed to something else.
Your answer will involve comparing rowNumber and numRows to determine when you are done.

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

Based on user input years, generate random numbers for a 2d array based on the user input

Before I state my question I have searched the questions that have already been posted and they were of some help to me, but not really what I am looking for.
For now, don't worry about the 2d array portion.
I am supposed to create a program that generates random float values based on the user input for a number of years. Let me explain.
First it asks for the user input for years; the user enters a value between 1-80 and the program checks if the entered value is between those two. (DONE)
Then, based on the user input, it will print out each year with a random value between [0.00 and 100.00] like so.
Example; if user enters 3, then the output will display;
year 1: random values
year 2: random values
year 3: random values
Let's just start with that for now. I already have it to where it it asks for user input and I did have it to where it generated random values, but they were not between what I wanted.
Here is my code so far.
package name;
import java.util.*;
public class name {
public static void main(String[] args) {
Random generator = new Random();
inputCheck();
}
public static void inputCheck(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the desired number of years: ");
int years = keyboard.nextInt();
System.out.println();
while (years < 1 || years >= 80){
System.out.print("Please enter a value for years that is greater than 1 and less than 80: ");
years = keyboard.nextInt();
System.out.println();
}
}
}
Here you are
public class Test {
public static void main(String[] args) {
Random generator = new Random();
int years = inputCheck();
for (int i = 1; i <= years; i++) {
System.out.println("Year " + i + ": " + generator.nextFloat() * 100);
}
}
public static int inputCheck() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the desired number of years: ");
int years = keyboard.nextInt();
System.out.println();
while (years < 1 || years >= 80) {
System.out.print("Please enter a value for years that is greater than 1 and less than 80: ");
years = keyboard.nextInt();
System.out.println();
}
return years;
}
}
I don't see that generator being used, but aside from that, when you do you will only get an integer between zero and the given value(without manipulation of course) wha you want is a float between 0 and 100 with two decimal places, so generate the random number:
Randint=(Generator.nextFloat(100.00));
At least that is what I remember 😁.
I only gave this since you say you have everything else down pat.

Finding the Min and Max numbers using Dialog boxes Java

So my assignment is this
Ask the user to input a number. You should use an input dialog box for this input. Be sure to convert the String from the dialog box into a real number. The program needs to keep track of the smallest number the user entered as well as the largest number entered. Ask the user if they want to enter another number. If yes, repeat the process. If no, output the smallest and largest number that the user entered.
This program outputs the largest and smallest number AT THE END of the program when the user wants to quit.
Also, your program should account for the case when the user only enters one number. In that case, the smallest and largest number will be the same.
I am having a hard time making it if the user only enters 1 number then both values will be set but at the same time making it loop as long as the user says yes.
public static void main(String[] args)
{
int maxNum = Integer.MAX_VALUE;
int minNum = Integer.MIN_VALUE;
String repeat;
String firstResponseString = JOptionPane.showInputDialog("Enter a Number ");
maxNum = Integer.parseInt(firstResponseString);
minNum = Integer.parseInt(firstResponseString);
String userRepeat = JOptionPane.showInputDialog(" Would you like to input another number? Y/N");
while(userRepeat.equalsIgnoreCase("Y"))
{
String num1String = JOptionPane.showInputDialog("Enter a Numer: ");
int num1 = Integer.parseInt(num1String);
if(num1 > maxNum)
{
maxNum = num1;
}
if(num1 < minNum)
{
minNum = num1;
}
userRepeat = JOptionPane.showInputDialog(" Would you like to input another number? Y/N");
}
JOptionPane.showMessageDialog(null, "Largest Number: " + maxNum + "\nSmallest Number: " + minNum, "Find Min and Max", JOptionPane.INFORMATION_MESSAGE);
}
I think I got it working now with this code
You may set the int minNum = Integer.MIN_VALUE and int maxNum = Ingerer.MAX_VALUE in declaration.
The String repeat serves no purpose since it's not used anywhere but in the declaration also the assignment of maxNum=... and minNum=.... is unnecessary since you're parsing the maxNum and minNum so they can be recognized by the JOptionpane.

In Java, is it possible to use some sort of while loop (or anything) to determine the amount of prompts for input?

public static void main (String [] args)
{
// declare variables, capture input
String input, name = JOptionPane.showInputDialog("Please " +
"enter your first and last name.");
double testScore1, testScore2, testScore3, average;
// capture input, cast, and validate input
input = JOptionPane.showInputDialog("What is the score " +
"of your first test?");
testScore1 = Double.parseDouble(input);
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your second test?");
testScore2 = Double.parseDouble(input);
while (testScore2 < 1 || testScore2 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore2 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your third test?");
testScore3 = Double.parseDouble(input);
while (testScore3 < 1 || testScore3 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore3 = Double.parseDouble(input);
}
// calculate average and display output
average = (testScore1 + testScore2 + testScore3)/3;
JOptionPane.showMessageDialog(null, name + ", your average score is: " + average);
}
First off, I'm a beginner programmer. My terminology and jargon are quite lacking, so bear with me.
I'm writing a program to capture 3 test scores then validate them using a while loop (must be within the 1-100 range). The test scores are then averaged and the output displays the average. Pretty simple stuff.
I'm wanting to find a way, if possible, to capture the number of test scores, then from there, capture each actual score. For example, the program asks "How many tests are being computed for average?", then take that number and have it be the same amount of times the program prompts, "Please enter test score (1):" or something along those lines. So for further clarity, if the user typed 4 for number of tests, then the prompt for inputting the score would show up 4 times.
I feel the above code is redundant by using a while loop for each score and at that, limited because the program is only meant for 3 scores. Any help is much appreciated and feel free to critique anything else in the code.
Yes you can.
What you need is a nested loop. In pseudo code:
while(condition)
{
int numberOfInput = getInput() ; //get the input from the user
for(int i =0 ; i < numberOfInput; i++) //iterate for the amount of prompts required
prompt() ; //get input
}
function prompt
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
Short answer:Yes, it is possible.
Option 1: Initially ask the user how many scores they are planning on entering, and store that in an int variable.
For example:
Ask user how many scores to enter.
Check the response, and store it in an int variable.
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable
Once loop is exhausted, just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Option 2: Use a sentinel-loop (the user has to enter a letter -usually 'Q' or 'N'- or something to exit the loop)
Create an int variable to store total loops (initialize to 0).
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Check if the value is the quit character
If it is not
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable and increment
the total loops variable by 1.
If it is
just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Hope it helps.
In http://korada-sanath.blogspot.in/p/discussion-on-tech-topics.html, there is a pseudo code which illustrates similar problem with basic Java programming skills. In that in looping section you can simply add a check whether user entered score is in range 1-100 or not. If not, you can decrease loop variable by '1' so that user can enter his score one more time...
For further illustration please add below code in looping section of code present in above mentioned link.
instead of directly assigning user entered value to your testScores array, you can use one temp var and then can assign if user entered score in range.
Double temp = Double.parseDouble(br.readLine());
if(temp > 1 && temp < 100) {
testScores[loopVar] = temp;
} else {
loopVar--;
}

Categories