I'm trying to re-write this code in a cleaner way:
public static void main(String[] args) {
if(checkArgs(args) < 0) return;
return;
}
private static int checkArgs(String[] args) {
if (args.length == 0) {
System.out.println("Error: No Args");
return -1;
}
try{ //If it's a number
int myNumber = Integer.parseInt(args[0]);
System.out.println("My number is: " + myNumber);
}
catch (Exception e) {//If it's a String
try{
String[] myStr = args ;
System.out.print("My String is ");
for (int i=0; i<args.length; i++) {
myStr[i] = args[i];
System.out.print(myStr[i]);
}
System.out.print("\n");
return 0;
}
catch(Exception err){
System.out.println("Error");
return -1;
}
}
return 0;
}
The code checks the program args and tell the user if it's a String or just a number.
Any ideas on how to re-write this code without using try-catch?
First, you don't really need the second try...catch. This code:
String[] myStr = args ;
System.out.print("My String is ");
for (int i=0; i<args.length; i++) {
myStr[i] = args[i];
System.out.print(myStr[i]);
}
System.out.print("\n");
return 0;
Is not throwing any checked exception and is not very likely to ever throw a runtime exception.
Second, this code also has parts that are simply not needed - the myStr array - you assign the args array to it, and then you assign each element individually to it. And it's a local variable so it's going to go away as soon as you return anyway.
So:
System.out.print("My String is ");
for (int i=0; i<args.length; i++) {
System.out.print(args[i]);
}
System.out.print("\n");
return 0;
would do the same thing and is not going to throw exceptions.
Now, as for checking the integer - I think just using it like this and catching the exception is good enough. Just catch NumberFormatException instead of Exception. It's never a good idea to do a catch-all.
But if you insist on a method without try-catch, you could do something like this:
private static boolean checkInt(String str) {
if ( ! str.matches("-?0*[0-9]{1,10}")) {
return false;
}
long l = Long.valueOf(str);
if ( l > Integer.MAX_VALUE || l < Integer.MIN_VALUE) {
return false;
}
System.out.println("My number is: " + myNumber);
return true;
}
This first checks that you have no more than 10 digits with or without a minus sign (and any number of preceding zeros). If so, then it can be safely converted to a long, without exception checking. You can then check if the resulting long is in the range of an integer. It's a workaround that requires no try and catch, but I don't think it's better than the try-catch method.
So, with try-catch, you would have:
private static int checkArgs1(String[] args) {
if (args == null || args.length == 0) {
System.out.println("Error: No Args");
return -1;
}
try { // If it's a number
int myNumber = Integer.parseInt(args[0]);
System.out.println("My number is: " + myNumber);
} catch (NumberFormatException e) {// If it's a String
String[] myStr = args;
System.out.print("My String is ");
for (int i = 0; i < args.length; i++) {
myStr[i] = args[i];
System.out.print(myStr[i]);
}
System.out.print("\n");
return 0;
}
return 0;
}
And without it, using my checkInt() method:
private static int checkArgs2(String[] args) {
if (args == null || args.length == 0) {
System.out.println("Error: No Args");
return -1;
}
if ( ! checkInt(args[0])) {
// If it's a String
String[] myStr = args;
System.out.print("My String is ");
for (int i = 0; i < args.length; i++) {
myStr[i] = args[i];
System.out.print(myStr[i]);
}
System.out.print("\n");
return 0;
}
return 0;
}
I'm not really sure how useful your check is, though. Usually, argument checking is done in preparation for doing something with the args, and you don't save the information about whether it was a number or a string anywhere.
As mentioned in the comments your code has compilation issues. As far as logic is concerned, to find out if an input string contains only digits or not, you can use regex as shown below.
Pattern p = Pattern.compile("^-?[0-9]+$");
if(p.matcher(arg[0]).matches()) {
System.out.println("It's a number!!");
} else {
System.out.println("Not a number.");
}
In this case you don't have to use try/catch block.
Try like this...
public class CheckArgs {
public static void main(String[] args) {
if (args != null && args.length != 0) {
for (String arg : args) {
System.out.println(String.format("<----- %s ----->", arg));
System.out.println(String.format("is number %s", checkIfNumber(arg)));
System.out.println(String.format("is string %s", checkIfString(arg)));
System.out.println(String.format("<-------------->", arg));
}
}
}
private static boolean checkIfString(Object arg) {
if (arg instanceof String) {
return true;
}
return false;
}
private static boolean checkIfNumber(Object arg) {
if (arg instanceof Integer) {
return true;
}
return false;
}
}
Related
I'm making a Palindrome Generator. Basically the user inputs a word or sentence and the program outputs whether or not its a Palindrome, which is a word that is spelled the same forwards and backwards like "wow" or "racecar". My program works fine, however the output text will repeat itself like fifty times and I can't seem to figure out where the issue is without messing everything up. Help would be appreciated.
import javax.swing.JOptionPane;
public class palindromedectector {
public static void main(String[] args) {
String testStrings = "";
testStrings = JOptionPane.showInputDialog("Enter word: ");
for (int i = 0; i < testStrings.length(); i++)
{
System.out.print("\"" + testStrings + "\"");
if (isPalindrome(stripString(testStrings)))
System.out.println(" is a palindrome.");
else
System.out.println(" is not a palindrome.");
}
}
public static String stripString(String strip)
{
strip = strip.toUpperCase();
String stripped= "";
for (int i= 0; i< strip.length(); i++)
{
if (Character.isLetter(strip.charAt(i)))
stripped += strip.charAt(i);
}
return stripped;
}
public static boolean isPalindrome (String str)
{
boolean status = false;
if (str.length() <= 1)
status = true;
else if (str.charAt(0) == str.charAt(str.length()-1))
{
status = isPalindrome (str.substring(1, str.length()-1));
}
return status;
}
}
Main issue is that you run isPalindrome check for the same string in the loop, probably you wanted to run multiple checks
public static void main(String[] args) {
final int attempts = 5;
for (int i = 0; i < attempts; i++) {
String word = JOptionPane.showInputDialog("Enter word: ");
System.out.print("\"" + word + "\"");
if (isPalindrome(stripString(word))) {
System.out.println(" is a palindrome.");
} else {
System.out.println(" is not a palindrome.");
}
}
}
Also, the main functionality may be implemented in a shorter way:
// use regexp to get rid of non-letters
private static String stripString(String word) {
if (null == word || word.isEmpty()) {
return word;
}
return word.replaceAll("[^A-Za-z]", "").toUpperCase(); // remove all non-letters
}
// use Java Stream API to check letters using half of word length
private static boolean isPalindrome(String word) {
if (null == word) {
return false;
}
final int len = word.length();
if (len < 2) {
return true;
}
return IntStream.range(0, len/2)
.allMatch(i -> word.charAt(i) == word.charAt(len - 1 - i));
}
Basic problem: You are testing if the word is a palindrome testStrings.length() times, ie once for every letter in the word, rather than just once.
Remove the for loop in your main() method.
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
isPailindrome(ori);
if (isPailindrome(ori))
System.out.println(ori + "is a Pailindrome");
else
System.out.println(ori + "is NOT a Pailindrome");
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
The code works perfectly I'm just confused how I will get it to work irrespective of the case
inputted by the user. For example aBba is a palindrome but It says it's not in the code I've done. I
would like any help if possible thanks.
You can convert all of the letters to lowerCase before you start the processing.
You can write your own function or use toLowerCase() String function.
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
ori = ori.toLowerCase();
isPailindrome(ori);
if (isPailindrome(ori))
}
System.out.println(ori + "is a Pailindrome");
} else {
System.out.println(ori + "is NOT a Pailindrome");
}
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
Take the input and call toUpper(); that way when you check to see if it is a palindrome, all of the characters are uppercase.
String ori = scr.nextLint();
if(isPalindrome(ori.toUpperCase()))
//do something
Convert all the cases to lowercase/uppercase before checking the palindrome
isPailindrome(ori.toLowerCase());
Zoom in from both ends and adjust the case as required.
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len >>1; i++) {
if (Character.toLowerCase(str.charAt(i)) !=
Character.toLowerCase(str.charAt(len - i - 1))) {
return false;
}
}
return true;
}
So I have a Computer Science course at school in which we learn Java. We were assigned to do a simple text based recreation of the guessing game. I got it done until this point, and I cannot seem to find where I messed up because there is nothing printed when I run the core.
This is the code:
public class GuessGame
{
public static void main(String[] args)
{
new GuessGame();
}
public GuessGame ()
{
char end = 'y';
while (end!='y')
{
System.out.println ("Welcome to the Guessing Game!");
System.out.println ("\nThe computer has picked a number");
System.out.println ("between 1 and 100. Try to guess it.");
int num = (int)(Math.random()*(100-1)+1);
int guess = IBIO.inputInt ("Guess the number: ");
if (guess==num)
System.out.println ("You got it!");
else if (guess>num)
System.out.println ("That is too high.");
else
System.out.println ("That is too low.");
end = IBIO.inputChar ("Exit game? (y/n)");
}
}
}
By the way, IBIO is a class provided by my IB program that we use to make Input/Output statements.
This is IBIO.java:
public class IBIO
{
static void output (String info)
{
System.out.println (info);
}
static void output (char info)
{
System.out.println (info);
}
static void output (byte info)
{
System.out.println (info);
}
static void output (int info)
{
System.out.println (info);
}
static void output (long info)
{
System.out.println (info);
}
static void output (double info)
{
System.out.println (info);
}
static void output (boolean info)
{
System.out.println (info);
}
static String input (String prompt)
{
String inputLine = "";
System.out.print (prompt);
try
{
inputLine = (new java.io.BufferedReader (new java.io.InputStreamReader (System.in))).readLine ();
}
catch (Exception e)
{
String err = e.toString ();
System.out.println (err);
inputLine = "";
}
return inputLine;
}
static String inputString (String prompt)
{
return input (prompt);
}
static String input ()
{
return input ("");
}
static int inputInt ()
{
return inputInt ("");
}
static double inputDouble ()
{
return inputDouble ("");
}
static char inputChar (String prompt)
{
char result = (char) 0;
try
{
result = input (prompt).charAt (0);
}
catch (Exception e)
{
result = (char) 0;
}
return result;
}
static byte inputByte (String prompt)
{
byte result = 0;
try
{
result = Byte.valueOf (input (prompt).trim ()).byteValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static int inputInt (String prompt)
{
int result = 0;
try
{
result = Integer.valueOf (input (prompt).trim ()).intValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static long inputLong (String prompt)
{
long result = 0;
try
{
result = Long.valueOf (input (prompt).trim ()).longValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static double inputDouble (String prompt)
{
double result = 0;
try
{
result = Double.valueOf (input (prompt).trim ()).doubleValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static boolean inputBoolean (String prompt)
{
boolean result = false;
try
{
result = Boolean.valueOf (input (prompt).trim ()).booleanValue ();
}
catch (Exception e)
{
result = false;
}
return result;
}
}
Sorry for the lengthy question. Im new to Java.
The computer is doing exactly what you told it to. When GuessGame's constructor runs:
Declare end as a char local variable and initialise it to contain 'y':
char end = 'y';
Run the loop body while end does not contain 'y':
while (end!='y')
(since end does contain 'y' it does not run the loop body; it skips to the code after the loop).
The problem is that you will never enter the initial loop
char end = 'y';
while (end!='y')
You instantiate end to y, then enter only if end is not y which will always be false, hence never enter the loop.
Simply change the default value of end
char end = 'n';
Also, you don't have to cast the value 0 in your IBIO class
result = (char) 0;
You can simply do result = 0 and it will take the ASCII value.
I would also declare num and guess outside of the loop to avoid re-declaring them each time, as you did for end.
Finally, instead of declaring 7 output method with different paremeter type which simply do a System.out.println of the received parameter I would directly call System.out.println(value).
I would apply the same logic for all other methods that only call one method with the received parameter.
These two lines clearly contradict each other, the while loop will never execute. Initialize end to be a different value.
char end = 'y';
while (end!='y')
You initialize the variable char end with value 'y'.
char end = 'y';
Then the condition for your loop is
while (end!='y')
This condition is never fulfilled, that's why it's out of the loop. Change the initial value of the variable end.
The problem states the following: given a string and a character by the user find the number of times the character (given by the user) repeats itself in the string (also given by the user).
I have this piece of code
public int repeticion (int s){
int return = 0;
int cont = 0;
Scanner in = new Scanner(System.in);
System.out.println("Write a string: ");
String chain = in.next();
System.out.println("Write the character: ");
String character = in.next();
if (chain.contains(character)) {
cont = cont + 1;
}
System.out.println("The character repeats itself "+cont+"times");
return return;
But as you can see the .contains only counts the character once, not the number of times it appears in the string.
.contains() only says that a character exists within a string, not how many. You need to iterate over each character of a string to check if it equals the character you are searching for.
String chain = "your string";
int cont = 0;
for(int i=0; i<chain.length(); i++) {
if(chain.charAt(i) == character) {
cont++;
}
}
You could also repeatedly check that the character is in the string, get that index, then check the substring from after that index to the end of the string. I recommend the following:
int index = 0;
int count = 0;
while (chain.indexof(character, index) != -1 && index < chain.length()-1) {
index = chain.indexof(character, index) + 1;
count++;
}
Contains will simply tell you if the character is present. To actually count the number of times that character would appear, you'll need to iterate over the string and count the number of times the selected character appears. This method will work:
public countACharacter(char thecharacter, String stringtocountcharactersin) {
int count = 0;
for(int i = 0; i < stringtocountcharactersin.length(); i++) {
if(stringtocountcharactersin.charAt(i) == thecharacter) {
count++;
}
}
return count;
}
import java.io.*;
public class Duplicate {
public static void main(String[] args) throws IOException {
int distinct = 0;
int i = 0, j = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter STRING : -");
String s = br.readLine();
try {
for (i = 0; i < s.length(); i++) {
while (s != null) {
s = s.trim();
for (j = 0; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
distinct++;
}
}
System.out.println(s.charAt(i) + "--" + distinct);
String d = String.valueOf(s.charAt(i));
s = s.replaceAll(d, " ");
distinct = 0;
}
}
} catch (Exception e) {}
}
}
public static void chars( String a, char k)
{
String z=""+k;
int s=0;
for(int i=0;i<a.length();i++)
{
if(z.equals(a.substring(i,i+1)))
s++;
}
System.out.println(s);
}
you can achieve your goal this way you're taking the integer s without any reason and what you're doing wrong is you are using .contains() method instead of that you should compare the given char with each char of the string and use a counter for maintaining number of times of the character or you can do it this way by converting the char into a string by concatenating it with an empty string("") and then use .equals method like i have used in my code.
//With out string methods.
public static void main(String[] args) {
String ss="rajesh kumar";
Field value = null;
try {
value = String.class.getDeclaredField("value");
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// It's private so we need to explicitly make it accessible.
value.setAccessible(true);
try {
char[] values = (char[])value.get(ss);
//String is converted to char array with out string functions
for (int i = 0; i < values.length; i++) {
int count=0;
for(int j=0;j<values.length;j++)
{
if(values[i]== values[j])
{
count++;
}
}
System.out.println("\n Count of :"+values[i] +"="+count);
}
System.out.println("Values "+values[1]);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am new to java, and have been writing a program to check if a given string is periodic or not.A string is not periodic if it cannot be represented as a smaller string concatenated some number of times. Example "1010" is periodic but "1011" is not. Here is my code. It compiles, but the problem is that it tells every string is not periodic. I guess the problem is with the for loop in the isPeriodic function. Please help me get it correct.
import java.io.*;
import java.util.*;
public class Test {
/**
* #param args
*/
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader R = new java.io.BufferedReader
(new java.io.InputStreamReader(System.in));
//String st = R.readLine();
String st = "10101010";
if (isPeriodic(st) == false) {
System.out.println(" Non Periodic");
}
else {
System.out.println("Periodic");
}
}
private static boolean isPeriodic(String s)
{
String temp = s;
int i;
boolean pflag = false;
for ( i = 1; i <= (s.length()/2); i++) {
s = rotateNltr(s,i);
if (s == temp) {
pflag = true;
break;
}
}
return pflag;
}
private static String rotateNltr(String s, int n) {
if( n > s.length()) {
return null;
}
for ( int i = 0; i < n; i++) {
s = leftRotatebyOne(s);
}
//System.out.println(s);
return s;
}
private static String leftRotatebyOne(String s) {
char[] temp = s.toCharArray();
char t = temp[0];
for ( int i = 0 ; i < s.length()-1 ;i++ ) {
temp[i] = temp [i+1];
}
temp[s.length()-1] = t;
String r = new String(temp);
//System.out.println(r);
return r;
}
}
You can't compare objects (and that includes String's) with ==. You have to use the equals method.
Unlike C++ (which I assume is your language of preference) Java doesn't allow comparing String objects with the == operator. Use the equals method to compare the strings.
if (s.equals(temp)) {
pflag = true;
break;
}
In your isPeriodic() the check you are doing is wrong. Do it as below:
if (s.equals(temp)) {
pflag = true;
break;
}
s.equal(temp) alone wont solve the problem, yes it will make the code execute correctly for the input as given in Main method but for 1010, 1011 it wont.
Try using this method :
private static boolean isPeriodic(String s) {
String temp = s;
int i;
boolean pflag = false;
for (i = 1; i <= (s.length() / 2); i++) {
s = leftRotatebyOne(s);
if (s.equals(temp)) {
pflag = true;
break;
}
}
return pflag;
}
This will ensure that for all combination this program works.