How to calculate exponent with loop? - java

I am currently working on a program that calculates the power of certain numbers. The number limit is 1 to 9. My code is posted below. I have the following issues:
Every time I run the program it doesn't print the correct answer.
I want to modify the code so the application calculates X to power of Y, where X and Y are allowed to be integers in the range 1 to 9 (including 9). If the user enters an invalid value the program should ask the user for input again. When a user is done with entering the values for base and exponents, the program will print the result.
Conditions of this task is that I must use loops to calculate the result by doing
several multiplications; I am not allowed to use any available method or API
that calculates the result for me. Please help me come up with the solution.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package exponent;
//import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
int t = 1;
for(int i = 1;i <= e; i++);
{
t=t*b;
}
System.out.println(t);
}
// TODO code application logic here
}

For a start, there should be no semi colon after the for loop:
for(int i=1;i<=e; i++ )
{
t=t*b;
}
A simple input test could be something along the lines of:
public boolean testInput(int e)
{
if(e>9||e<1)//where e is the inputted number
{
return false
}
else
{
return true;
}
}
Then use it like this:
boolean valid = false;
while(valid!=true)
{
e = Integer.parseInt(br.readLine());
if(testInput(e)==false)
{
System.out.println("Please enter a number between 1 and 9")
continue;
}
else
{
valid = true;
}
}

Remove semi colon from for-loop
From
for(int i=1;i<=e; i++ );
to
for(int i=1;i<=e; i++ )

For the first part, its is a easy fix. You just added a semicolon where there shouldn't be in the for loop.
for(int i = 1;i <= e; i++); {
for(int i = 1;i <= e; i++){ //There should be no semicolon here
For the second part, you can do it with two very easy do-while loops.
//Replace this
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
//with
do{
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
}while(b > 9 || b < 1);
do{
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
}while(e > 9 || e < 1);
So the do-while loops, will first ask for the base or the power (Depending where in the code the program is running), then it will set the int to the value. If the value is greater than 9, ie: 10 or above, the program will reask for the base or power (Like I said, depended which loo is running), and then it will set the int again. It will do this, until the value is under 10. Like you want.
Here is an example of the output:
Enter the base
56
Enter the base
-4
Enter the base
4
Enter the power
67
Enter the power
10
Enter the power
-8
Enter the power
7
4 to the 7th power is 16384
If the code snippets are confusing, here is the entire compilable, working class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StackOverflowAnswers{
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
do{ //Asks for the base
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
}while(b > 9 || b < 1); //If the base is not valid, it goes back to the "do" statement, which asks for the base, again.
do{ //Asks for the power
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
}while(e > 9 || e < 1); //If the power is not valid, it goes back to the "do" statement, which asks for the power, again.
int t = 1;
for(int i = 1;i <= e; i++){ //No semicolon here
t=t*b;
}
System.out.println(b + " to the " + e + "th power is " + t); //Just added some words and the base and the power for easier debugging and understanding.
}
}
Hope this helps.

For the first part, it is just happening because you placed a semicolon after loop's declaration, which java just loops to that semicolon and nothing more. By removing semicolon the loop should work. However, for the second part, you can just add inputcheck method, as shown in my code below.
import java.io.*;
public class abc {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b, e;
System.out.println("Enter the base");
b = check(Integer.parseInt(br.readLine()));
System.out.println("Enter the power");
e = check(Integer.parseInt(br.readLine()));
int t = 1;
for (int i = 1; i <= e; i++); {
t = t * b;
}
System.out.println(t);
}
private static int check(int x) {
while (x < 1 || x > 10)
x = Integer.parseInt(br.readLine());
return x;
}

Related

How to create an addition loop of random numbers?

After writing 1 on scanner I want a random dice number generated and after pressing 1 again I want another random number generated but now I want it added with previous number. I want to make a loop, I want to keep pressing 1 and keep adding random numbers till I reach a certain number.
Thank you.
import java.util.Random;
import java.util.Scanner;
public class dice {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int k = 0; k < 100; k++) {
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
System.out.println(s);
int previous = s;
if (s == 1) {
Random ran = new Random();
int n = ran.nextInt(6) + 1;
System.out.print(n);
int next;
while (true) {
next = scan.nextInt();
if (next == 1) {
System.out.println(previous);
}
previous = n + 10;
}
}
}
}
}
Define previous outside the for loop, and replace
int previous = s;
previous = n + 10;
with
previous += s;
previous += n + 10;
Scanner sc=new Scanner(System.in);
int sum=0;
for(;;)
{
if(sc.nextInt()==1)
{
int num = (int)(Math.random()*6); // using the pre-defined random function in java.lang.Math class
System.out.println("Dice Value: "+num);
sum+=num; // shorthand adding the number for each iteration
}
//if(sum>100)
// break;
//if statement to check if value of sum is greater/lesser than a specific number
}
System.out.println("Final Answer: "+sum)
Something like this might work (not yet tested): an infinite loop that can be terminated as per choice.
If you are looking for a way that the program works as soon as you physically press the '1' key on your keyboard, without having to press the enter key, something like a keyevent might work:
https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
Please do let me know if there are any errors or doubts :)

Using arrays to store primes

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

Java validate only values between 1 and 3

