Try{} Catch {} in Java is executing catch before try{} [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
I am having an issue that I cannot get rid off.
I am running the code from bellow and for this input:
*Enter cells: XXOO_OX
| X X |
| O O |
| O X |
Enter the coordinates:You should enter numbers!
Enter the coordinates:one
You should enter numbers!
Enter the coordinates:ont three
You should enter numbers!
Enter the coordinates:1 3
| X X X |
| O O |
| O X |
Process finished with exit code 0*
and after running it I get the catch message before I input the coordinates. Why? What should I change?
Scanner scanner = new Scanner(System.in);
String[][] tictactoe = new String[3][3];
//init method
System.out.print("Enter cells: ");
String s = scanner.next();
String a = s.substring(0, 1);
tictactoe[0][0] = a;
String b = s.substring(1, 2);
tictactoe[0][1] = b;
String c = s.substring(2, 3);
tictactoe[0][2] = c;
String d = s.substring(3, 4);
tictactoe[1][0] = d;
String e = s.substring(4, 5);
tictactoe[1][1] = e;
String f = s.substring(5, 6);
tictactoe[1][2] = f;
String g = s.substring(6, 7);
tictactoe[2][0] = g;
String h = s.substring(7, 8);
tictactoe[2][1] = h;
String i = s.substring(8, 9);
tictactoe[2][2] = i;
for (int n = 0; n < 3; n++) {
for (int m = 0; m < 3; m++) {
String cuv = tictactoe[n][m];
if (cuv.equals("_")) {
tictactoe[n][m] =" ";
}
}
}
System.out.println("---------");
System.out.println("| " + tictactoe[0][0] + " " + tictactoe[0][1] + " " + tictactoe[0][2] + " |");
System.out.println("| " + tictactoe[1][0] + " " + tictactoe[1][1] + " " + tictactoe[1][2] + " |");
System.out.println("| " + tictactoe[2][0] + " " + tictactoe[2][1] + " " + tictactoe[2][2] + " |");
System.out.println("---------");
String player1 = "X";
String letter;
boolean correctCoordinate=false;
while (!correctCoordinate){
System.out.print("Enter the coordinates:");
String input=scanner.nextLine();
String [] pieces = input.trim().split("\\s+");
int x;
int y;
try {
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
letter = tictactoe[3-y][x-1];
if (letter.equals("X") || letter.equals("O")) {
System.out.println("This cell is occupied! Choose another one!");
} else {
tictactoe[3-y][x-1]=player1;
System.out.println("---------");
System.out.println("| " + tictactoe[0][0] + " " + tictactoe[0][1] + " " + tictactoe[0][2] + " |");
System.out.println("| " + tictactoe[1][0] + " " + tictactoe[1][1] + " " + tictactoe[1][2] + " |");
System.out.println("| " + tictactoe[2][0] + " " + tictactoe[2][1] + " " + tictactoe[2][2] + " |");
System.out.println("---------");
correctCoordinate=true;
}
}catch (NumberFormatException err1) {
System.out.println("You should enter numbers!");
}catch (ArrayIndexOutOfBoundsException err2){
System.out.println("Coordinates should be from 1 to 3!");
}
}
Thank you,
Florin

The best way to debug your code is by stack tracing.
Try adding
catch (NumberFormatException err1) {
err1.printStackTrace();
System.out.println("You should enter numbers!");
}catch (ArrayIndexOutOfBoundsException err2){
err2.printStackTrace();
System.out.println("Coordinates should be from 1 to 3!");
}
This way you can trace your issue.
Hope it was helpful.
Have a nice day :)

Related

How can i shorten this code and make it less repetitive?

