I´m having a question about my program. I´m trying to figure out, how i can check if the s.nextLine() input form a user is only holding ints form 1 to 49 in it or also letters.
I know that the "eingabe" is a string so I can’t just use an if right?
My problem is, that I´m relative new in programming with java and i have no idea for a solution. :/
Maybe you can help me that would be great!
public static int Scanner() {
Scanner s = new Scanner(System.in);
String eingabe = s.nextLine();
//???
return eingabe;
}
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class MyClass {
public static void main (String[] args) {
try {
int x = Scanner();
if(x >= 1 && x <= 49) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
catch(java.lang.NumberFormatException e) {
System.out.println(e);
}
//Second Method Using Regex.
try {
int x = useRegex();
if(x >= 1 && x <= 49) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
} catch(java.lang.NumberFormatException e) {
System.out.println(e);
}
}
public static int Scanner() {
Scanner s = new Scanner(System.in);
String eingabe = s.nextLine();
return Integer.parseInt(eingabe);
}
public static int useRegex() {
Scanner s2 = new Scanner(System.in);
String eingabe = s2.nextLine();
Pattern p = Pattern.compile("^[\\+-]?\\d+$");
Matcher m = p.matcher(eingabe);
boolean b = m.matches();
if(b) {
return Integer.parseInt(eingabe);
}
else {
throw new java.lang.NumberFormatException();
}
}
}
Here I am using try catch block to handle if the input format is wrong. If it is wrong then the Exception
java.lang.NumberFormatException
will occur and then if it is a valid number then I am checking whether it is between 1 and 49. Integer.parseInt(num) is used to convert a String into number.
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String).
Try catch is used to handle to exceptions without . See here
By using regex also I have mentioned. See this for regex
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I would like to be able to tell for sure when the compiler throws an exception with no output and when it's going to execute a few lines of code followed by an exception.
To further illustrate my point, consider the following code:
public class OverAndOver {
static String s = "";
public static void main(String[] args) {
try {
s += "1";
throw new Exception();
} catch (Exception e) { s += "2";
} finally { s += "3"; doStuff(); s += "4";
}
System.out.println(s);
}
static void doStuff() { int x = 0; int y = 7/x; }
}
A quick glance at the doStuff() method and you know the compiler is going to throw a Divide-by-zero exception.
Now, here's my question though (and the source of my confusion): Why didn't the compiler displayed "123" followed by the exception? And most importantly, how can I be able to tell for sure when the compiler is going to execute a few lines of code before throwing an exception and when it's going to throw an exception right away with no output?
Why didn't the compiler displayed "123" followed by the exception?
First of all, the compiler doesn't execute the code, so it will never display those values.
If you wonder why your app didn't display the text before the exception, the answer is that you didn't print it: you just append it to a string, and you print the string after the finally block.
The finally block throws an exception and your print statement will never be reached.
Try to print the text directly:
public class OverAndOver {
public static void main(String[] args) {
try {
System.out.println("1");
throw new Exception();
} catch (Exception e) {
System.out.println("2");
} finally {
System.out.println("3");
doStuff();
System.out.println("4");
}
}
static void doStuff() {
int x = 0;
int y = 7 / x;
}
}
The output will be:
1
2
3
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at com.jedisoftware.lf_delivery_tracking.OverAndOver.doStuff(App.java:74)
at com.jedisoftware.lf_delivery_tracking.OverAndOver.main(App.java:67)
Why didn't the compiler displayed "123" followed by the exception?
Because System.out.println(s); instruction is never executed.. Exception is raised in the doStuff(); method and the execution of main method is interrupted.
If you want to display 123 before the exception you should put the System.out.println(s); instruction before the doStuff() method as follows:
public class OverAndOver {
static String s = "";
public static void main(String[] args) {
try {
s += "1";
throw new Exception();
} catch (Exception e) { s += "2";
} finally { s += "3"; System.out.println(s); doStuff(); s += "4";
}
}
static void doStuff() { int x = 0; int y = 7/x; }
}
You call doStuff() which may throw an unchecked exception outside of a try block. If you want to print both the exception and the string you must wrap the doStuff() call in a try-catch construct.
public class OverAndOver {
static String s = "";
public static void main(String[] args) {
try {
s += "1";
throw new Exception();
} catch (Exception e) { s += "2";
} finally {
try{
s += "3"; doStuff(); s += "4";
}catch(ArithmeticException e){
e.printStackTrace();
}
}
System.out.println(s);
}
static void doStuff() { int x = 0; int y = 7/x; }
}
So basically I'm doing a java tutorial but in order to follow along I need to make a class file. Everything was already given to me but it gives me an error. The error is: Delete else statement or something along those lines. But when I delete it it tells me to put another else statement there.
The code is : Is this a problem with eclipse or is there something wrong with the code?
import java.io.*;
import java.text.*;
public class In {
static InputStreamReader r = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(r);
// Read a String from the standard system input
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
return "";
}
}
// Read a number as a String from the standard system input
// and return the number
public static Number getNumber() {
String numberString = getString();
try {
numberString = numberString.trim().toUpperCase();
return NumberFormat.getInstance().parse(numberString);
} catch (Exception e)
{
// if any exception occurs, just return zero
return new Integer(0);
}
}
// Read an int from the standard system input
public static int getInt() {
return getNumber().intValue();
}
// Read a long from the standard system input
public static long getLong() {
return getNumber().longValue();
}
// Read a float from the standard system input
public static float getFloat() {
return getNumber().floatValue();
}
// Read a double from the standard system input
public static double getDouble() {
return getNumber().doubleValue();
}
// Read a char from the standard system input
public static char getChar() {
String s = getString();
if (s.length() >= 1)
return s.charAt(0);
else
return’\ n’;
}
}
What is actually causing the error here is that whatever messed up marks you have around \n are not apostrophes... I have no idea what they are. After rewriting the code exactly as you did, except with apostrophes (plus using curly braces in the if and else statements because I prefer it that way), there were no errors:
public static char getChar ()
{
String s = getString();
if (s.length() >= 1){
return s.charAt(0);
}else{
return '\n';
}
}
Please, in the future, make sure to use correct indentations in your questions to make it much easier for us to read.
import java.io.*;
import java.util.*;
public class DemoEx {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("BP.txt"));
int badData = 0;
int goodData = 0;
while (in.hasNext()) {
try {
int value = in.nextInt();
if (value < 0)
throw new BPIllegalValueException("value cannot be less than zero");
else goodData++;
} catch (InputMismatchException ex) {
// Consume badData
badData++;
} catch (BPIllegalValueException ex) {
badData++;
}
}
System.out.println("gooddata" + goodData);
System.out.println("baddata" + badData);
}
}
public class BPIllegalValueException extends Exception {
BPIllegalValueException(String message){
System.out.println(message);
}
}
I'm writing a program the reads a txt file and then outputs the number of pieces of "good" and "bad" data with good data being any non-negative integer number and bad data being anything else.
However, I'm not sure how to consume and move to the next piece of data if my program encounters a string.
Loop with a check on encountering the int:
if (in.hasNextInt()) {
... all
} else {
++badData();
in.next();
}
What do You mean by "consume"? You propably want to advance to another token. Reading the documentation should give You the answer:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
next() method will allow You to go to a next token...
I come across few of the times called helper objects... can anybody elaborate what are those helper objects and why do we need them?
Some operations which are common to a couple of classes can be moved to helper classes, which are then used via object composition:
public class OrderService {
private PriceHelper priceHelper = new PriceHelper();
public double calculateOrderPrice(order) {
double price = 0;
for (Item item : order.getItems()) {
double += priceHelper.calculatePrice(item.getProduct());
}
}
}
public class ProductService {
private PriceHelper priceHelper = new PriceHelper();
public double getProductPrice(Product product) {
return priceHelper.calculatePrice(product);
}
}
Using helper classes can be done in multiple ways:
Instantiating them directly (as above)
via dependency injection
by making their methods static and accessing them in a static way, like IOUtils.closeQuietly(inputStream) closes an InputStream wihtout throwing exceptions.
at least my convention is to name classes with only static methods and not dependencies XUtils, and classees that in turn have dependencies / need to be managed by a DI container XHelper
(The example above is just a sample - it shouldn't be discussed in terms of Domain Driven Design)
These are objects that "sit to the side" of the main body of code, and do some of the work for the object. They "help" the object to do it's job.
As an example, many people have a Closer helper object. This will take various closeable objects, for example, java.sql.Statement, java.sql.Connection, etc and will close the object, and ignore any errors that come out of it. This tends to be because if you get an error closing an object, there is not much you can do about it anyway, so people just ignore it.
Rather than having this boilerplate:
try {
connection.close();
} catch (SQLException e) {
// just ignore… what can you do when you can't close the connection?
log.warn("couldn't close connection", e);
}
scattered around the codebase, they simply call:
Closer.close(connection);
instead. For example, look at guava closeQuietly.
A 'helper' method is typically a method to make something easier, whatever it is. Sometimes they're used to make things more readable/clearly organized (some may argue this, but it's ultimately very subjective):
public void doStuff() {
wakeUp();
drinkCoffee();
drive();
work();
goHome();
}
Where, each 'helper method' on their own are fairly complex... the concept becomes really clear and simple.
Another very good use of helper methods is to provide common functionality across many different classes. The best example of this is the Math class which contains a ton of static helper methods to help you calculate things like the log of a number, the exponent of a number... etc.
Where you draw the line as to what's a helper method and what's just a regular method is pretty subjective, but that's the gist of it. Other answers here are pretty good too.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Helpers {
public static String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
return dateFormat.format(new Date());
}
public static boolean isTimeABeforeTimeB(String timeA, String timeB) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
Date dA = dateFormat.parse(timeA);
Date dB = dateFormat.parse(timeB);
if (dA.getTime() < dB.getTime()) {
return true;
} else {
return false;
}
} catch (Exception e) {
//
}
return false;
}
public static String getDateAndTimeInput(String prompt) {
Scanner input = new Scanner(System.in);
String ans;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
dateFormat.setLenient(false);
boolean dateValid;
do {
System.out.print(prompt);
ans = input.nextLine();
ans = ans.trim();
dateValid = true;
try {
Date d = dateFormat.parse(ans);
} catch (Exception e) {
dateValid = false;
}
} while (!dateValid);
return ans;
}
public static String getStringInput(String prompt) {
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print(prompt);
ans = input.nextLine();
ans = ans.trim();
} while (ans.length() == 0);
return ans;
}
public static double getDoubleInput(String prompt) {
Scanner input = new Scanner(System.in);
double ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
//Convert string input to integer
try {
ans = Double.parseDouble(s);
inputValid = true;
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
public static int getIntegerInput(String prompt) {
Scanner input = new Scanner(System.in);
int ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
// Convert string input to integer
try {
ans = Integer.parseInt(s);
inputValid = true;
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
public static int getIntegerInput(String prompt, int lowerBound, int upperBound) {
Scanner input = new Scanner(System.in);
int ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
// Convert string input to integer
try {
ans = Integer.parseInt(s);
if (ans >= lowerBound && ans <= upperBound) {
inputValid = true;
} else {
inputValid = false;
}
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
}
that is an example of of a Helper Class. It contains method which of are common use of the other classes in the project.
Example if someone wants to enter an Integer number from a class hew ill have to type in this: String num = Helpers.getIntegerInput("input your number");
The prompt is the output that is show to the user. Other examples to input a String, double, date and time etc.
Helper class, in my opinion, is similar to normal functions declared outside of classes in C++. For example, if you need a global constant for many classes, then you can define a helper class that encloses a final static const variable.
You can see a helper class as a toolbox that can be used by other classes to perform task like testing if a string is a palindrome, if a given number is prime, if an array contains negative number etc. You can create helper class by making all its methods static and its constructor private, and optionally you can also make the class final. Thus it can not be instantiated and one can easily access to all its methods directly.
public final class HelperClass{
private HelperClass(){
}
public static boolean isPositive(int number) {
if (number >= 0)
return true;
else
return false;
}
}
Here the function can be use directly to test a number :
HelperClass.isPositive(5);
this helper class help you to validate multiple edit text fields at once
public class MyHelperClass {
public void toast(Context context, String message){
Toast toast=new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setText(message);
toast.show();
}
public void validateEditText(Context context,List<EditText> editTextList)
{
boolean result=false;
for (int i=0;i<editTextList.size();i++)
{
if (editTextList.get(i).getText().toString().trim().equals(""))
{
result=true;
toast(context," Required fields are not empty !");
i=editTextList.size();
}
}
}
}