I am trying to only accept integers between the values of 1 and 3 using a while loop and nested if statement in Java.
Anything outside of this range, produces an error message
The program should only accept integers between 1 and 3, any strings of text or decimal values should also produce the same error message and loop back to the original print statement (enter a number: )
The code below runs without any compiler errors although the statement || (a < 1 || a > 3)) will always produce the error message, regardless of the value.
If I was to delete this statement, the program will run and only accept integers of any value, (error message appearing when a string or decimal value is entered)
Could anyone help range this program, only accepting values of between 1 and 3, thanks.
import java.util.Scanner;
public class Validate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
while (true) {
System.out.print("enter a number: ");
if (!input.hasNextInt() || !input.hasNext() || (a < 1 || a > 3)) {
System.out.println("Oops! ");
input.nextLine();
}
else {
a = input.nextInt();
break;
}
}
input.close();
System.out.println("a = " + a);
}
}
Make sure to be careful of the order of expressions. If one of the 3 statements you wrote happens to be true then the code in the if curly braces will execute. You likely want something like this
if (!input.hasNextInt() || !input.hasNext()){
if ((a > 1 || a < 3)){
YourCode
}
}
The biggest issue is that you need to remember that initially your integer "a" is set to "0". This always catches your first if condition meaning that a is never set!
You are not updating the value of a, so it's 0 all the time.
import java.util.Scanner;
public class Validate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
boolean loop = true;
while (loop) {
System.out.print("enter a number: ");
if (!input.hasNextInt() || !input.hasNext()) {
System.out.println("Oops! ");
input.nextLine();
} else {
a = input.nextInt();
if (a <= 3 && a >= 1)
loop = false;
else {
System.out.println("Oops! ");
input.nextLine();
}
}
}
input.close();
System.out.println("a = " + a);
}
}
EDIT:

Multiplication Tutor Java Program

I am working on writing a program that follows these instructions:
Your little sister asks you to help her with her multiplication, and you decide to write a Java program that tests her skills. The program will let her input a starting number, such as 5. It will generate ten multiplication problems ranging from 5×1 to 5×10. For each problem she will be prompted to enter the correct answer. The program should check her answer and should not let her advance to the next question until the correct answer is given to the current question.
After testing ten multiplication problems, your program should ask whether she would like to try another starting number. If yes, your program should generate another corresponding ten multiplication problems. This procedure should repeat until she indicates no.
I have the code correct to ask for the multiplication part, but I can't quite figure out how to get the program to ask if the user wants to continue.
The following code has the program run through once:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
}
}
When I uncomment out line 21 the program returns:
Enter number you would like to attempt: 1
1 x 1 = 1
Would you like to do another problem? 1 x 2 = 2
Would you like to do another problem? 1 x 3 =
etc...
If I take the code from line 21 and put it outside of the for loop the program runs the for loop once and then jumps straight to the question.
How do I go about fixing this and successfully completing the instructions?
Here's how I'd do it:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args)
{
boolean wantsToContinue = true;
while(wantsToContinue)
{
wantsToContinue = mathProblem();
}
}
public static boolean mathProblem()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
boolean wantsToContinue;
//Ask if the user would like to do another problem here, set "wantsToContinue" accordingly
return wantsToContinue;
}
}

How do you print x number of lines at a time

I have a program that prints the instance variables of objects stored in an arraylist.
I want to add a feature to this program so it only prints the instance variables for first 10 objects, then ask the user to press enter to continue, then continues with the next 10 objects and so on.
Here is an example of how the printing loop looks without the function i'm asking for:
for (int i = 0; i < myList.size(); i++)
{
System.out.println(myList.get(i).getName();
}
The "Press enter to continue" part is easy enough:
import java.util.*;
...
Scanner input = new Scanner(System.in);
input.nextLine()
but how do i create a conditional loop that stops after 10 prints and then resumes after the "Press enter to continue" event??
for (int i = 0; i < myList.size(); i++)
{
System.out.println(myList.get(i).getName();
if(i % 10 == 0){
input.nextLine()
}
}
You could use System.in.read(), It reads a character and hence when the user presses any key, it continues.
Other wise waits for the user to input.
for (int i = 0; i < myList.size(); i++)
{
System.out.println(myList.get(i).getName();
if(i % 10 == 0){
System.out.println("Press any key to continue!");
char ch = (char) System.in.read();
}
}
Try this code:
for(int index = 0; i <myList.size(); i++){
/*check if it has printed 10 times first or else, it'll be printed 11 times first*/
if( i % 10 == 0 && i!=0 ){
System.out.println("Press enter to continue...");
//Prompt the user of course...
input.nextLine();
}
System.out.println(myList.get(i).getName());
}
as commented in the code above, you need to check if it is printed 10 times first. #bmscomp's code might have a bug if it has more than 10 entries.
I decided to go with my own approach.
I wish i could credit everyone with an answer-tick as my suggestion is a combination of them all:
for (int i = 0; i < myList.size(); i++)
{
if(i % 10 == 0 && i != 0){
System.out.println("Press enter to continue...");
input.nextLine();
}
System.out.println(myList.get(i).getName());
}
Putting the printing outside the if statement makes more sense.
Now it properly prints 10 statements the first time instead of 11.
I believe you can have a better idea on what to be done on receiving user input.
Please try following:-
`
import java.util.Scanner;
public class GetInputFromUser {
public static void main(String args[]) {
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}

Categories