I made a simple calculator but the if statements are very repetitive and long. I am wondering what other solution I could use to shorten it and make it less repetitive. For example using a method (which i have tried but not succeeded) or any other techniques that are usable. Preferably not too advanced since I'm a beginner.
import static java.lang.System.*;
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;
public class SimpleCalc {
public static void main(String[] args) {
String operator = showInputDialog("Choose operation: " + "\n" +
"[1] = Plus" + "\n" +
"[2] = Minus" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
int c = parseInt(operator);
if (c > 4) {
showMessageDialog(null, "You cant do that.");
} else if (c == 1) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " + " + b + " = " + (a + b));
} else if (c == 2) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " - " + b + " = " + (a - b));
} else if (c == 3) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " * " + b + " = " + (a * b));
} else if (c == 4) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " / " + b + " = " + (a / b));
}
}
}
Try something like
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
switch(c) {
case 1:
showMessageDialog(null, a + " + " + b + " = " + (a+b));
break;
case 2:
...
default:
showMessageDialog(null, "You cant do that.");
Well, to start; you can move the
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
outside of the if blocks so that it only asks once before the if block, which will save you 12 lines of code.
Or you can also use methods or functions as a practice; but that wouldn't shorten your code further, really. I'd also suggest looking into Codegolf, you can learn a LOT about code-shortening.
The following will be identical, but doesn't repeat the same lines over and over. You can also use the switch statement in place of the 4 if/else if statements.
public class SimpleCalc {
public static void main(String[] args) {
String operator = showInputDialog("Choose operation: " + "\n" +
"[1] = Plus" + "\n" +
"[2] = Minus" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
int c = parseInt(operator);
if (c>4) {
showMessageDialog(null, "You cant do that.");
return;
}
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
if(c==1) {
showMessageDialog(null, a + " + " + b + " = " + (a+b));
}
else if (c==2) {
showMessageDialog(null, a + " - " + b + " = " + (a-b));
}
else if (c==3) {
showMessageDialog(null, a + " * " + b + " = " + (a*b));
}
else if (c==4) {
showMessageDialog(null, a + " / " + b + " = " + (a/b));
}
}
}
There are a couple approaches:
Put the common code into a method
Move the common code to a different part of the current method so that it is executed unconditionally.
Put the non-common code into a function / method / class that can be used to parameterize the common code.
In this case, the second approach works best; e.g.
if(c==1) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " + " + b + " = " + (a+b));
}
else if (c==2) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " - " + b + " = " + (a-b));
}
...
can be transformed into:
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
int result;
char op;
if (c == 1) {
result = a + b;
op = '+';
} else if (c == 2) {
result = a - b;
op = '-';
}
...
showMessageDialog(null, a + " " + op + " " + b + " = " + result);
(I have left a problem there for you to notice and sort out ... as a learning exercise.)
Just for fun. Factor out the stuff that's common! And handle the possibility that you'll need to implement unary operators. You'll probably also want to put it in a loop, and add an exit command.
public class SimpleCalc {
public static void main(String[] args) {
String operator = showInputDialog(
"Choose operation: " + "\n" +
"[1] = Add" + "\n" +
"[2] = Subtract" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
"[5] = Negate" + "\n");
int c = parseInt(operator);
int operand_count = 0;
switch (c) {
case 1:
case 2:
case 3:
case 4:
operand_count = 2;
break;
case 5:
operand_count = 1;
break;
default:
showMessageDialog(null, "You cant do that.");
return(-1);
}
int a = 0;
int b = 0;
if (operand_count >= 1) {
String textA = showInputDialog("Enter first number: ");
int a = parseInt(textA);
}
if (operand_count >= 2) {
String textB = showInputDialog("Enter second number: ");
int b = parseInt(textB);
}
char * opname = "";
int result = 0;
switch (c) {
case 1:
opname = "+";
result = a + b;
break;
case 2:
opname = "-";
result = a - b;
break;
case 3:
opname = "*";
result = a * b;
break;
case 4:
opname = "/";
result = a / b;
break;
case 5:
opname = "-";
result = -a;
break;
}
if (operand_count == 1) {
showMessageDialog(null, opname + " (" + a + ") = " result);
} else {
showMessageDialog(null, a + " " + opname + " " + b + " = " + result);
}
}
}

How can I format the output with System.out?

