The point of this program is to take a three digit number from the command line and then reversing it. After that it is supposed to subtract the reverse from the original number and add the original to the reversed.
This is supposed to only take numbers that are three digits and the first digit of the number has to be greater than the last so that it is not negative when the numbers are subtracted.
The code compiles correctly but when I put a number in the command line prints out the line "Enter a three digit number, with the first digit larger than the third" only.
What it is supposed to print out like
$ java Rev 351
Reverse and subtract:
351
153 -
---
198
Reverse and add:
198
891 +
---
1089
This is my code:
public class Rev
{
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
num = Integer.parseInt(args[i]);
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
static boolean checkDigits(int number) // checks if numbers are correct
{
int reverse = reverseNum(number);
if(number > reverse)
{
throw new Error("Reverse number needs to be less than the original number!");
}
else
{
return true;
}
}
static int reverseNum(int number) //reverses number
{
int reverse = 0;
int r = 0;
while (number != 0)
{
if(number < 1000 || number > 99)
{
r = number % 10;
reverse = (reverse*10) + r;
number = number/10;
}
}
return reverse;
}
static void subtractNum(int number) // subtracts
{
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();
number = total;
}
static void addNum(int number) // adds
{
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);
number = total;
}
}
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
num = Integer.parseInt(args[i]);
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
So the args variable is the command line argument. So if you're compiling via command line, you would call something like java Rev.class 321 where 321 is your 3 digit number. If you want to use the Java console to take inputs, use a Scanner.
To take inputs, use something like this:
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
You're never actually getting a number from the input. You need to do this in your main():
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
try (Scanner s = new Scanner(System.in)){
num = s.nextInt();
}
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
The Scanner reads the main input stream (from the keyboard). Otherwise, when you pass in the argument on the command line, it hasn't yet asked you for the input, and prints out the request for input.
Your other problem is that you don't call checkDigits() after getting your number, so you should probably do a while loop using it until you get a number you'll accept, like this:
public static void main(String[] args)
{
int num = -1;
while (num < 0 || !checkDigits(num)){
System.out.println("Enter a three digit number, with the first digit larger than the third");
try (Scanner s = new Scanner(System.in)){
num = s.nextInt();
}
}
reverseNum(num);
subtractNum(num);
addNum(num);
}
Also, your other methods are incorrect in that they are acting on an input parameter (which is possible for objects but not primitives, and is bad practice in any case).
Instead write them as functions which take in values and return them, then modify your main again to look like this:
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");
}
}
Related
I'm new to java, got an assignment about converting binary to decimal.
here's my code
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
It's already done but the teacher request "Use scanner class inside a while loop for users to enter the binary number one by one. A “-1” would stop the loop."
Does anyone know how to change my code?
Use another while loop and keep iterating until the user inputs -1.If user inputs -1 use break to come out of while loop
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
if(num ==-1){
break;
}
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
}
Your task consists of two parts: iterated input-check-process cycle and the process itself.
The former is simply solved with a loop:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
// TODO
}
}
This repeats asking for input data, reading it, testing for a special 'terminate' value and exits eventually if one is found.
The second part can be solved as follows: scan input digits one by one; each new digit found becomes a new least-significant bit of a number being constructed, while all preceding digits become one position more significant than they were.
That means, whenever you find a new digit, the number gets doubled and the value of a new digit gets added:
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
Together they make:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
}
}
Of course, for a real-life program we should also validate input, ie. test if it consists of digits 0 and 1 only, whether it's not empty or not too long (so that the result of conversion fits the values range of type int).
I'm trying to ask the user for two two-digit numbers and then perform a length check and a type check on both of the numbers, then I want to output the sum of the numbers. Here's what I have so far:
package codething;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = number.nextInt();
if(number.hasNextInt()) {
} else {
System.out.println("Error");
}
int m;
int length = String.valueOf(number).length();
if (length == 2) {
} else {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
Scanner number1 = new Scanner(System.in);
System.out.println("Enter another two digit number (10-99) ");
m = number.nextInt();
if(number1.hasNextInt()) {
m = number1.nextInt();
} else {
System.out.println("Error");
}
int sum = n + m;
System.out.println(sum);
}
}
At the moment my program won't even ask me for my second input. Not sure what to do :/
So several things:
-Don't construct more than one Scanner objects to read from System.in. It just causes problems.
-You're using String.valueOf() to convert an int to a String. It is better to simply check to make sure it is between 10 and 99.
-You check to make sure that the Scanner has a next int after you call nextInt which won't help. You need to make sure that there is a next int.
-A lot of your if statements have an empty if block and then you do something in the else. You can just do the opposite in the if and omit the else (Instead of if(length ==2) {} you can do if(length != 2) {//code}
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
if(number.hasNextInt()) {
n = number.nextInt();
} else {
number.next(); //Clear bad input
System.out.println("Invalid");
}
int m = 0;
if ( n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
m = number.nextInt();
} else {
number.next();
System.out.println("Invalid");
}
if (n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);
Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}
I am have a program which prints off the fibonacci sequence up to a given input. The user puts in a number and it prints out the sequence up to that many numbers.
ex: input = 4 prints 1 1 2 3
I want to limit the program to only allowing an input 1-16. The way I have it now will print the sequence an then prints the error message? Any suggestions? Thank you
public class FibonacciGenerator
{
private int fibonacci = 1;
public FibonacciGenerator()
{
}
public int Fibonacci(int number)
{
if(number == 1 || number == 2)
{
return 1;
}
else if (number > 16)
{
System.out.println("Error must select 1-16");
}
else
{
int fib1=1, fib2=1;
for(int count= 3; count < 17 && count <= number; count++)
{
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
}
return fibonacci;
}
}
Here is my main method:
import java.util.Scanner;
public class FibonacciPrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer 1-16: ");
int input = in.nextInt();
FibonacciGenerator newNumber = new FibonacciGenerator();
System.out.println("Fibonacci sequence up to " + input + " places.");
for(int fibCount = 1; fibCount <= input; fibCount++)
{
int sequence = newNumber.Fibonacci(fibCount);
System.out.print(sequence);
}
}
}
As a recommendation don't make your methods or variables start with capital letter, capital letter is used by convention for Classes only.
Also, you should validate input variable before passing it to your method.
I mean:
if (input > 16 || input < 1) {
System.out.println("Enter a number between 1-16");
}
else {
for(int fibCount = 1; fibCount <= input; fibCount++)
{
int sequence = newNumber.Fibonacci(fibCount);
System.out.print(sequence);
}
}
In your Fibonacci function, your first line should be an if statement to see if the number is greater than 16. If it is, then you can throw an error.
Below is what it should be:
public int Fibonacci(int number) {
if (number > 16 || number < 1) throw new IllegalArgumentException("Error. Must select 1-16.");
// Rest of the code
}
In your Fibonacci function, for number not equal to 1 and 2. The return statement return fibonacci; will always be called. That's why the error message is printed with the sequence.
To avoid this, you can use #Frakcool method to validate variable input before passing it to Fibonacci function. Alternatively, you may use do-while loop to do this (force the user to retry).
do{
System.out.print("Enter an integer 1-16: ");
input = in.nextInt();
if (input<1 || input>16)
System.out.println("Error. Must select within 1-16.");
}while(input<1 || input>FibonacciGenerator.upper_limit);
Some other suggestion:
Make your methods and variables name start with a lower case letter
To avoid repeat calculation (for-loop in Fibonacci method), use integer array to store the fibonacci values and pass integer array instead of integer (for small input number such as 16). Another way is to set two more global variables to store the last and second last calculated values.
Make upper limit (and/or lower limit) as a global variable for better maintenance
public static int upper_limit = 16;
and get it in other class as
FibonacciGenerator.upper_limit
I have tried various techniques to check the values of user input in this method. The user should only be able to enter a '1' or a '0'. If any other input is used there should be an error message and the program exits. Any ideas? I got it to work for the first digit but not the second through the tenth.
System.out.println("Enter a ten digit binary number. Press 'Enter' after each digit. Only use one or zero. :");
binary[0] = keyboard.nextInt();
for (index = 1; index < 10; index++)
binary[index] = keyboard.nextInt();// fill array with 10 binary
// digits from user. User
// must press 'Enter' after
// each digit.
Try this:
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext())
{
final String input = scanner.next();
try
{
int num = Integer.parseInt(input, 2);
}
catch (NumberFormatException error)
{
System.out.println(input + " is not a binary number.");
//OR You may exit here, if you don't want to continue
}
}
Try this code part :
import java.util.Scanner;
public class InputTest
{
public static void main(String... args) throws Exception
{
Scanner scan = new Scanner(System.in);
int[] binary = new int[10];
for (int index = 0; index < 10; index++)
{
int number = scan.nextInt();
if (number == 0 || number == 1)
{
binary[index] = number;
System.out.println("Index : " + index);
}
else
System.exit(0);
}
}
}