If I wanted to enter 10 numbers, and after each number it displays the square root, how would I do this using a for loop?
int number;
System.out.print("Enter a number: ");
num = input.nextInt();
for (count = 0; count <= 10; count++)
{
System.out.println("The Square of Number is : "+(num*num));
System.out.println("The Cube of Number is : "+(num*num*num));
I have tried this code. However, it displays 1 input 10 times. How do I get it to display after each input?
Similar to what others have said, you are only getting input once, and then printing the output 10 times. input.nextInt() must be moved inside the for loop.
However, something that hasn't been said is that you aren't consuming the newline delimeter. (Assuming you're using the console, which it seems you are) When the user inputs text by hitting enter, there is a newline delimeter at the end of the input. You are only consuming the number, but not the newline.
An example of this can be found here.
If you want to output the square root after you entered a number, just put num = input.nextInt(); inside the for-loop, as already mentioned.
If you however want to input the 10 numbers first and then output the squares of every number, this would be a pretty good solution:
int[] numbers = new int[10];
for(int i = 0; i < numbers.length; i++) numbers[i] = input.nextInt();
for(int tempInt : numbers) System.out.println(Math.pow(tempInt, 2));
Move num = input.nextInt() inside the for loop, like #Pavneet Singh said. If you want it to display all 10 after they have been entered, use an int[] with a length of 10 like this:
int[] numbers = new int[10];
Related
The program listed is about writing the Fibonacci series given user input that is below 100. The problem that I am having is figuring out how to get the Fibonacci to not print if the number listed by the user is above 100. However, I am unable to figure out what to do. This is my code, I am not trying to use while loop to only print if the number is between 1 and 100. however when I print 101, it still gives me the Fibonacci series.
import java.util.Scanner;
class Program_2 {
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("Enter an integer between 1-99: ");
int num = console.nextInt();
while (num>1) {
if(num<100) {
System.out.println("Fibonacci Series till " + num + " terms:");
}
int n = 100, firstTerm = 0, secondTerm = 1;
for (int i = 1; i <= n; ++i) {
System.out.print(firstTerm + ", ");
// compute the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
}
The Output that im getting when i print 101, is
I've used an if/else statement, but for some reason, it didnt do anything. Then I tried using a while loop and an if statement, but its still printing above 100. I am unsure how to go about this. Any help is very much appreciated!
To fix this issue, you can add another condition into your while loop. Right now, you are going into the while loop as long as num is greater than 1. Thus, numbers above 100 are being considered as well. To fix this, you can make your while loop start like this: while(num>1 && num<=100).
Your while check "while(n>1)" will run infinitely. You need to change num's value after every iteration like this:
num--; //In the loop
And when num becomes less than 1, the program exits from the loop.
If you want to check whether num is less than 100 or bigger than 1 use if statement(to check if input value corresponds to your range)
while(num > 1 && num < 100){
//your code in while loop
}else{
System.out.println("Your value is too big or too small!");
}
And also I've noticed your output of fibonacci sequence is not right(negative values, bound in int32). You can't even display in long values because fibonacci of 9*th order are over quadrillions. Try to use BigInteger in order to show right values in the console output. Want to fancy your output? Use /t and %n in System.out.print();
Here I am trying to reverse a number using for loop but when n=1234 it gives the output 432 only.
Please explain why for loop behaving differently.
When i tried the same problem with while loop using condition while(n>0) it worked as expected and gave the desired output
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int rev=0;
for(int i=1;i<=n;i++){
int temp=n%10;
n=n/10;
rev=rev*10+temp;
}
System.out.println(rev);
expected output is 4321 when n=1234 but it is giving output as 432
Its seems like you need to read more about loops in java
when you use for loop, you go thru all the numbers from 1 (in your case) to n
and when you use while you go until n is 0
you can see there is a different between the values you end up with, i really suggesting you to watch some more toturials before moving on :)
Understand what you want to achieve first: For reversing a number
Input: num
(1) Initialize reverse_num = 0
(2) Loop while num > 0
(a) Multiply reverse_num by 10 and add remainder of num
divide by 10 to rev_num
reverse_num = reverse_num*10 + num%10;
(b) Divide num by 10
(3) print reverse_num
The for loop you are using is taking all the values in consideration starting from 1 to 1234 (1, 2, 3, 4,5, 6......1234)
When you are using while loop you just have one condition if num>0 which is what we need, hence it works.
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
int reversed = 0;
while(num >0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println(reversed);
}
Try smth like this:
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int rev=0;
while(n>0)
{
int temp=n%10;
rev=rev*10+temp;
n=n/10;
}
System.out.println(rev);
Will be better to use while
How the algorithm work with while and why you need to cut untill n=0(1234 as example):while(do this untill n == 0).
First try:
first line:temp=n%10 so temp=1234%10=4.second line:n=n/10 so n=1234/10=123
third line: rev=rev*10+temp so 0*10+4=4;
Next try:
first line:temp=n%10 so temp=123%10=3,second line:n=n/10 so n=123/10=12,
third line: rev=rev*10+temp so 4*10+3=43;
Next try:
first line:temp=n%10 so temp=12%10=2 second line:n=n/10 so n=12/10=1.2(1,int)
third line:rev=rev*10+temp so 43*10+2=432;
Final try:
first line:temp=n%10 so temp=1%10=1
second line:n=n/10 so n=1/10=0.1(0,int),third line: rev=rev*10+temp so REV it's 432*10+1=4321;
I am trying to populate an NxN matrix. What I'd like to do is be able to enter all the elements of a given row as one input. So, for example if I have a 4x4 matrix, for each row, I'd like to enter the 4 columns in one input, then print the matrix after each input showing the new values. I try to run the following code but I get an error that reads: Exception in thread "main" java.util.InputMismatchException. Here is my code:
double twoDm[][]= new double[4][4];
int i,j = 0;
Scanner scan = new Scanner(System.in).useDelimiter(",*");
for(i =0;i<4;i++){
for(j=0;j<4;j++){
System.out.print("Enter 4 numbers seperated by comma: ");
twoDm[i][j] = scan.nextDouble();
}
}
When I get the prompt to enter the 4 numbers I enter the following:
1,2,3,4
Then I get the error.
You should just do this;
double twoDm[][] = new double[4][4];
Scanner scan = new Scanner(System.in);
int i, j;
for (i = 0; i < 4; i++) {
System.out.print("Enter 4 numbers seperated by comma: ");
String[] line = scan.nextLine().split(",");
for (j = 0; j < 4; j++) {
twoDm[i][j] = Double.parseDouble(line[j]);
}
}
scan.close();
You should not forget to close the scanner too!
1 2 3 4 are not visible by Scanner as double numbers, but as integers.
So you have the following possibilities:
If you don't need a double use nextInt()
Write 1.0,2.0,3.0,4.0 instead of 1,2,3,4
Read the values as strings and convert them to double with Double.parseDouble()
I believe it would be easier to use string.split() , rather than .useDelimiter() , because when using delimiter , you would have to input the last number with a comma as well (since comma is the one delimiting stuffs) unless you create some regex to take both comma and \n as delimiter.
Also, you should give the prompt - System.out.print("Enter 4 numbers separated by comma: "); inside the outer loop, not the inner loop, since you would be taking in each row inside the outer loop, and only elements in each row in the inner loop.
You can do -
double twoDm[][]= new double[4][4];
int i,j = 0;
Scanner scan = new Scanner(System.in);
for(i =0;i<4;i++){
System.out.print("Enter 4 numbers separated by comma: ");
String row = scan.nextLine().split(",");
for(j=0;j<4;j++){
twoDm[i][j] = Double.parseDouble(row[j]);
}
}
I'm new to java and I have an assignment asking to prompt user for a number between 2 and 10 and it is supposed to print out multiples of that number. It is also supposed to use a for loop.
I think I have the general idea with the for loop I'm just trying to figure out how to do the multiples. Any help is greatly appreciated! This is where I am so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter a number between 2 and 10:");
for(int i = 2; i<= 100; i++){
System.out.println(+ i);
}
I suggest thinking about how you would go about doing the task mentally. When you're counting integers, you will add one each time (i++). When you're counting by, say threes, you will add three each time. You need to store your scanner's read value to a variable (don't try to read the scanner each time!) and adjust i++ in your loop to add the number you read from the scanner instead.
Begin with:
int step = in.nextInt();
if(step >= 2 && step <=10){
for(int i = 0; i <=100; ???){
System.out.println(+ i);
}
} else {
System.out.println("The step value was not between 2 and 10.");
}
I will leave you at this point as learning it for yourself is far more valuable than any Stack Overflow answer could ever be. If you are still stumped, I can guide you farther in the right direction.
You should ensure that the user can only enter numbers between 2 and 10, and you will need to store the input for use in your for loop. For example:
int num = 0;
Scanner in = new Scanner(System.in);
do
{
System.out.print("Please enter a number between 2 and 10:")
num = in.nextInt();
System.out.println();
} while((num < 2) || (num > 10));
Followed by your for loop.
A multiple of a number is that number times something.
So one multiple of i would be i * 13 (for example).
of course you need to get number from the Scanner "in" object
for (int i=2; i < 13; i++) {
System.out.println(" Multiple (" + i + ") = " + i*number;
}
I am creating a program that takes various double arrays and displays them. The array is 10 elements and I am asked to get the values for elements 2 through 9 from the user input by using a loop. I have tried a for loop but I just don't understand how to get this done.
int c;
for(c = 0; c >= 2 && c <= 9; c++){
System.out.println("Enter a value for the elements 2-9: ");
}
System.out.println(" ");
If you have a Java array as follows:
double myarr[10];
You access elements in an array by index (assuming the array has been populated with data)
double somenum = myarr[3]; // extracts the *fourth* element from the list
To set a value in the array, you use the assignment operator and specify a value:
myarr[7] = 3.14159; // sets the *eighth* element to value '3.14159'
If you wish to iterate over a range of numbers, you can use a for-loop. For-loops have the following format:
for (initialization; condition; increase)
If you wanted to print all numbers between 1 and 10, you can write:
for (int i=1; i<=10; i++) {
System.out.println(i);
}
The trick is to use the variable i in the for-loop and ensure the loop iterates over the proper range. Hint: You can use i as an array index.
Here are some good resources:
Java: Array with loop
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
http://www.tutorialspoint.com/java/java_loop_control.htm
http://www.homeandlearn.co.uk/java/java_for_loops.html
Here's a loop and a means for user input:
Scanner reader = new Scanner(System.in);
for(int i=2; i<8; i++){
System.out.println("Enter Element "+i);
a=reader.nextInt();
//store "a" somewhere
}
c needs to start at 1 (since you want the second elment) and stop at 8 (for the ninth)
so for(int c=1;c<9;c++) should be the loop
When writing loops remember;
array indexes are 0 based, the first element is at 0, the second at 1 up to the last which is at the length of the array minus 1
if your loop increments, then the smallest value it can have is what ever it starts as, so you shouldn't check to make sure its greater then that, (ie if you start at 2 and increment then you don't need to check to if its greater than or equal to 2 because it always is)
Take a look at the syntax for for loops here
Console console = System.console();
double arr[10];
for(int c = 1; c<10; c++){
String input = console.readLine("Enter a value for the elements 2-9: ");
arr[c] = Double.parseDouble(input);
System.out.println(arr[c]);
}