I am creating a Premier League football table in my spare time and I have come across a problem. While the program runs I want it to be perfect and output in the format I want it to, the problem is:
You enter the the Input (" HomeTeam : AwayTeam : HomeScore : AwayScore ") as follows
When you are done with the list you enter "quit" to stop the program
My issue is that the scores come out like this
(" HomeTeam | AwayTeam | HomeScore | AwayScore ")
I intend it to print like this (" HomeTeam [HomeScore] | AwayTeam [AwayScore] ")
I have tried many variations of System.out.printlns to no avail, even trying to make several Boolean conditions that will output the input in the way I want it too. I am truly at a loss and it is frustrating - I hope that someone can give me tips the code is attached
Edited for loop;
for (int i = 0; i < counter; i++) { // A loop
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + "[" + words[2].trim() + "]" + " | " + words[1].trim() + "[" + words[3].trim()) + "]";
This should work:
Scanner sc = new Scanner(System.in);
public void outputScore(String input) {
String[] words = input.trim().split("\\s+");
String satisfied = sc.nextLine();
if (satisfied.equals("quit")) {
System.out.println(words[0] + " [" + words[4] + "] | " + words[2] + " [" + words[6] + "]");
}
}
This is what the method should look like when you call it:
outputScore(sc.nextLine());
Here is the code to your edited question:
String [] product_list = new String [100];
int counter = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows:");
System.out.println("Home team : Away team : Home score : Away score");
String line = null;
while (!(line = scanner.nextLine()).equals("")) {
if (line.equals("quit")) {
break;
} else {
product_list[counter] = line;
System.out.println("Home team : Away team : Home score : Away score");
}
counter++;
}
for (int i = 0; i < counter; i++) {
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + " : " + words[2].trim() + " | " + words[1].trim() + " : " + words[3].trim());
}
Hope this helps.

Array index out of bounds exception 4 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I keep getting an error when trying to delete or display the users that I've created. Pointing to the line of code where it actually does the deletion or displaying of a certain user. I can't seem to figure out where the error is coming from.
import java.util.*;
public class contactInfo {
public static void main(String[] args) {
String tracker[][] = {
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",}
};
Scanner input = new Scanner(System.in);
int picker = 0;
while (true) {
System.out.print("Please choose an option: \n 1. Add a user \n 2. Delete a user \n 3. Display a user \n 4. Quit ");
picker = input.nextInt();
if (picker == 1) {
addUser(tracker);
} else if (picker == 2) {
deleteUser(tracker);
} else if (picker == 3) {
displayUser(tracker);
} else {
break;
}
}
}
public static String[][] addUser(String[][] add) {
Scanner input = new Scanner(System.in);
System.out.print("Which user is this information for (1 - 10): ");
int user = input.nextInt();
System.out.println(" ");
System.out.print("Enter the users first name: ");
add[user][0] = input.next();
System.out.println(" ");
System.out.print("Enter the users last name: ");
add[user][1] = input.next();
System.out.println(" ");
System.out.print("Enter the users phone number (without dashes): ");
add[user][2] = input.next();
System.out.println(" ");
System.out.print("Enter the users age: ");
add[user][3] = input.next();
System.out.println(" ");
return add;
}
public static String[][] deleteUser(String[][] del) {
Scanner input = new Scanner(System.in);
System.out.print("Which user would you like to delete?: ");
int user = input.nextInt();
for (int i = 0; i < del.length - 1; i++) {
del[user][i] = " ";
}
return del;
}
public static String[][] displayUser(String[][] displ) {
Scanner input = new Scanner(System.in);
System.out.print("Which user would you like to display?: ");
int user = input.nextInt();
for (int i = 0; i < displ.length; i++) {
System.out.print(displ[user][i] + " ");
}
return displ;
}
}
Your tracker is a 2-dimensional array. 10 rows of 4 strings each. The problem is this code:
for (int i = 0; i < del.length - 1; i++)
{
del[user][i] = " ";
}
You iterate over the array of 4 strings, but the variable i will go from 0 to 8. What you want is something like:
for (int i = 0; i < del[user].length; i++)
{
del[user][i] = " ";
}
Instead of using displ.length or del.length for you limits, use displ[user].length or del[user].length.

