Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm totally new to Java, and I'm facing a little problem. Sometimes I need to declare a numerical variable in between two values like int x>=2 && x<=20; but I can't find a way to do that.
For example I have this problem to solve:
Given an integer, N, print its first 10 multiples. Each multiple N*i (where 1 <= i <= 10) should be printed on a new line in the form: N x i = result.
Constraints
2 <= N <= 20
How can i solve that, and how can I initialize an int variable "in between two values" ?
It makes no sense to "initialize a variable between 2 values", as a variable can have only 1 value at a time.
You should give the different possible values to the variable one by one :
int i=1;
while(i<=10){
System.out.println("N x " + i + " = " + (N*i));
i++;
}
Final result
If you don't want to keep your i variable after you can use a for loop:
for(int i=1; i<= 10; i++){
System.out.println("N x "+ i +" = " + (N*i));
}
You can do the same if you want to do this for all the specified values of N:
for(int N = 2; N <= 20; N++)
for(int i = 1; i <= 10; i++)
System.out.println("N x "+ i +" = " + (N*i));
About variables with several values
In software programming, the very concept of a variable is a "placeholder to store a value". So by definition, a variable can hold only one value, and is doing so at any time.
When you see variables that seem to hold several values, they are actually holding 1 value, which itself is a container for several values.
It is not possible to give an int variable a range as its value. However, it is possible to change the value of an int at runtime.
For the given problem, there are two approaches I might consider using.
Taking a command line argument
You can write your program to take a value given on the command line and assign it to your int variable. Assuming you are within your main method, command line arguments are kept in the args array and can be accessed like this...
int value = Integer.parseInt(args[0]);
This will store the first argument given on the command line in the variable value, provided it is parseable as an integer. So if you run the program with the command java Program 10, then value will be assigned value 10.
Asking the user for input
Look up the Scanner class and use it to ask the user for a value in the range that you want.
Like this...
Scanner in = new Scanner(System.in);
int value = in.nextInt();
Obviously if you want to make sure that the given values lie in your desired range this can also be checked at runtime pretty easily.
Java doesn't allow to specify range of variable like python's range(int,int) method . However you can use Range class from apache commons library.
For your problem, there is no need to declare variables value beforehand. Just initialize the variable with the lowest value ,perform some calculation and increment the variable in a loop.
public static void main(String[] args){
int n = 2;
while(n<=20){
for(int i=1;i<=10;i++){
System.out.println(n+"X"+i+"="+n*i);
}
n=n+1;
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to generate a 100 unique random numbers, but the numbers need to be in the range of 1-10.
Right now I am doing this:
for (int i = 0; i < 100; i++) {
Double n = rand.nextDouble(10) + 1;
arr[i] = n;
}
I could get Double numbers by checking if they're unique using if/else statements in arrays but it is very difficult and inefficient because the numbers(Doubles) could be almost infinite.
So how do i make sure the numbers are unique without using arrays?
Are there any data structures in java which do not allow duplicate elements?
As you alluded to in the comments, there's no way to generate 100 unique integers between 1 and 100. Using doubles allows you to do that, but does not guarantee uniqueness by itself (even though there's an infinitesimal chance of getting repeating items), so you would have to guarantee this yourself - e.g., by using a Set:
Set<Double> doubles = new HashSet<>();
while (doubles.size() < 100) {
doubles.add(1 + rand.nextDouble() * 9);
}
EDIT:
JDK 8 provides an arguably more elegant way of achieving this with streams:
List<Double> doubles =
rand.doubles()
.distinct()
.map(d -> 1 + d * 9)
.limit(100)
.boxed()
.collect(Collectors.toList());
You can use something like this.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
double[] arr = new double[100];
for (int i = 0; i < 100; i++) {
Random rand = new Random();
double n = 10*rand.nextDouble();
System.out.println(n);
arr[i] = n;
}
}
}
But it is not possible to get unique 100 integers between 1-10.
The above program generate something like this
4.142037859604101
2.655156962359073
3.7397565068261205
2.9699181925544247
2.747362791293101
3.243100861992423
9.308481386292623
4.96298205308679
3.4319099852820822
9.951375372917328
3.6941158775736316
1.0388381644118727
1.6895078811799191
0.9166823110491484
9.60259797093202
2.3365812211691708
8.556399515524168
2.570971809286772
1.6621912919374215
0.5896588206170794
6.921688301938134
6.325470591144598
2.35492413118687
2.1778674294915454
The class Math has a bunch of useful functions, also at least one which you could use for this.
for(int i = 0; i < 100; i++) {
double n = (Math.random()*9) + 1;
arr[i] = n;
}
Math.random returns a random positive greater than or equal to 0.0 and less than 1.0, so if you multiply that by 9, you get a number greater than or equal to 0.0 and less than 9.0. And then the plus 1 is to make sure the range is between 1 - 10.
If you really want to make sure that all numbers are unique you could write a method that checks if the number is not already in the array.
Hopefully this helps you out. Good luck!
I am having issues with this array code. It needs to have a number count that displays the numbers that are entered by the user. So for instance, if the user enters three four's it will say "4 3." I already have the majority of the code done, but it is just returning the first number that's entered.
import java.util.Scanner;
public class NumberCounts
{
public static void main(String args[])
{
int[] answer = new int [100];
inputArray(answer);
}
public static void inputArray(int[] Numbercounts)
{
System.out.println("This Program is written by Benjamin Barcomb\n");
Scanner kb = new Scanner(System.in);
System.out.print("How many numbers will you enter? : ");
kb.nextInt();
//int[] answer = new int[100];
int arryNum[] = new int[] {};
System.out.println("\nEnter numbers in [0, 100] range separated by a space:");
int input = kb.nextInt();
System.out.println("Number Count");
int[] counter = new int[] {input};
for (int i = 0; i < arryNum.length; i++) {
System.out.println(" " + (i + 1) + " " + counter[i]);
}
for (int i = 0; i < counter.length; i++) {
System.out.println(" " + (i + 1) + " " + counter[i]);
}
}
}
Where to start...
1) You create an array answer of length 100, pass it to your method, then never use it anywhere.
2) You ask the user to tell you how many numbers they are going to enter, you get that input with kb.nextInt(), then do nothing with it. You never assign that int to a variable.
3) You create an array arryNum and leave it empty. You never put anything into it, ever.
4) You ask the user to input numbers separated by spaces. You then take only the first int they enter.
Since it seems like you are just learning I will leave the coding to you. Hopefully if you can now see what certain parts of your code are doing you will be able to move on from there. My one tip would be to use more descriptive variable names. It makes it easier for you to read what is going on when you look at your code.
Some Solutions
1) Unless the requirements say you must pass an array into the inputArray() method, I would just remove it all together since you are doing all the other work in the method. I would remove int[] answer = new int [100]; call the method with no parameters inputArray() and change the signature of the method to just
public static void inputArray() { ... }
2) When you ask the user how many numbers they are going to enter you are basically asking them "How long should my array be?" When you get this int you should use it to make your new array. Something like
System.out.print("How many numbers will you enter? ");
int usersNumbers = new int[kb.nextInt()];
Notice I have changed the name of arrayNum to usersNumbers. It's more descriptive and makes reading your code easier.
3) Now you want to get all those numbers and put them into that array. Since you need to get multiple numbers you will need a loop. Again, unless the requirements say you have to, I would do this a bit differently. Instead of entering all the numbers on one line separated by spaces, I would ask for the numbers individually. Since we know the length of the array (how many numbers they are going to enter), we know how many times to prompt them.
System.out.println("\nEnter numbers in [0, 100] range.\n");
for (int i = 0; i < usersNums.length; i++) {
System.out.println("Enter Your Number:");
usersNums[i] = kb.nextInt();
}
4) Now onto counting the number of occurrences of each int entered. Since the user can enter their numbers in any random order it makes things tougher. Again, I'm not sure what exactly your requirements allow or not, but here is what I did. First I want to get a list of the unique numbers. For example, if the array is {2, 4, 2, 5, 2, 4} I want to get a list with {2, 4, 5}. Once I have that I can look at each of those numbers and go through the array counting how many times I see each one. An easy way to get a list of unique numbers is to put them into a Set. It is a data structure which doesn't allow duplicates. A TreeSet is a Set which puts the numbers in order, just to make it easier to read.
Set<Integer> uniqueNumbers = new TreeSet<Integer>();
for (int i : usersNums) { uniqueNumbers.add(i); }
Now that I have the list of unique numbers I can start counting. I start count at 0. Then for every number in the set, I look at every number in the array and see if they are the same. If they are, count goes up by 1. Once I get to the end of the array I print my results for that number, then reset count to 0.
int count = 0;
for (Integer i : uniqueNumbers) { //For every number in the Set
for (int j = 0; j < usersNums.length; j++) { //Look at every number in the array
if (i == usersNums[j]) { count++; } //If the same, count++
}
System.out.print(i + " - " + count + "\n"); //Print results
count = 0; //Reset Count
}
It seems you're only getting the first value because you only called nextInt() on your scanner once. You should ideally have a while loop to keep gathering user input. Also, I think you're trying to store your answers in an array, which really isn't ideal since you don't know how big your input will be. You should really use a list. Something along the lines of
List<Integer> data = new ArrayList<Integer>();
while (kb.hasNext()) {
data.add(kb.next());
}
Explain your code hope you understand how to fix it.
First, I assume you want your user to enter more than one number but you use nextInt which means
The java.util.Scanner.nextInt() method Scans the next token of
the input as an int.An invocation of this method of the form
nextInt() behaves in exactly the same way as the invocation
nextInt(radix), where radix is the default radix of this scanner.
Suggestion: try to use to while loop to read more number and quite when your user enter -999999 for example as a termination for your while loop.
Second, use Array is not right data structure to use because you do not know the size of array.
There are 2 ways to fix this issue:
1. first to ask the size of array from the user like how many numbers the user wants to input which is not what you want.
2. use another data structure that shrinks and expands by itself which is ArrayList
Third, you did not say whether you gonna have different numbers in your input like
1 1 2 3 3 4 4 5 or unsorted like `1 2 1 4 3 4 5`
or just your input includes the same numbers like
2 2 2 2 2 2 2
More info for third point is here
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So i'm a beginner and I am trying to figure out how to add more than 2 numbers and display it through the output of netbeans. Its really confusing for me since i'm still new to programming.
First, you need to define variable.
what is variable?
A variable provides us with named storage that our programs can
manipulate.
There are different type variable in Java like int, double, char, String, and so on.
What do I mean by type variable?
determines the size and layout of the variable's memory
he range of values that can be stored within that memory
the set of operations that can be applied to the variable
How to define Variable in Java
data type variable [ = value][, variable [= value] ...] ;
For example , you can define two variable as int type as follows
int firstNumber = 1;
int secondNumber = 2;
Note if you like you can define more than two variables by following up the rules.
you can do Arithmetic Operators on your variables
Operator Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Here you want to add so you need to use + operator.
read this which is my source : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
At the end, you should define a variable that carries the summation of two variables like
int sum = number1 + number2;
and print the value on your console by using System.out.print/ln
System.out.print("the summation of number one and number two is " + sum);
Source:
http://www.homeandlearn.co.uk/java/java_int_variables.html
http://www.tutorialspoint.com/java/java_variable_types.htm
int a = 1;
int b = 2;
int c = 3;
int d = a + b + c;
System.out.println(d);
If you want to add up the numbers in an array or collection:
int[] numbers = { 1, 2, 3 };
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println(sum);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to understand how can the int x be incremented inside an if (Boolean expression) for every loop iteration
How is that possible?? How does it work?
public class MethodsTest {
public static void main(String[] args) {
int x= 0;
for (int z = 0; z < 5; z++)
{
if(x++ > 2){
}
System.out.println(x);
}
}
}
the output will be
1
2
3
4
5
x++ is a compound assignment operator, which is equivalent to x = x + 1, with the side effect taking place after the evaluation. Therefore, the if statement is equivalent to a pair of statements like this:
if(x > 2) {
x = x + 1;
// At this point, the side effect has taken place, so x is greater than it was before the "if"
...
} else {
// The side effect takes place regardless of the condition, hence the "else"
x = x + 1;
}
Note that this code is forced to repeat the x = x + 1 part. Using ++ lets you avoid this repetition.
There is a pre-increment counterpart of x++ - namely, ++x. In this form the assignment takes place before the expression is evaluated, so the condition becomes
if ((x = x + 1) > 2) {
// Note that the condition above uses an assignment. An assignment is also an expression, with the result equal to
// the value assigned to the variable. Like all expressions, it can participate in a condition.
}
To break your notion that the condition of an if can't "do things", imagine that you have a function that returns a boolean, like:
boolean areThereCookies(int numCookies)
{
return numCookies > 0;
}
then you could use it in your if statement:
if (areThereCookies(cookies))
{
eatCookies(cookies);
}
However the method areThereCookies(int) that we are calling to evaluate the if condition could be making anything in the world. It could change variable values, read input, write output, steal cookies...
So the language is perfectly capable of "doing things" in the if evaluation. The other answers explain what your code was specifically doing.
Cheers.
You are allowed to have expressions inside a if statement as long as the expression resolves to a boolean. For example,
int i = 0
if (i = i + 1)
is not a valid expression inside an if statement because the expressions resolves to 1, which is an integer.
However,
int i = 0
if (2 == i = 2)
is a valid expression because 2 is first assigned to the variable i and then is compared to 2, and thus the expression resolves to “true”.
In your example if statement, you have a post-incremented variable x that is compared against 2 with the greater than operator, resulting in a boolean value, and thus it is a valid expression. Hotlinks has described what a post-incremented variable is in the comments.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
//I am supposed to do it with loops and decision statements, but it's not working. Help!
import java.util.Scanner;
public class main {
/**
* #param args
*/
public static void main(String[] args) {
//Declare variables
Scanner abc;
abc = new Scanner (System.in);
int input;
int divide = 2;
int count=0;
//Ask for input
System.out.println("Please enter an integer to determine if it is prime");
input = abc.nextInt();
//Do math
for (int x=1; x < input; x++) {
if ((input%divide) == 0)
count += 1;
divide = divide + 1;
}
if (count == 0)
System.out.println("It is a prime number");
else
System.out.println("It is not a prime number");
}
}
In your for loop, for the last iteration, x = input - 1, but that means divide = input (since divide was one greater in the beginning, and you increment both once per iteration of the loop), so count will actually be equal to 1 if the number is prime, not 0.
You're counting the number of divisors; all you need to do is determine if there is at least one divisor. Here's a better algorithm:
function isPrime(n)
if n is even
return n == 2
d := 3
while d * d <= n
if n % d == 0
return False
d := d + 2
return True
I discuss this algorithm, among others in the essay Programming with Prime Numbers at my blog, which includes implementations in Java.
It looks like count is supposed to count the number of factors of input not counting 1 and input. For readability, I'd recommend using a name like numOfFactors instead of count.
Given that, now look at your loop and answer these questions. I'm not going to give you the answer. (Yes, you can get the answer by looking at others' comments, but I think you will learn more by answering these questions anyway.)
(1) What are x and divide the first time you go through the loop, at the beginning of the loop?
(2) If you look at what happens to x and divide, there's a simple relationship between x and divide at the beginning of each time through the loop. What is it?
(3) What is x the last time you go through the loop?
(4) Based on the answers to #2 and #3, what is divide at the beginning of the last time through the loop? What will input%divide be equal to?
That's why it isn't working. Figure that out first. Then we can talk about how to can make it work more efficiently.
MORE: OK, I'll say one more thing. If all you care about is whether count is zero or not, you can quit your loop as soon as you find a factor. Like this:
if ((input%divide) == 0)
{
count += 1;
break;
}
(And if you do it that way, then instead of count you should use a boolean foundAFactor because all it says is whether you found a factor, not how many there are.)
But if you really want to know the exact number of factors, don't do that.
Hello do it like this:
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("is a prime");
else
System.out.println("is not a prime");
break;
}
}
for (int x=2; x < input; x++) (change x=1 to x=2)
otherwise you end up trying to divide 5 by 5 to test if 5 is prime