I've tried merging the two loops into one do loop, but every time I enter an invalid value it doesn't prompt me the error message and ask to enter the value again. Instead it just moves on to the next prompt statement.
do {
try {
dependents = Integer.parseInt(JOptionPane.showInputDialog("number of dependents:"));
}
catch (NumberFormatException e) {
dependents = MIN_DEPENDENTS - 1;
}
if (dependents < MIN_DEPENDENTS || dependents > MAX_DEPENDENTS) {
JOptionPane.showMessageDialog(null, "Number of dependents must be between 0 and 9.");
}
} while (dependents < MIN_DEPENDENTS || dependents > MAX_DEPENDENTS);
do {
try {
income = Double.parseDouble(JOptionPane.showInputDialog("amount of income:"));
}
catch (NumberFormatException e) {
income = MIN_INCOME - 1;
}
if (income < MIN_INCOME || income > MAX_INCOME) {
JOptionPane.showMessageDialog(null, "income must be between $0 and $999,999.");
}
} while (income < MIN_INCOME || income > MAX_INCOME);
No, but you could create some sort of GetInput function and pass in min, max, promptText, and errorText. This would save you duplicating the code.
dependents = getInput(MIN_DEPENDENTS, MAX_DEPENDENTS,"number of dependents:","Number of dependents must be between 0 and 9.")
income = getInput(MIN_INCOME,MAX_INCOME,"amount of income:","income must be between $0 and $999,999.")
private double getInput(double min, double max, String promptText, String errorText) {
double result = 0.0;
do {
try {
result = Double.parseDouble(JOptionPane.showInputDialog(promptText));
}
catch (NumberFormatException e) {
result = min - 1;
}
if (result < min || result > max) {
JOptionPane.showMessageDialog(null, errorText);
}
} while (result < min || result > max);
return result;
}
Dan, you need to put below lined in your catch block to show error message and prompt again for input.
catch (NumberFormatException e) {
dependents = MIN_DEPENDENTS - 1;
JOptionPane.showMessageDialog(null, "Number of dependents must be between 0 and 9.");
dependents = Integer.parseInt(JOptionPane.showInputDialog("number of dependents:"));
}
Another option could to main list of input in array and then use it in while loop
Object[][] input = {
{"number of dependents", MIN_DEPENDENTS, MAX_DEPENDENTS},
{"amount of income", MIN_INCOME, MAX_INCOME},
};
int index = 0;
int value, min, max;
do {
Object[] inputDetails = input[index];
String label = inputDetails[0].toString();
min = Integer.valueOf(inputDetails[1].toString());
max = Integer.valueOf(inputDetails[2].toString());
try {
value = Integer.parseInt(JOptionPane.showInputDialog(label));
} catch (NumberFormatException e) {
value = min - 1;
}
if (value < min || value > max) {
JOptionPane.showMessageDialog(null, String.format("%s must be between %s and %s", label, min, max));
} else {
index++;
}
} while ((value < min || value > max) || index < input.length);
Related
I have a scenario to take the maximum value from the nearest number and match with that number with .if it is match click action would perform..all conditions I put it in a for loop..
public static int insertBeforeAfterMethod(int i, String event, String shotType, WindowsDriver < WebElement > mainEntrySession) {
for(int cellIndex = 14;cellIndex < pbp_insert_grid_cells.size();cellIndex+=17) //
{
System.out.println(pbp_insert_grid_cells.size());
rowSequenceNo = pbp_insert_grid_cells.get(cellIndex).getText();
String[] splitvalue=rowSequenceNo.split("\\.");
int guiSequenceNo=Integer.parseInt(splitvalue[0]);
System.out.println("hello gui sequence number....."+guiSequenceNo);
//i==4 here i==3
if ((i%2!=0) && (sequenceNo < guiSequenceNo)) //1.5 <2 insert before
{
System.out.println("hello"+i);
next =guiSequenceNo; //2
System.out.println("next"+next);
break;
}
else if((i%2==0) && (sequenceNo > guiSequenceNo)) //insert after
{
previous=guiSequenceNo;
break;
}
if(next==guiSequenceNo) // 2==rowSequenceNo insert before
{
System.out.println(cellIndex);
WebElement sequenceCellNoInsertBefore = mainEntrySession.findElementByName(pbp_insert_grid_cells.get(cellIndex).getAttribute("Name"));
rowNumber = sequenceCellNoInsertBefore.getAttribute("Name").substring(16);
System.out.println(rowNumber);
if(mainEntrySession.findElementByName(rowNumber).isDisplayed())
{
rowToClick = mainEntrySession.findElementByName("Period " +rowNumber);
rowToClick.click();
action.moveToElement(rowToClick).contextClick().perform();
mainEntrySession.findElementByName("Insert Before").click();
mainEntrySession.findElementByAccessibilityId("6").click();
retValue = getNexti(i, event,shotType,mainEntrySession);
System.out.println("return i "+retValue);
}
}
else if(previous==guiSequenceNo) //insert after
{
WebElement sequenceCellNoInsertAfter = mainEntrySession.findElementByName(pbp_insert_grid_cells.get(cellIndex).getAttribute("Name"));
rowNumber = sequenceCellNoInsertAfter.getAttribute("Name").substring(16);
System.out.println(rowNumber);
if(mainEntrySession.findElementByName(rowNumber).isDisplayed())
{
rowToClick = mainEntrySession.findElementByName("Period " +rowNumber);
rowToClick.click();
action.moveToElement(rowToClick).contextClick().perform();
mainEntrySession.findElementByName("Insert After").click();
mainEntrySession.findElementByAccessibilityId("6").click();
retValue = getNexti(i, event,shotType,mainEntrySession);
System.out.println("return i "+retValue);
}
}
}
return retValue;
}
here the for looping is not incrementing it is exiting...without break how to take immediate greater and smaller and store it in a variable...?
I am writing a java code to Change a number from decimal base to another base.
But I don't know why the program runs wrong. I think the error comes from function Prin_as. Can anyone tell me why ?
Below is my code,
import java.util.Scanner;
public class bai2chuyendoi {
public static void main(String[] args) {
int a, b;
System.out.println("Number in decimal base:");
a = Enter();
System.out.println("Other base :");
b = Enter();
Change_base (a, b);
}
public static int Enter() {
int n = 0;
boolean check = false;
while (!check) {
Scanner sc = new Scanner(System.in);
try {
n = sc.nextInt();
check = true;
} catch (Exception e) {
System.out.println("Enter again:");
sc.nextLine();
}
}
return n;
}
public static void Change_base(int a, int b) {
int i = 0;
int[] c = new int[8];
while (a != 0) {
c[i] = a % b;
a = a / b;
i++;
}
while (i >= 0) {
--i;
if (c[i] < 10) {
System.out.print(c[i]);
} else {
System.out.print((char) (c[i] + 55));
}
}
}
}
The error was in Change_base method in second while loop.
You need decrement 'i' and check that i >= 0, but you didn't.
while (--i >= 0) {
if (c[i] < 10) {
System.out.print(c[i]);
} else {
System.out.print((char) (c[i] + 55));
}
}
I'm working on a project where the Java code must find the total,
average, etc. of exam scores. It reads the scores from an external
file.
I've been trying for hours to find a way to edit my code so that it ignores any data in the file that is not an integer between 0-100. But I can't. Checked all the questions and answers on Stack Overflow, and I can't find any answers that would help my specific situation. Here's the while loop of my code that I'm trying to work with:
Scanner reader = new Scanner(file);
while (reader.hasNext())
{
String line = reader.nextLine();
nextScore = Integer.parseInt(line);
System.out.println(nextScore);
sum = nextScore + sum;
totalNumberOfScores++;
if (nextScore > maxScore)
{
maxScore = nextScore;
}
else if (nextScore < minScore)
{
minScore = nextScore;
}
if (nextScore >= A)
{
countA++;
}
else if (nextScore >= B)
{
countB++;
}
else if (nextScore >= C)
{
countC++;
}
else if (nextScore >= D)
{
countD++;
}
else
{
countF++;
}
}
reader.close();
Can anyone help ?
if(isInteger(line)){
nextScore = Integer.parse(line);
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
then you can do this
boolean isNumber = false;
for(int i = 0; i < line.length; i++){
try{
Integer.parseInt(String.valueOf(line.charAt(i)));
}catch(Exception e){
isNumber = false;
break;
}
}
if(isNumber){
Integer.parse(line);
}
or even
boolean isNumber = true;
try{
Integer.praseInt(line);
}catch(Exception e){
isNumber = false;
}
if(isNumber){
//everthing else
}
I would use a try-with-resources Statement to close the Scanner when through reading. Next, you need to define your min, max, total and lines count outside the loop. You could default min to the maximum possible value, and max to the minimum; then use Math.max(int,int) and Math.min(int,int) to set the max and min respectively. Then, you need to validate that you read an int and that is in the correct range before processing it as input. Something like,
try (Scanner reader = new Scanner(file)) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int total = 0;
int lines = 0;
int countA = 0, countB = 0, countC = 0, countD = 0, countF = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine();
try {
int nextScore = Integer.parseInt(line);
if (nextScore >= 0 && nextScore <= 100) {
min = Math.min(nextScore, min);
max = Math.max(nextScore, max);
total += nextScore;
lines++;
if (nextScore >= A) {
countA++;
} else if (nextScore >= B) {
countB++;
} else if (nextScore >= C) {
countC++;
} else if (nextScore >= D) {
countD++;
} else {
countF++;
}
}
} catch (NumberFormatException nfe) {
}
}
System.out.printf("Min: %d, Max: %d, Total: %d, Lines: %d, Average: %.2f%n",
min, max, total, lines, total / (float) lines);
System.out.printf("%d As, %d Bs, %d Cs, %d Ds, %d Fs", countA, countB,
countC, countD, countF);
} catch (IOException e) {
e.printStackTrace();
}
The method "aboveAverage" in the following code is not displaying correctly and I've tried everything I can. Could someone please explain what's going wrong?
My code:
import java.util.*;
public class DailyCatch
{
private int fishermanID, fisherID;
private String dateOfSample, date;
private double[] fishCaught = new double[10];
private int currWeight = 0;
private String summary;
private double average;
private int aboveAvg;
public DailyCatch() { }
public DailyCatch (int fishermanID, String dateOfSample)
{
fisherID = fishermanID;
date = dateOfSample;
}
public DailyCatch (int fishermanID, String dateOfSample, String weight)
{
this(fishermanID, dateOfSample);
readWeights(weight);
}
public void addFish(double weight)
{
if (currWeight > 10)
{
// array full
}
else
{
fishCaught[currWeight] = weight;
currWeight += 1; // update current index of array
}
}
private void readWeights(String weightsAsString)
{
String[] weightsRead = weightsAsString.split("\\s+");
for (int i = 0; i < weightsRead.length; i++)
{
this.addFish(Double.parseDouble(weightsRead[i]));
}
}
public String toString()
{
return "Fisherman ID: " + fisherID + "\nDate:" + date + "\nFish Caught with Weights: " + Arrays.toString(fishCaught);
}
public void printWeights()
{
for (int i = 0; i < fishCaught.length; i++)
{
System.out.println(fishCaught[i]);
}
}
public double averageWeight()
{
double sum = 0;
double count = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] != 0)
{
sum += fishCaught[i];
count += 1;
average = sum/count;
}
}
return average;
}
public String getSummary()
{ int storyTellerCount = 0;
int keeperCount = 0;
int throwBackCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 5)
{
storyTellerCount++;
}
else if (fishCaught[i] >=1 && fishCaught[i] <= 5)
{
keeperCount++;
}
else if (fishCaught[i] < 1 && fishCaught[i] > 0)
{
throwBackCount++;
}
} String summary = ("\nStoryteller - " + storyTellerCount+ "\nKeeper - " + keeperCount + "\nThrowback - " + throwBackCount);
return summary;
}
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > average)
{
aboveAvg = greatAvgCount++;
}
}
return aboveAvg;
}
}
Test Code:
public class BigBass
{
public static void main (String[]args)
{
//Part 1
DailyCatch monday1 = new DailyCatch(32, "4/1/2013", "4.1 5.5 2.3 0.5 4.8 1.5");
System.out.println(monday1);
//Part 2
DailyCatch monday2 = new DailyCatch(44, "4/1/2013");
System.out.println(monday2);
monday2.addFish(2.1);
monday2.addFish(4.2);
System.out.println(monday2);
//Part 3
System.out.println("\n\nSUMMARY OF FISHERMAN 32");
System.out.println(monday1.getSummary());
//Part 4
double avg = monday1.averageWeight();
System.out.printf("\nThere are %d fish above the average weight of %.1f.", monday1.aboveAverage(), avg);
}
}
I just need to get Part 4 to work here. What it does is return that there have been 2 fish caught that are above average when I know it should be 3. The average is 3.1.
A simple mistake.
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++; // no 'return'
}
}
return greatAvgCount;
}
if (fishCaught[i] > 3.1)
{
return greatAvgCount++;
}
First try : 4.1 > 3.1
true
returns 0 ++ which is 0 basically
You can increment the counter inside the loop and keep the return statement for the end only.
try
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++;
}
}
return greatAvgCount;
}
This line is your problem,
return greatAvgCount++;
you are incrimenting greatAvgCount then returning its initial value, there should be no "return" on this line
The aboveAverage method should be
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 3.1)
{
greatAvgCount++;
}
}
return greatAvgCount;
}
Also, you may just be doing it for debug, in which case fair enough, but hardcoding the "average" as 3.1 is generally considered bad practice. If you want average to be always 3.1 (i.e. its a global average that you've looked up from a book then its more usual to declare a static variable called double AVERAGE=3.1 and then use that where ever average is required, that way if the "book value" changes you only need to change average in one place in your code. If average is calculated from your data obviously you should use the calculated value.
Also not directly related to your problem but why are you using an array for your caught fish with a predefined maximum of 10. If you used an ArrayList you could add to it as you saw fit and it would auto expand to accommodate
private double[] fishCaught = new double[10];
becomes
private ArrayList<Double> fishCaught = new ArrayList<Double>();
I'm making a program to return a value, from two entered numbers, with one of two calculations.
But I can't get the second JButton to work. When i enter two values and click the "Get Alternative Definition", it returns nothing.
I've tested my AltDefinition Class and it is working proberly.
Can anyone help me find the problem in this code?:
public class BinomialCoefficient implements ActionListener {
private JTextField tJTextFieldResult;
private JTextField tTextNumber1;
private JTextField tTextNumber2;
public BinomialCoefficient(String pString) {
JFrame tJFrame = new JFrame(pString);
tJTextFieldResult = new JTextField("Enter value n and k. Note: 0 < k < n < 60", 20);
tTextNumber1 = new JTextField("n", 10);
tTextNumber2 = new JTextField("k", 10);
JButton tButton1 = new JButton("Get BinomialCoefficient");
JButton tButton2 = new JButton("Get Alternative Definition");
tButton1.addActionListener(this);
tButton2.addActionListener(this);
Container tContentPane = tJFrame.getContentPane();
tContentPane.add(tJTextFieldResult, BorderLayout.NORTH);
tContentPane.add(tTextNumber1, BorderLayout.WEST);
tContentPane.add(tTextNumber2, BorderLayout.EAST);
tContentPane.add(tButton1, BorderLayout.CENTER);
tContentPane.add(tButton2, BorderLayout.SOUTH);
tJFrame.pack();
tJFrame.setVisible(true);
}
public void actionPerformed(ActionEvent pActionEvent) {
String tCommand = pActionEvent.getActionCommand();
int number1 = new Integer(tTextNumber1.getText()).intValue();
int number2 = new Integer(tTextNumber2.getText()).intValue();
if (number1 > 60 || number2 > 60 || number1 <= 0 || number2 <= 0 || number1 < number2 ) {
tJTextFieldResult.setText("Please follow these conditions: 0 < k < n < 60");
} else if
(tCommand.equals("Get BinomialCoefficient")) {
try {
final double Result = Conditions.GetBiCoefficient(number1, number2);
tJTextFieldResult.setText("" + Result);
} catch (IOException e) {
e.printStackTrace();
}
if (number1 > 60 || number2 > 60 || number1 <= 0 || number2 <= 0 || number1 < number2 ) {
tJTextFieldResult.setText("Please follow these conditions: 0 < k < n < 60");
} else if
(tCommand.equals("Get Alternative Definition")) {
try {
final double Result2 = AltDefinition.GetAltDefinition(number1, number2);
tJTextFieldResult.setText("" + Result2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
You have if (tCommand.equals("Get Alternative Definition")) { inside your other if that checks if it equals "Get BinomialCoefficient".
If it ever equals "Get BinomialCoefficient", then it obviously can't equal "Get Alternative Definition". Rethink the flow of your action handler.
Edit: it actually looks like you just forgot a closing brace. This should correct it:
public void actionPerformed(ActionEvent pActionEvent) {
String tCommand = pActionEvent.getActionCommand();
int number1 = new Integer(tTextNumber1.getText()).intValue();
int number2 = new Integer(tTextNumber2.getText()).intValue();
if (number1 > 60 || number2 > 60 || number1 <= 0 || number2 <= 0 || number1 < number2) {
tJTextFieldResult.setText("Please follow these conditions: 0 < k < n < 60");
} else if (tCommand.equals("Get BinomialCoefficient")) {
try {
final double Result = Conditions.GetBiCoefficient(number1, number2);
tJTextFieldResult.setText("" + Result);
} catch (IOException e) {
e.printStackTrace();
}
} else if (tCommand.equals("Get Alternative Definition")) {
try {
final double Result2 = AltDefinition.GetAltDefinition(number1, number2);
tJTextFieldResult.setText("" + Result2);
} catch (IOException e) {
e.printStackTrace();
}
}
}