I am going to post my code below because this is kind of hard to describe. The code below works, but it is using Math.pow in the main method rather than in the helper, so if someone could show me a way to move the power to the helper method without messing up the program that would be much appreciated.
Main method:
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer: ");
double input = keyboard.nextInt();
double x = Math.pow(2.0, input);
int n = (int)x;
System.out.println(starStr(n));
Helper method:
public static String starStr(int n)
{
if (n >= 1) {
return ("*" + starStr(n-1));
}
else {
return "";
}
}
EDIT:
if(n == 0) {
return "*";
}
else {
return starStr(n - 1) + "**";
}
Something like this would work. You don't really need to use a power function at all. Just start with 1 star and double the number of stars in every step of the recursion.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer for the number of stars: ");
int input = keyboard.nextInt();
System.out.println(doStars(input));
}
public static String doStars(int n)
{
//If n == 0 the recursion is done
//Otherwise, reduce n by 1 and double the number of stars
if(n == 0)
return "*";
else
{
String output = doStars(n - 1);
return output + output;
}
}
I think this is what you are looking for. Not sure if you have learned the tree data-structure, but that's the purpose of my variable names.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
// 1 + (2^n)-1 = 2^n
System.out.println("*" + doStars(i));
}
}
public static String doStars(int n)
{
if (n == 0) {
return "";
}
else {
String subTree = doStars(n - 1);
return subTree + "*" + subTree; // length = (2^n)-1
}
}
}
Output
*
**
****
********
****************
Visualization - read clockwise in triangles from little to big
"*"
+
doStars(2)
"*"
doStars(1) + doStars(1)
"*" "*"
doStars(0) + doStars(0) doStars(0) + doStars(0)
"" "" "" ""
Related
I'm new to java and I'm tinkering with my code and decided to create an input validation method, my problem is how am I going to loop the input through the validations.
First I decided to take the input as string to do a try/catch with a double, no problem with that, now I need to test the input if it's in the range of 0-100. Of course I wanted to check if the user will type in a double in the "range check". What I wrote somewhat worked but when the input passed the data type validation but not the range check, it will still return the first double, whatever I typed next.
public static double check(String n){
boolean done = false;
double i=0.0;
Scanner beep = new Scanner(System.in);
while (!done) {
try {
i = Double.parseDouble(n);
done = true;
} catch (Exception e) {
System.out.print("Please input a valid grade (0-100): ");
n = beep.nextLine();
}
}
double b = rangetest(i);
return b;
}
public static double rangetest (double n){
if (n > 100 || n < 0){
System.out.print("0-100 only ");
Scanner beep = new Scanner(System.in);
check(beep.next());
}
return n;
}
public static void main(String[] args) {
Scanner beep = new Scanner(System.in);
double ave = 0.0;
int rounded;
for (int i = 1; i <= 5; i++)
{
System.out.print("Input grade number " + i + " : ");
ave += rangetest(check(beep.next()));
}
ave /= 5;
rounded = (int)Math.round(ave);
}
Is there any easier methods or workarounds? Or am I doing it all wrong? Cheers!
Beware of Scanner#next, this can leave a dangling new line character in the buffer which can mess with your workflows, however, the core issue is with your rangetest
public static double rangetest (double n){
if (n > 100 || n < 0){
System.out.print("0-100 only ");
Scanner beep = new Scanner(System.in);
check(beep.next());
}
return n;
}
Here, if the value is not within the specified range, you're calling check again, but you're ignoring the result, so you end up returning the original value of n
It would seem that instead, you want to do...
n = rangetest(check(beep.next()))
within the if block.
You could accomplish something similar using do-while loops, for example...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Double value = getDoubleWithinRange(scanner, "Make me an offer ([X] to exit): ", "That's not a reasonable offer", "X", 0, 100, "Value is not within a valid range (0-100)");
if (value != null) {
System.out.println("You mad an offer of " + value);
}
}
public static Double getDoubleWithinRange(Scanner input, String prompt, String errorMessage, String exitValue, double min, double max, String rangeErrorMessage) {
boolean done = false;
Double value = null;
do {
value = getDouble(input, prompt, errorMessage, exitValue);
if (value != null) {
if (isWithinRange(value, 0, 100)) {
done = true;
} else {
beep();
System.out.println(rangeErrorMessage);
}
} else {
done = true;
}
} while (!done);
return value;
}
public static void beep() {
java.awt.Toolkit.getDefaultToolkit().beep();
}
public static boolean isWithinRange(double value, double min, double max) {
return value >= min && value <= max;
}
public static Double getDouble(Scanner input, String prompt, String errorMessage, String exitValue) {
Double value = null;
boolean exit = false;
do {
System.out.print(prompt);
String nextLine = input.nextLine();
Scanner parser = new Scanner(nextLine);
if (parser.hasNextDouble()) {
value = parser.nextDouble();
} else if (nextLine.equals(exitValue)) {
exit = true;
} else {
beep();
System.out.println(errorMessage);
}
} while (!(value != null || exit));
return value;
}
}
nb: I have a exit condition available, you don't need it, but it's nice as a demonstration
I fashioned myself a function from #MadProgrammer's code (Thanks man!), this somehow works a wee bit simpler.
public static double getValue() {
Scanner beep = new Scanner(System.in);
boolean flag = true;
double value=0.0;
while(flag==true){
if(beep.hasNextDouble()){
value = beep.nextDouble();
if(value>=0&&value<=100){
flag=false;
}
else{
System.out.print("Invalid input, 0-100 only: ");
beep.nextLine();
}
}
else{
System.out.print("That's not a numerical value, try again: ");
beep.nextLine();
}
}
return value;
}
Feel free to comment, make a correction and/or suggest anything that would make this better.
I was working on a project for class and everything works fine until the code the professor gave us that will prompt the user to "doOver" the code if they choose to, it's coming out with this error and I'm frankly confused.
I tried changing the sc.nextLine to a .hasNextLine as I've seen in other posts, but it comes up with an error stating it needs to be a boolean and then says I can not use the next doOver.trim() code on a boolean.
final static String TITLE = "ISBN-13 Generator!";
final static String CONTINUE_PROMPT = "\nDo this again? [y/n] ";
static Scanner input = new Scanner(System.in);
private static void process(Scanner sc, String args[]) {
boolean numberChecker;
String isbn;
do {
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
input.close();
isbn = isbn.trim();
numberChecker = true;
int s = 0;
do {
numberChecker = numberChecker && Character.isDigit(isbn.charAt(s));
s++;
} while (s < isbn.length() || numberChecker == false);
} while (isbn.length() != 12 & numberChecker == false);
int sum = 0;
int s = 0;
do {
if (s % 2 == 0) {
sum = sum + isbn.charAt(s) - 48;
} else {
sum = sum + 3 * (isbn.charAt(s) - 48);
}
s++;
} while (s < 12);
{
sum = 10 - (sum % 10);
if (sum == 10)
sum = 0;
}
System.out.println("Your ISBN is " + isbn + sum);
}
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.trim().equalsIgnoreCase("Y");
}
public static void main(String args[]) {
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using the " + TITLE);
}
It should display "Do this again? [y/n]" with you inputting "y" to start the process over and entering "n" to stop and have the system print out ("Thank you for using the " + TITLE)
This is happening because you have closed the scanner instance already using line input.close();
Just comment out or delete input.close(); and your program will work as expected.
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
//input.close();
Let me know if it helps! :)
I know how to code to find the factorial of a number:
public static void factorialcalculations()
{
int usernumber, calculation, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
usernumber = in.nextInt();
if ( usernumber < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( calculation = 1 ; calculation <= usernumber ; calculation++ )
fact = fact*calculation;
System.out.println("Factorial of "+usernumber+" is = "+fact);
{
But what I need is for is to display what numbers it is being multiplied by for example if it was 5
I need it to display the factorial is: 5*4*3*2*1=120
Use recursion. The value you want to display for n=1 is "1=". For any other n, it's "n*" + display(n-1).
display(2) => "2*" + display(1) => "2*1="
display(3) => "3*" + display(2) => "3*2*1="
and so on.
There is lot of ways to do it. With your existing code you can print it within your existing loop. Recursive will be the elegant way to find the factorial.
public static int factorial(int n) {
System.out.print("factorial is : ");
int result = 1;
for (int i = n; i >= 1; i--) {
result = result * i;
System.out.print(i!=1 ? (i+"*"): (i+"="));
}
System.out.println(result);
return result;
}
PS: As a best practice you need to handle the all scenarios in here. (String/negative/.. inputs)
Here is what you seem to be looking for man:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println(getFactString(n,result));
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public static String getFactString(int n, int result){
String output= "";
int count = n;
for (int i = count; i > 0; i--) {
if (n==1) {
output = output + n +" = ";
break;
}
output = output + n+" * ";
n--;
}
return output + result;
}
It's also possible to do this will StringBuilder as well. With the getFactorString() method, it doesn't matter what n is, you will get the correct string returned to display.
I want to take any user input integer between 1 and 9999 and return that number with its digits reversed. The problem with my code is it's returning the sum of the entered integer and I have no idea how to fix it. This is the code that that I came up with so far:
import java.util.Scanner;
class Reverse{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 1 and 9999: ");
int user = input.nextInt();
if(user>1 && user<9999){
System.out.println("The number with its digits reversed is : " + reverseDigit(user));
}else{
System.out.println("Invalid Input");
}
}
public static int reverseDigit(int num){
return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000); //This is the problem
}
}
You could replace :
return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000);
with:
return ((num%10)*1000 + ((num%100)/10 )*100+ ((num%1000)/100)*10 + num/1000);
The reason that the first was wrong is because you get:
last digit:num%10
third digit:num%100)/10
second digit:(num%1000)/100
first digit:num/1000
so you was just adding all the digits before
But the Above works only for numbers from 1000-9999 .So you could replace the reverseDigit method with this simple method that works for every number:
public static int reverseDigit(int num){
int reverse=0;
while( num != 0 )
{
reverse = reverse * 10;
reverse = reverse + num%10;
num = num/10;
}
return reverse;
}
First, convert the number into a string then reverse the string and reconvert it into a number.
public static int reverseDigit(int num)
{
String str;
str = String.valueOf(num);
str = new StringBuilder(str).reverse().toString();
return (Integer.parseInt(str));
}
public static int reverseDigit(int num) {
int result = 0;
while(num != 0 ) {
result *=10;
int temp = num % 10;
result += temp;
num /=10;
}
return result ;
}
To do it using int (although String would be better).
public void test() {
System.out.println("Reversed: " + 1234 + " = " + reverseDigits(1234, 4));
}
public static int reverseDigits(int num, int digits) {
int reversed = 0;
for (int i = 0; i < digits; i++) {
reversed *= 10;
reversed += num % 10;
num /= 10;
}
return reversed;
}
I'm having a hard time wrapping my head around object based programming. Im attempting to invoke a method from a class. However, all I invoke is a variable that has been declared, while I'm trying to pull the variable later. (Im sure my terminology is off - feel free to correct)
Im getting logic errors. Instead of a value, im getting "null".
The Class:
public class NumberOperations {
int number;
String oddsUnder;
String powersTwoUnder;
int isGreater;
String toString;
public NumberOperations(int numberIn) {
number = numberIn;
}
public int getValue() {
return number;
}
public String oddsUnder() {
String output = "";
int i = 0;
while (i < number) {
if (i % 2 != 0) {
output += i + "\t";
}
i++;
}
return output;
}
public String powersTwoUnder() {
String output2 = "";
int powers = 1;
while (powers < number) {
output2 += powers + "\t";
powers = powers * 2;
}
return output2;
}
public int isGreater(int compareNumber) {
if (number > compareNumber) {
return 1;
}
else if (number < compareNumber) {
return -1;
}
else {
return 0;
}
}
public String toString() {
return number + "";
}
}
The Program:
import java.util.Scanner; import java.util.ArrayList;
/** * Demonstrates the NumberOperations class. */ public class NumberOpsDriver {
/**
* Reads a set of positive numbers from the user until the user enters 0. * Prints odds under and powers of 2 under for each number. *
* #param args - Standard commandline arguments
*/ public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// declare and instantiate ArrayList with generic type <NumberOperations>
ArrayList<NumberOperations> numOpsList = new ArrayList<NumberOperations>();
// prompt user for set of numbers
System.out.println("Enter a list of positive integers separated "
+ "with a space followed by 0:");
// get first user input using in.nextInt()
int firstInput = in.nextInt();
// add a while loop as described below:
while (firstInput != 0) {
numOpsList.add(new NumberOperations(firstInput));
firstInput = in.nextInt();
}
// while the input is not "0"
// add NumberOperations object to array based on user input
// get the next user input using in.nextInt()
int index = 0;
while (index < numOpsList.size()) {
NumberOperations num = numOpsList.get(index);
System.out.println("For: " + num);
System.out.println("Odds under: " + num.oddsUnder);
System.out.println("Powers of 2 under: " + num.powersTwoUnder);
// add print statement for odds under num
// add print statement for powers of 2 under num
index++;
} } }
You never assign to your member variables oddsUnder and powersTwoUnder. So of course they are null when you read them, and when you try to print them you have a NullPointerException it prints "null".
You probably actually want to call the methods of the same name instead of taking the variables
System.out.println("Odds under: " + num.oddsUnder());
System.out.println("Powers of 2 under: " + num.powersTwoUnder());
Make your properties as private to avoid this kind of situations and change your properties in System.out... to call the methods not the object fields. For example
System.out.println("Odds under: " + num.oddsUnder()); //<-changed