In my program that turns roman numerals into arabic numbers I have run across the error
incompatible types: java.lang.String cannot be converted into int
Here is my code
if ( Character.isDigit(TextIO.peek()) ) {
int arabic = TextIO.getlnInt();
try {
RomanNumerals N = new RomanNumerals(arabic);
TextIO.putln(N.toInt() + " = " + N.toString());
}
catch (NumberFormatException e) {
System.out.println("Invalid input.");
System.out.println(e.getMessage());
}
}
else {
String roman = TextIO.getln();
try {
RomanNumerals N = new RomanNumerals(roman);
System.out.println(N.toString() + " = " + N.toInt());
}
catch (NumberFormatException e) {
System.out.println("Invalid input.");
System.out.println(e.getMessage());
}
}
I am using BlueJ and the error is being highlighted over "(roman)"
Guesswork here... but probably your class RomanNumerals does not have a constructor taking a string as an argument like
public RomanNumerals(String r) {
Thats why calling it that way:
RomanNumerals N = new RomanNumerals(roman);
Is not permitted.
I'm looking at TextIO.putln(N.toInt() + " = " + N.toString()); and imagining that N.toInt() returns an int and the compiler is confused when you try adding " = " to it.
Try TextIO.putln(Integer(N.toInt()).toString() + " = " + N.toString());.
Related
This question already has answers here:
Java: Ternary with no return. (For method calling)
(6 answers)
Closed 4 years ago.
In userInput.equals("0") ? part both resulting expressions return void type. Why then it tells me that the expression returns String?
import java.util.Scanner;
public class BaseConverter {
private static final int SENTINEL = 0;
public static void main(String args[]) {
askInput();
}
private static void askInput() {
Scanner reader = new Scanner(System.in);
String userInput;
System.out.println("This is converter");
System.out.println("0 to stop");
while(true) {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
userInput.equals("0") ? break : System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
}
}
}
You must switch from ternary operator to if/else statement
if(userInput.equals("0")) {
break;
} else {
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
}
This code can be reduced to:
if(userInput.equals("0")) {
break;
}
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
You cannot use the ternary operator like that, instead do this:
if(userInput.equals("0")) break;
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
In your case, it's better to use use do{} while() loop like this :
do {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
} while (!userInput.equals("0"));
Which mean, repeat until userInput should equal to 0, you don't need to use break in this case.
For a better solution, you still need to use try and catch to avoid NumberFormatException :
do {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
try {
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
} catch (NumberFormatException e) {
System.out.println("Incorrect Number");
}
} while (!userInput.equals("0"));
I want to create a program that handles the 3 possible exceptions that occur when dividing two ints, asking the user to correct the input if it triggers an exception. The code only executes if no exceptions are triggered. The following code works, but I feel it is too unoptimized. Is there no other way, other than while loops, to continuously check for exceptions?
import javax.swing.JOptionPane;
public class DivisionExceptions {
public int divide(int num, int den) {
return num/den;
}
public static void main(String[] args) {
int num = 0,
den = 0,
a = 0,
b = 0,
c = 0;
DivisionExceptions div = new DivisionExceptions();
while(a == 0) {
try {
num = Integer.parseInt(JOptionPane.showInputDialog("Introduce the first int"));
a++;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
while (c == 0) {
b = 0;
while(b == 0) {
try {
den = Integer.parseInt(JOptionPane.showInputDialog("Introduce the second int"));
b++;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
try {
JOptionPane.showMessageDialog(null, "Result of dividing: " + num + "/" + den + " is " + div.divide(num, den));
c++;
}
catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
}
}
Could be simplified to:
public static void main(String[] args) {
int num = 0, den = 0;
DivisionExceptions div = new DivisionExceptions();
while(true) {
try {
num = Integer.parseInt(JOptionPane.showInputDialog("Introduce the first int"));
break;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
while (true) {
try {
den = Integer.parseInt(JOptionPane.showInputDialog("Introduce the second int"));
JOptionPane.showMessageDialog(null, "Result of dividing: " + num + "/" + den + " is " + div.divide(num, den));
break;
} catch (NumberFormatException | ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
}
~
Well your code could use some refactor.
public class DivisionExceptions {
public int divide(int num, int den) {
return num / den;
}
public static void main(String[] args) {
int num = 0,
den = 0,
a = 0,
b = 0,
c = 0;
DivisionExceptions div = new DivisionExceptions();
num = getNum(a, "Introduce the first int");
den = getNum(b, "Introduce the second int");
while (c == 0) {
try {
JOptionPane.showMessageDialog(null, "Result of dividing: " + num + "/" + den + " is " + div.divide(num, den));
c++;
} catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
}
private static int getNum( int loopParam, String message) {
int num = 0;
while (loopParam == 0) {
try {
num = Integer.parseInt(JOptionPane.showInputDialog(message));
loopParam++;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
return num;
}
}
I also allow myself to extract den calculation from while(c==0) loop, because it always calculates same value but for n times, so you gain some optimilization here. If you can provide more information about why do you predefine all of your params as 0, than perhaps I could find some solution for that while(c==0) loop. If you use java 8 you could also extract your while loop to another method and give some Function as a param.
I'm new to java and was trying to do this program. Basically entering 3 numbers, it will calculate the volume of a cube. If a negative number is typed then it will throw an exception, and also when there are more then 3 input. I wanted it to throw an exception also, if the input is not a number, but I have no idea how to store the input inside a variable and then check if it's a string and eventually throw an exception. Any suggestions? Here's my code
public class CubeVolume
{
public static void main(String [] args)
{
try
{
// try if there is more than 3 arguments
int width = Integer.parseInt(args[0]);
int depth = Integer.parseInt(args[1]);
int hight = Integer.parseInt(args[2]);
if (args.length > 3)
throw new ArrayIndexOutOfBoundsException
("You have supplied " + args.length + " arguments!");
// try if there is less than 3 arguments
if (args.length < 3)
throw new ArrayIndexOutOfBoundsException
("You have supplied " + args.length + " arguments!");
// checks if the width entered is equal or less than 0
if (width <= 0)
throw new NumberFormatException
("The argument " + width + " is a negative number!");
// checks if the depth entered is equal or less than 0
if (depth <= 0)
throw new NumberFormatException
("The argument " + depth + " is a negative number!");
// checks if the hight entered is equal or less than 0
if (hight <= 0)
throw new NumberFormatException
("The argument " + hight + " is a negative number!");
int volume = width * depth * hight;
System.out.println("The volume of a cube with dimensions " + "(" + width
+ "," + hight + "," + depth + ") " + "is " + volume);
} // try
// if there's one than more argument error will be displayed
catch (ArrayIndexOutOfBoundsException exception)
{
System.out.println("Please supply width, depth and hight arguments!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
// if a negative number is entered error will be displayed
catch (NumberFormatException exception)
{
System.out.println("Dimensions for a cube can't be negative, please "
+ "insert only positive whole numbers!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
} // main
} // CubeMain
This:
int width = Integer.parseInt(args[0]);
already throws a NumberFormatException if the String in question is not a valid string representation of an integer.
EDIT:
To address your comments:
public class CubeVolume {
private int width;
private int depth;
private int height;
public static void main(String [] args) {
if (args.length != 3) {
throw new Exception("Width, height and depth are required arguments");
}
width = Integer.parseInt(args[0]);
depth = Integer.parseInt(args[1]);
height = Integer.parseInt(args[2]);
// more stuff here
}
}
You can create your own exception class and throw the instance of that class from a method.
The exception class:
// Extending Exception makes your class throwable
class MyException extends Exception {
public MyException( String string ) {
super( string );
}
}
And for parsing the input string to integer, call a method like this :
int width = parseInt(args[0]);
where your parseInt() method throws your custom exception as follows:
private int parseInt( String number ) throws Exception {
try {
return Integer.parseInt( number );
} catch ( Exception e ) {
throw new MyException( "The input is not a number" );
}
}
Now, you can catch your custom exception MyException similar to other standard exceptions:
// catching your custom exception
catch ( MyException e ) {
System.err.println( e );
}
// if there's one than more argument error will be displayed
catch (ArrayIndexOutOfBoundsException exception)
{
System.out.println("Please supply width, depth and hight arguments!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
// if a negative number is entered error will be displayed
catch (NumberFormatException exception)
{
System.out.println("Dimensions for a cube can't be negative, please "
+ "insert only positive whole numbers!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
I've written this code to read in a file and then ask for a mark, for each name in the file. And if the mark is over 40 its a pass and below is a fail and writes each name to the corresponding file. But I get an error at line 27 which: while(namesFile.hasNext() here's my code:
import java.io.*;
import java.util.*;
public class TestResults {
public static void main(String[] args) {
String errs = "";
Scanner k = new Scanner(System.in);
try {
try (
Scanner namesFile = new Scanner(new File("Names.txt"));
PrintWriter passFile = new PrintWriter("Pass.txt");
PrintWriter failFile = new PrintWriter("Fail.txt");) {
while (namesFile.hasNext()) {
try {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
}
} // Checks to see if file is there.
catch (IOException ioe) {
System.out.println("ERROR: " + ioe.getMessage());
}
}
}
public class TestResults {
public static void main(String[] args) {
Scanner namesFile;
PrintWriter passFile;
PrintWriter failFile;
String errs = "";
Scanner k = new Scanner(System.in);
try {
try {
namesFile = new Scanner(new File("D:/Names.txt"));
passFile = new PrintWriter("D:/Pass.txt");
failFile = new PrintWriter("D:/Fail.txt");
try {
while (namesFile.hasNext()) {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
catch(IOException ioe){
System.out.println("ERROR: " + ioe.getMessage());
}
} // Checks to see if file is there.
catch (Exception e) {
}
}
}
Ok, so I have tried everything even hard coding unicode into my program, but my conditional statement won't read that a √- was matched in the TextArea. I'm writing a calculator program and I want Java to read it as NaN. It only skips over my else if statement when I'm using the TextArea itself. I tested it without the TextArea and I get NaN, but returns the number used in the TextArea.
For Example:
Test Program (without GUI) --> Runs perfectly fine outputs NaN
String Text = "√-25";
System.out.println(Text);
ArrayList<String> OP = new ArrayList();
ArrayList<Float> NUM = new ArrayList();
Scanner OPscan = new Scanner(Text).useDelimiter("[[.][0-9]]+");
Scanner NUMscan = new Scanner(Text).useDelimiter("[-+*/√]+");
int iOP = 0;
int iNUM = 0;
float Root = 0;
while (OPscan.hasNext()) {
OP.add(OPscan.next());
}
OPscan.close();
System.out.println(OP + "OP Size: " + OP.size());
while (NUMscan.hasNextFloat()) {
if (OP.get(iOP).equals("-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "+");
} else if (OP.get(iOP).equals("--")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "-");
} else if (OP.get(iOP).equals("+-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "+");
} else if (OP.get(iOP).equals("*-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "*");
} else if (OP.get(iOP).equals("/-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "/");
} else if (OP.get(iOP).equals("√-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "√");
} else {
NUM.add(NUMscan.nextFloat());
}
iOP++;
}
System.out.println(NUM + "NUM Size: " + NUM.size());
System.out.println(OP + "NUM Size: " + NUM.size());
while (OP.contains("√")) {
try {
if (OP.get(iOP).equals("√")) {
Root = (float) Math.sqrt(NUM.get(iNUM));
NUM.set(iNUM, Root);
OP.remove(iOP);
System.out.println(Root + " Root!");
}
if (OP.get(0).matches("[+-*/]+")) {
iOP++;
iNUM++;
}
} catch (IndexOutOfBoundsException IndexOutOfBoundsException) {
System.out.println("Index Error Bypassed! " + "INDEX: " + "iOP:" + iOP + " iNUM:" + iNUM + " | Size: " + "iOP:" + OP.size() + " iNUM:" + NUM.size());
iOP = 0;
iNUM = 0;
}
}
Program with GUI & TextArea outputs --> just 25
Use the Unicode representation of √
\u221A
e.g.
public static void main(String[] args) {
System.out.println("Encoding: " + System.getProperty("file.encoding"));
JTextArea area = new JTextArea(10, 30);
JScrollPane pane = new JScrollPane(area);
JOptionPane.showMessageDialog(null, pane);
String text = area.getText();
char sqrt = '\u221A';
if (text.contains(Character.toString (sqrt))) {
System.out.println("YES for " + text);
} else {
System.out.println("NO for " + text);
}
}