How to print error if nothing is put in command line? - java

If nothing is put in after java Rev, I need this statement to be printed "Enter only a three digit number, with the first digit larger than the third."
This is not being printed but an error is coming up that says:
x-10-104-10-64:Assgn Katie$ javac Rev.java
x-10-104-10-64:Assgn Katie$ java Rev
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Rev.main(Rev.java:9)
What do I need to fix?
Here is my code:
public class Rev {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
if (checkDigits(num)) {
num = subtractNum(num);
addNum(num);
} else {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}
// checks if numbers are correct
static boolean checkDigits(int number) {
int reverse = reverseNum(number);
if(number < reverse) {
throw new Error("Reverse number needs to be less than the original number!");
} else {
return true;
}
}
//reverses number
static int reverseNum(int number) {
int reverse = 0;
while(number != 0) {
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
// subtracts
static int subtractNum(int number) {
int reverse = reverseNum(number);
int total = number - reverse;
System.out.println("Reverse and subtract: ");
System.out.println(number);
System.out.println(reverse + " - ");
System.out.println("---");
System.out.println(total);
System.out.println();
return total;
}
// adds
static int addNum(int number) {
int reverse = reverseNum(number);
int total = number + reverse;
System.out.println("Reverse and add: ");
System.out.println(number);
System.out.println(reverse + " + ");
System.out.println("---");
System.out.println(total);
return total;
}
}

Check the length of args. Add something like
if (args.length != 1) {
System.err.println("Please provide a single argument.");
System.exit(1);
}
to the start of main.

You are trying to access the 0th element of the args array, which may not exist (if the program is ran without arguments). You should either verify that args has sufficient length before attempting to access the element, or handle the ArrayIndexOutOfBoundsException with a try/catch block.

Use a try/catch block with a print statement inside the catch portion to display that particular message.
public static void main(String[] args)
{
try {
int num = Integer.parseInt(args[0]);
if (checkDigits(num))
{
num = subtractNum(num);
addNum(num);
}
} catch (Exception e) {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}

Related

How to print another term at the end after the loop? In java

import java.util.Scanner;
public class PrimeNumbers {
public static boolean prime(int num) {
boolean flag = true;
for(int i=2;i<=num/2;i++) {
if(num%i==0) {
flag = false;
break;
}
}
return flag;
}
public static void main(String[] args) {
String separator = "";
Scanner scan = new Scanner(System.in);
System.out.println("First num:");
int low = scan.nextInt();
System.out.println("Second num:");
int high = scan.nextInt();
if(low>high||high<=0||low<0||(high-low) == 1) {
System.out.println("Invalid input");
System.exit(0);
}
while(low<high) {
if(prime(low)==true) {
System.out.printf(separator+"%d",low);
separator = ",";
}
low++;
}
}
}
Example:
first num:1
second num:10
Output: 1,2,3,5,7
My requirement is,I need to check the 'second num' input if its prime or not, and if it is not prime, print the next prime number.
Example:
first num:1
second num:
Output: 1,2,3,5,7,11
int lastNumber = high;
if(!prime(lastNumber))
{
while(!prime(++lastNumber));
// now you have to prime number after the high or that number itself if it
//is the prime
}
// now print all numbers and lastNumber in the last
You did num/2 if the first loop which is good for performance but you can increase
performance even more you can do int sqrt = sqrt(num) , now cast it to int and use it
int the loop
so if num is 100 in your case you will be doing 50 checks , but in sqrt case on 10
checks

Parsing a String to an Integer

So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}

how do i repeatedly multiply a number in java by 2 until it reaches 1 million?

import java.util.Scanner;
class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int testNumber = userInput.nextInt();
do{
System.out.println(newNumber * 2);
newNumber++;
}while( testNumber < 1000000);
}
}
You need to update the number after you multiply it by 2:
newNumber = newNumber * 2;
System.out.println(newNumber);
Also you are using newNumber and testNumber and newNumber doesn't appear to be defined anywhere...
}while( ***testNumber***newNumber*** < 1000000);
You need to pick one because if you are updating newNumber but comparing testNumber in your loop you will have created an infinite loop.
The code you have shown shouldn't compile unless you are leaving something out of your post.
You have the right idea with your loop, but you have multiple problems with your variables.
Your first problem is that you read in a variable from the user - testNumber, but then you are (incorrectly) manipulating a completely different variable - newNumber.
Your second problem is that you are testing the unchanged variable as your stop condition.
You probably want your loop to be something like:
do {
testNumber = testNumber * 2;
System.out.println(testNumber);
} while(testNumber < 1000000);
You can also make a recursive method for it.
public int reachMillion(int num) {
if(num<=0)
return -1; // indicating it is not possible.
if(num>=1000000) // Base Condition denoting we have reached 1 million
return num;
return reachMillion(num*2); // recursive part to multiply by 2 until we reach 1 million
}
class Main {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int newNumber = 0;
do{
System.out.println("Enter a positive number: ");
try{
newNumber = userInput.nextInt();
}catch(Exception ignored){ }
System.out.println("");
}while(newNumber <= 0);
System.out.println("----- " + newNumber + " multiply by 2 ------");
while(newNumber <= 1_000_000){
System.out.print("2 * " + newNumber +" = ");
newNumber <<= 1;//in some compilers left shift is faster than multiply
System.out.println(newNumber);
}
}
#brso05 has done well describing what went wrong here. I'd like to offer a complete example:
import java.util.Scanner;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please input a number: ");
int userInputNumber = userInputScanner.nextInt();
System.out.println();
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
Beware! That code does not handle any bad user input. For instance, if you give it 0, it will loop forever, and if you give it foo, it will crash. In case you want to handle all the edge cases of user input, this will do that:
import java.util.*;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
int userInputNumber;
//
while(true) {
System.out.print("Please input a number: ");
if (userInputScanner.hasNext()) {
// The user gave us something, but we don't know if it's a number
String rawUserInput = userInputScanner.next();
try {
userInputNumber = Integer.parseInt(rawUserInput);
// If that previous line runs, the user has given us an integer!
System.out.println();
if (userInputNumber > 0) {
// The user has given a valid number. Break out of the loop and multiply it!
break;
}
else {
// The user has given a bad number. Tell them why and ask again.
System.out.println("The number has to be greater than 0.");
}
}
catch (NumberFormatException exception) {
// The user has given us something, but it wasn't an integer
System.out.println();
System.out.println("That is not a number: " + exception.getMessage());
}
}
else {
// There is no input, so we can't do anything.
return;
}
}
// Done looping through user input
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
There is a tricky part of do-while loops. In that type of loops, do part is executed firstly. For the example below, although the input is already bigger than 1000000, it prints 1000001.
public void doWhileLoop() {
int num = 1000001;
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
Therefore, it will be a good idea to use some guard-clauses (aka, if-statements) before doing something in do-while loops. Like,
public void doWhileLoop() {
int num = 1000001;
if(num >= 1000000) {
return;
}
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}

Number comparision in java [duplicate]

This question already has answers here:
How do I check if a number is a palindrome?
(53 answers)
Closed 5 years ago.
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome.
package com.practise.examples;
import java.util.Scanner;
public class Practise
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
int revNum=0;
while(num!=0)
{
revNum=revNum *10;
revNum= revNum+ num%10;
num=num/10;
}
System.out.println("the reverse of the number is: " +revNum);
if(revNum==num)
{
System.out.println("the number is a palindrome" );
}
else
{
System.out.println("the number entered is not a palindrome");
}
}
}
Easier way:
String num=Integer.toString(s.nextInt());
String revNum = new StringBuffer(num).reverse().toString();
System.out.println("the reverse of the number is: " +revNum);
if(revNum.equals(num))
System.out.println("the number is a palindrome" );
else
System.out.println("the number entered is not a palindrome");
If you're insisting on your method:
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
int original = num;
int revNum=0;
while(num!=0)
{
revNum=revNum *10;
revNum= revNum+ num%10;
num=num/10;
}
System.out.println("the reverse of the number is: " +revNum);
if(revNum==original)
{
System.out.println("the number is a palindrome" );
}
else
{
System.out.println("the number entered is not a palindrome");
}
}
Try something like this:
public static int reverse(int num)
{
try
{
return Integer.parseInt(new StringBuilder(String.valueOf(num)).reverse().toString());
}
catch (Exception ex)
{
// Should not happen...
}
}
You have modified num for getting the reverse, and then using the same num for comparison. Use temporary variables.
your idea seems to only work in VERY specific instances, and the code itself... well, ill just give you a different idea.
create a stack and a queue.
take the original input, and add each consecutive item to each the stack and the queue.
once the queue and stack are full...
iterate until length=0
if stack.pop != queue.dequeue
palindrome=false
you can cast your number to a string and check doe's its palindrome?
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
if (isPalindrome(num+"")){
System.out.println("the number is a palindrome" );
}else{
System.out.println("the number entered is not a palindrome");
}
}
public static boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
}