Skips over Print statement [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I am building something for a class Project, the code is still messy, please ignore that.
The Question i am asking is how to fix this Error:
===================================
Employee Name |
Naofumi
Hours Worked |
40
Hourly Rate |
9.75
Employee Name | // NOTICE here that is skips the input question "Employee name"
Hours Worked |
===================================
/// CODE:-----
import java.util.Scanner;
public class PayRollProject {
public static void main(String[] args) {
final double FEDERALTAX = .18;
final double STATETAX = .045;
final double HOSPITALIZATION = 25.65;
final double UNIONDUES = 7.85;
// Init. Variable
Scanner Board = new Scanner(System.in);
String[] name = new String[3];
int[] hourWages = new int[3];
double[] hourRate = new double[3];
double[] grossPay = new double[3];
double[] fedTax = new double[3];
double[] stateTax = new double[3];
double[] deductions = new double[3];
double[] netPay = new double[3];
//GP = HW * HR;
//FW = GP * .18;
int i, j, k;
// Back Door
for(k = 0; k < 3; k++) {
System.out.println();
System.out.println("Employee Name |");
name[k] = Board.nextLine();
System.out.println("Hours Worked |");
hourWages[k] = Board.nextInt();
System.out.println("Hourly Rate |");
hourRate[k] = Board.nextDouble();
System.out.println();
System.out.println();
}
// input/ calculations
for(j = 0; j < 3; j++) {
/* System.out.println();
System.out.println("Employee Name |");
name[j] = Board.nextLine();
System.out.println("Hours Worked |");
hourWages[j] = Board.nextInt();
System.out.println("Hourly Rate |");
hourRate[j] = Board.nextDouble(); */
grossPay[j] = hourWages[j] * hourRate[j];
fedTax[j] = grossPay[j] * .18;
stateTax[j] = grossPay[j] * .045;
netPay[j] = grossPay[j] - (fedTax[j] + stateTax[j] + HOSPITALIZATION + UNIONDUES);
for(i = 0; i < 3; i++) {
System.out.println("Employee | " + name[i]);
System.out.println("Hours Work | " + hourWages[i]);
System.out.println("Hourly Rate | " + hourRate[i]);
System.out.println("Gross Pay | " + grossPay[i]);
System.out.println(""); //- < Blank!
System.out.println("Deductions: ");
System.out.println("Federal Withholding | " + fedTax[i]);
System.out.println("State WithHolding | " + stateTax[i]);
System.out.println("Hospitalization | " + HOSPITALIZATION);
System.out.println("Union Dues | " + UNIONDUES);
System.out.println(" -----");
System.out.println("Total Deductions | " + deductions[i]);
System.out.println(" ");
System.out.println("NetPay | " + netPay[i]);
}
}
}
}
You've got a problem with your for loops, specifically your j loop and your i loop. The i loop is inside the j loop, and it really looks as though it shouldn't be. You should have
for(j = 0; j < 3; j++) {
/* System.out.println();
System.out.println("Employee Name |");
name[j] = Board.nextLine();
System.out.println("Hours Worked |");
hourWages[j] = Board.nextInt();
System.out.println("Hourly Rate |");
hourRate[j] = Board.nextDouble(); */
grossPay[j] = hourWages[j] * hourRate[j];
fedTax[j] = grossPay[j] * .18;
stateTax[j] = grossPay[j] * .045;
netPay[j] = grossPay[j] - (fedTax[j] + stateTax[j] + HOSPITALIZATION + UNIONDUES);
}
// the loop above is complete; now we start the next one
for(i = 0; i < 3; i++) {
System.out.println("Employee | " + name[i]);
System.out.println("Hours Work | " + hourWages[i]);
System.out.println("Hourly Rate | " + hourRate[i]);
System.out.println("Gross Pay | " + grossPay[i]);
System.out.println(""); //- < Blank!
System.out.println("Deductions: ");
System.out.println("Federal Withholding | " + fedTax[i]);
System.out.println("State WithHolding | " + stateTax[i]);
System.out.println("Hospitalization | " + HOSPITALIZATION);
System.out.println("Union Dues | " + UNIONDUES);
System.out.println(" -----");
System.out.println("Total Deductions | " + deductions[i]);
System.out.println(" ");
System.out.println("NetPay | " + netPay[i]);
}
The reason this is causing you trouble is that you're printing output for the second and third employees when you've only calculated results for the first one.
I guess this issue is due to the use of nextLine. Either use a dummy nextLine before actually reading the input. This will read and flush the input after nextxxx and then read fresh. Or you may try using next instead.
I hope that helps. There is also a same problem here

Hanging token from user input is not allowing me to proceed in my program

My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);

Categories

Resources