Delete else statement but requires else statment - java

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.

Related

Is there any other method I can use to read lines in my code to perform the function of a readLine()?

I am writing a code to count the lines of code with the exception of comments and empty lines but I am stuck at what to use in place of readLine() method with the text variable as it is used only with the BufferedReader class. I do not want to use BufferedReader. I want it to remain String. What can I do to solve this problem?
public static int count(String text) {
int count = 0;
boolean commentBegan = false;
String line = null;
while ((line = text.readLine()) != null) {
line = line.trim();
if ("".equals(line) || line.startsWith("//")) {
continue;
}
if (commentBegan) {
if (commentEnded(line)) {
line = line.substring(line.indexOf("*/") + 2).trim();
commentBegan = false;
if ("".equals(line) || line.startsWith("//")) {
continue;
}
} else
continue;
}
if (isSourceCodeLine(line)) {
count++;
}
if (commentBegan(line)) {
commentBegan = true;
}
}
return count;
}
private static boolean commentBegan(String line) {}
private static boolean commentEnded(String line) {}
private static boolean isSourceCodeLine(String line) {}
The text.readLine() that I wrote above does not correlate with I should be done as it is giving an error, I have witten the full code for commentBegan(), commentEnd(), and isSourceCodeLine() methods. All I just need is to solve the problem of readLine() method.
My suggestion is to identify the lines before the loop, and change its mechanism:
public static int count(String text) {
int count = 0;
boolean commentBegan = false;
String[] lines = text.split(System.getProperty("line.separator"));
for (String line:lines) {
//your logic here
}
}
Splitting the text by the line.separator would return all lines inside it, stored in an array. Iterate through it and use your own logic there.

Making Palindrome(if possible) by filling missing characters

I've been working with a program recently in java which compiles successfully but during execution,after i enter the string, nothing gets displayed, allowing me to type anything on the execution page.The program goes like this:- The user enters a string with a couple of missing letters represented by '.'(a full stop).
The program should fill in those full stops to make a smallest (lexicographically) palindrome word. If this is not possible....display not possible to make a palindrome. Please tell me if i've gone wrong anywhere. Thank you :)
import java.io.*;
public class JavaApplication {
static String s;
//main method
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string with '.' as their missing characters:");
s=br.readLine();
int len=s.length();
String result;
if(len%2==0){
result=even();
}
else
result=odd();
System.out.println(result);
}
//Function to handle odd no. of characters
static String odd(){
int len=s.length();
int mid=(len-1)/2;
for(int i=1;i<=mid;i++){
if(s.charAt(mid-i)=='.'||s.charAt(mid+i)=='.'){
if(s.charAt(mid)=='.'){
s=s.substring(0,mid)+'a'+s.substring(mid+1);
}
if(s.charAt(mid-i)=='.'&&s.charAt(mid+i)=='.'){
s=s.substring(0,(mid-i))+'a'+s.substring((mid-i)+1,mid)+s.charAt(mid)+s.substring(mid+1,mid+i)+'a'+s.substring((mid+i)+1);
}
if(s.charAt(mid-i)=='.'){
s=s.substring(0,mid-i)+s.charAt(mid+i)+s.substring((mid-i)+1);
}
if(s.charAt(mid+i)=='.'){
s=s.substring(0,(mid+1))+s.charAt(mid-i)+s.substring((mid+1)+1);
}
}
}
String result=checkPalindrome();
return result;
}
//Function to handle even no. of characters
static String even(){
int len=s.length();
int mid2=len/2,mid1=mid2-1;
for(int i=0;i<mid2;i++){
if(s.charAt(mid1-i)=='.'||s.charAt(mid2+i)=='.'){
if(s.charAt(mid1-i)=='.'&&s.charAt(mid2+i)=='.'){
s=s.substring(0,mid1-i)+'a'+s.substring((mid1-i)+1,mid2+i)+'a'+s.substring((mid2+i)+1);
}
if(s.charAt(mid1-i)=='.'){
s=s.substring(0,mid1-i)+s.charAt(mid2+i)+s.substring((mid1-i)+1);
}
if(s.charAt(mid2+i)=='.'){
s=s.substring(0,mid2+i)+s.charAt(mid1-i)+s.substring((mid2+i)+1);
}
}
}
String result=checkPalindrome();
return result;
}
//Check if s is palindrome
static String checkPalindrome(){
String s1=s;
for(int i=0;i<s1.length();i++){
char ch=s1.charAt(i);
s1=ch+s1;
}
if(s1.equals(s))
return s1;
else{
s1="cannot form any palindrome";
return s1;
}
}
}

Consume bad data in text file java

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...

My Java Program won't Compile

As I just stated above this program won't compile. In my IDE, TextPad, it gives me 2 errors in the createArray method. It says that both a right bracket and semicolon are expected in my return statement when I indeed have them there. Could someone help me out here?
public class Driver
{
private static int size;
private static String somePromptMessage;
private static boolean validInput;
private static String userData;
public static void main(String[] args) throws IOException
{
validInput = false;
BufferedReader keyboard;
keyboard = new BufferedReader(new InputStreamReader(System.in));
int result;
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
{
return result;
}
}
public static void print(int[]x)
{
System.out.println("The array contains" + size + "elements");
for(int i = 0; i<x.length; i++)
{
System.out.println(x[i]);
}
}
private static int[] createArray(int size)
{
return int[size];
}
You're missing the enclosing } for the class, but I'll assume that one is a copy-paste issue.
The actual problem I see is that you want
return new int[size];
instead of
return int[size];
in your createArray function.
I see an extra simi-colon here:
while(!validInput);
{
return result;
}
Update: It was brought to my attention that this is actually a do while so why the extra braces around the return statement?
remove braces after while across return result; as it is do-while:
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
return result;

What are helper objects in java?

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();
}
}
}
}

Categories