java exception handling - divide by zero and divide by text method

I've been doing java for 4 months, so I'm still an amateur. Just trying to get some hwk done. Can't seem to find the right tips for getting my denominator to function well by rejecting text data and zero while keeping in a loop with error messages. Another issue is the fact my quotient is 0.0 no matter what my numerator / denominator is. Lots of problems, any advice is appreciated. Directions are as follows:
--This program takes user input for a (int) numerator and
(int) denominator then computes and displays the (double) quotient.
--If the user enters text instead of number for the numerator, display an error message explaining the issue and keep user in a loop until the correct data is entered.
--If the user enters text or a zero instead of a number for the denominator, display an error message explaining the issue and keep user in a loop until the correct data is entered.
--Messages should be descriptive with respect to the issue.
public static void main(String[] args) throws Exception {
Scanner console = new Scanner(System.in);
int n1 = 0; //number 1
int n2 = 1; //number 2..
double r = (double) n1 / n2; //quotient
String n1Str = "Please enter a real number for the numerator";
String n2Str = "Please enter a real number greater than zero for the denominator";
String errMsg = "Please enter a real number.";
String notZero = "Denominator cannot equal zero."; // not all string msgs are used, just there in case i need them.
try {
n1 = getInteger(n1Str); // validates against alphabet
if (hasNextInt()) { // working
n1 = console.nextInt();
}
} catch (InputMismatchException ime) {
}
try {
n2 = getInteger2(n2Str); // trying to validate against alphabet & zero
if (hasNextInt()) { // not working though...
n2 = console.nextInt();
}
} catch (InputMismatchException ime) {
}
System.out.println("Fraction result is " + r);
}
public static int getInteger(String message) {
Scanner console = new Scanner(System.in);
int count = 0;
boolean isValidInteger = false;
do {
System.out.println(message);
if (console.hasNextInt()) {
isValidInteger = true;
count = console.nextInt();
} else {
console.nextLine();
}
} while (!isValidInteger);
return count;
}
public static int getInteger2(String message) {
Scanner console = new Scanner(System.in);
int count = 0;
boolean isValidInteger = false;
do {
System.out.println(message);
if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but
isValidInteger = true; // can't get it to validate against text.
count = console.nextInt(); //tried switching statements and using && but get thrown into endless loop
}
} while (!isValidInteger);
return count;
}
private static boolean hasNextInt() {
return false;
}
}
You have lots of issues with your code.
For starters, you should have only one Scanner, that would exist throughout the lifespan of your application. There's no need to instantiate multiple scanners.
public class SomeClass {
private static Scanner console;
public static void main(String[] args) throws Exception {
console = new Scanner(System.in);
(...)
console.close();
}
}
Now lets look into your problematic getInteger2 method.
You should simple validate, as you do on your getIntegermethod, if the input is an integer. If it is, you process it; otherwise, you skip it using next() (not nextLine()) since you want to jump over the next complete token from this scanner.
public static int getInteger2(String message) {
int count = -1;
boolean isValidInteger = false;
do {
System.out.println(message);
if (console.hasNextInt()) {
count = console.nextInt();
if (count != 0) {
isValidInteger = true;
} else {
System.out.println("Denominator cannot equal zero.");
}
} else {
console.next();
}
} while (!isValidInteger);
return count;
}
Finally, your quotient is always being printed 0.0 since you're not updating its value before outputting it:
r = (double) n1 / n2;
System.out.println("Fraction result is " + r);
The fact that your quotient "r" is always 0.0 is because you initialize n1 to be 0 and n2=1; You should just declare the variables and initialize them down in your code; i.e when you want to get the values from the user.
It seems that you have two "main" problems in your code/logic...
Problem 1) You are not calculating r (your quotient) after you get the inputs.
So the lines:
} catch (InputMismatchException ime) {
}
System.out.println("Fraction result is " + r);
could be changed to something like:
} catch (InputMismatchException ime) {
}
r = (double) n1 / n2; //calculate the quotient
System.out.println("Fraction result is " + r);
Problem 2)
Your code:
do {
System.out.println(message);
if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but
isValidInteger = true; // can't get it to validate against text.
count = console.nextInt(); //tried switching statements and using && but get thrown into endless loop
}
} while (!isValidInteger);
return count;
could be changed to something like this, if you don't want to change too much in your code:
do {
System.out.println(message);
try {
if ((count = console.nextInt()) != 0) {
isValidInteger = true;
}
} catch (InputMismatchException ime) {
return getInteger2(message);
}
} while (!isValidInteger);
return count;
so that only if the input in console is an int you read it with nextInt() and store it in count. In your code you would read the int with nextInt() and if it is an int you read it again with nextInt(), which causes the user to write in 2 ints as well as your issue that you read the int before checking that it is an int which causes the InputMismatchException to be thrown. In the code I sent you, if the read number is an int AND not 0 then it is returned, if it is 0 your loop runs again and if it isn't an int at all the the method is simply called again (see Recursion).
I hope this helps you understand the issues.
The best way, however, would probbaly be do redesign your code a bit.

Categories

Resources