this is my first time using this site so sorry if I do something wrong,
Here's an example output of the program I'm working on, basically what's supposed to happening
1-10 |**
11-20 |****
21-30 |***
31-40 |
41-50 |******
It goes on like that till the range of 91-100. This is my code so far, I've had a couple of different ideas so the code is incomplete in some parts but I really don't know which direction to go.
import java.util.Scanner;
public class HowMany
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
int range1 = 0;
int range2 = 0;
int range3 = 0;
int range4 = 0;
int range5 = 0;
int range6 = 0;
int range7 = 0;
int range8 = 0;
int range9 = 0;
int range10 = 0;
System.out.println("Enter integers between 1 and 100 (inclusive).");
System.out.println("Enter an integer out of the range to stop.");
//Assigning the user input a variable
int userNum = input.nextInt();
while(userNum >= 1 || userNum <= 100)
{
for (int i = 0; i < value; i++)
System.out.print("*");
if(userNum >= 1 && userNum <= 10)
}
}
}
Any help will be appreciated and if I haven't mentioned anything that I should specify let me know
Thanks
I don't think it would be beneficial for you if I just write you the program because this looks like exercise or homework, so let's work this out together. The program should run like this:
USER INPUT
If: 1..100 => PUT in the correct range and do 1)
Quit
The first observation is that
int userNum = input.nextInt();
needs to happen inside a loop, called the event loop. The structure is one big loop, that does the steps as stated above.
Now there is a better way to keep track of the ranges. Whenever you see yourself writing variables like var1, var2... you are better off with an array of values. The best would be to use an array of integers, where each index represents one range, something like this:
[0] 1-10
[1] 11-20
[2] 21-30 ...
and then you can just increment the correct index.
For instance, the user types in 34, you work out with the modulo operator where it goes and insert it.
Then I am sure you can find a smart way to print the final string. The best would be to create a separate print function for the array, something like:
printCounts(int[] count) { ... }
Hope those help, feel free to ask follow-up questions :)
Related
Java novice here, trying to scan through the input in the form below:
3
3 3
101
000
101
1 2
11
5 5
10001
00000
00000
00000
10001
(The first digit is the number of test cases, followed by row and column, and 0s and 1s is the state of the world, and so on. Basically, like any typical BFS questions)
Below is a part of my Java code where I'm trying to get the input from the console. The comments are the values I see in the watch section while debugging:
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // t: 3, in.nextInt(): 3 as expected
for (int i = 1; i <= t; i++) { // i: 1, t: 3, in.nextInt(): 3 (not sure which "3")
int row = in.nextInt();
// after this line in.nextInt(): 101 and row: 0 which are all WEIRD
int column = in.nextInt();
// now here it's in.nextInt(): 2 and column: 2
int world[][] = new int[row][column];
// in.nextInt(): 11 now and as we see it changed its value when I didn't even call it
TreeMap<Integer, ArrayList<int[]>> distancesRandAcc = new TreeMap<Integer, ArrayList<int[]>>();
distancesRandAcc.put(0, new ArrayList<int[]>());
for (int j = 0; j < row; j++) {
int temp = in.nextInt();
char[] s = Integer.toString(temp).toCharArray();
for (int k = 0; k < column; k++){
world[j][k] = Character.getNumericValue(s[k]);
}
}
int result = calculateDeliveryTime(world, row, column, distancesRandAcc);
System.out.println("Case #" + i + ": " + result);
}
}
This does something weird that goes beyond 'common sense'. I was debugging line by line after putting all the inputs in the IntelliJ console and it seemed like in.nextInt() can't stop getting a random number of tokens at random lines regardless of whether I even called it or not.
When I tried to put the inputs line by line as well while debugging line by line and it seemed like one call of .nextInt is asking for two int values. (I typed in a number and entered but it still waited for another input while staying in the same line where .nextInt() is just called just once)
At this point, I'm getting the feeling that my debugging process is wrong or at least it's some external problems rather than the code itself. I might be wrong as I still consider myself a novice...
Please, could somebody more experienced teach me how to get around this problem? I found a few questions having similar-looking problems with .nextLine() and .nextInt() but not exactly this. I apologise in advance if it's really a duplicate, though...
(I'll add more info if needed)
You are calling nextInt(), so input 000 is parsed as the number 0 and the int return value is therefore 0. Integer.toString() will therefore return the string "0". Why are you surprised about that?
Since you don't actually care about the input as a number, just use next:
for (int j = 0; j < row; j++) {
String s = in.next();
for (int k = 0; k < column; k++) {
world[j][k] = Character.getNumericValue(s.charAt(k));
}
}
UPDATE
That is the only problem with the question code for reading the input. Whether there is a problem in the calculateDeliveryTime is unknown.
See IDEONE for proof. The calculateDeliveryTime method simply prints the 2D array, so it can be seen that the input has been handle ok.
I have some doubts as to why the value of index is not incrementing here.
The reason why I have declared my array like that is because I need to store n natural numbers where (1 ≤ n ≤ 1012), so numbers are large which is why I have taken an array of type long, but then I get an error that I cannot put any long value in the group, which is why I cast it to int. Is there any way to declare an array for this type of condition, as I want a large number of indexes, and I can not put a long number in the [ ].
hope you guys understand my problem
CODE:
import java.util.Scanner;
class Error{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long array[] = new long[(int) n];
long index = 0;
for (int j = 1; j <= n; j++) {
if (j % 2 != 0) {//odd
array[(int) index++] = j;
System.out.print(" " + array[(int) --index]);
System.out.print(index);// index value -> always 0 why??
System.out.print(j);
}
}
System.out.println();
}
}
OUTPUT:
Unix-Box ~/Desktop$ javac Error.java
Unix-Box ~/Desktop$ java Error
10
101 303 505 707 909
Unix-Box ~/Desktop$
the middle value is of index and it is always 0
what i shout it to be like
10
101 313 525 737 949
Unix-Box ~/Desktop$
According to
https://www.quora.com/What-is-the-maximum-size-of-the-array-in-Java,
the max size of an array is 2147483647 theoretically, but in practice we would want to use 2147483600 to be safe. Declaring the array as type long will mean that long values can be stored inside. Maybe you can use a two dimensional array to store a long n amount of values. Something like--
public static void main(String[] args)
{
System.out.println("enter the size of the array:");
Scanner in = new Scanner(System.in);
long n = Long.parseLong(in.nextLine());
int secondIndex = 2147483600;
int firstIndex = ((int)(n/secondIndex))+1;
if(secondIndex > n)
{secondIndex = (int)n;
}
else{int leftover = (int)(n%secondIndex);
secondIndex = secondIndex - leftover;}
long[][] array = new long[firstIndex][secondIndex];
//loop through array
outerloop:
for(int i =0;i <firstIndex; i++)
{
for(int z = 0; z<secondIndex; z++)
{
System.out.println("do work with number here: " + array[i][z]);
if(z==(secondIndex-1))
{
z=0;
continue outerloop;
}
}
}
}
You might get a java.lang.OutOfMemoryError:, which can be resolved by reading this article https://plumbr.eu/outofmemoryerror/java-heap-space.
As others have indicated,
array[(int) index++] = j; // You use index and then increment it
System.out.print(" " + array[(int) --index]); // You decrement the index here
That's why index will always be 0 when you print it.
Personally, I don't like mixing brackets with increment operators for the precise reason you're seeing here - it tends to be confusing and it lends itself to subtle (and not-so-subtle) bugs and off-by-one errors. In fact, I really don't like mixing them with any other syntax (with the exception of for loops) as it can quickly become very unclear. For example, if you had done something like
index++;
array[(int)index] = j;
index--;
System.out.print(" " + array[(int)index]);
the problem would've been obvious immediately.
In general, it's a bad idea to sacrifice clarity for brevity.
Also, just to review how the operators in question are working:
index++ - use the value and then increment it
index-- - use the value and then decrement it
++index - increment the value and then use it
--index - decrement the value and then use it.
Here's a C# code sample I put together (Java's behavior will be identical) to illustrate this:
int i = 0;
Trace.TraceInformation((i++).ToString()); // Prints 0
Trace.TraceInformation(i.ToString()); // Prints 1
Trace.TraceInformation((--i).ToString()); // Prints 0
Trace.TraceInformation((i--).ToString()); // Prints 0
Trace.TraceInformation(i.ToString()); // Prints -1
I'd encourage you to trace/step through this to convince yourself that that's the case and to understand exactly why the value is what it is at every point.
Either way, this syntax can be very confusing if overused.
I need to complete this task. But I am not entirely sure how to get the range into the array. I think I am supposed to use a loop somehow but I do not get it to work.
This is what I have so far:
import java.util.*;
public class A2_1
{
static Scanner x = new Scanner(System.in);
public static void main(String[] args)
{
int [] myArray = new int [1000000];
int x;
for ( x = 0; x <= 100; x++)
{
myArray [x] = x+1;
}
System.out.println(myArray);
}
}
This is the task:
"Create a program that generates 1,000,000 integer random values in the range of [1,..,100] and for any given x (between 1 and 100) taken from the user input computes "(𝑇𝑜𝑡𝑎𝑙 𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑒𝑙𝑒𝑚𝑒𝑛𝑡𝑠 𝑙𝑒𝑠𝑠 𝑡ℎ𝑎𝑛 𝑜𝑟 𝑒𝑞𝑢𝑎𝑙 𝑡𝑜 𝑥)/1,000,000".
This value must be comparable to the CDF of a uniform distribution U[1,100] at point x."
Im not going to give you the answer since this sounds like homework but I will help you break it down into manageable chunks.
First, generate 1000000 random numbers between 1 and 100. You were on the right track and combine it with Dawnkeepers hint. int[] randoms = new int[1000000]; is an int array with a size of 1000000. Now iterate over each index and assign it a random number(see above). Now you have an array with a million random numbers. Generating a million randoms can be a lengthy procedure depending on you machine, so yea.
Next, use the Scanner class to get the users input.(pro tip: dont use the same variable name for your scanner as your variable in the for loop lol). Now do an if check to make sure they enter a number between 1 and 100. if(val > 0 && val <= 100). If this passes, move on, else quit or prompt for user to give a new input. Using the scanner is pretty trivial so I wont go into this.
Finally, iterate through your list of randoms and keep a counter of how many numbers less then or equal to x.
int counter = 0;
for(int i = 0; i < randoms.length; i++) {
//if randoms[i] is less then or equal x, counter++
}
Take that counter and do your math, int final_answer = counter/randoms.length;
That's all that is to it. There are more efficient ways of doing this but I tried to make it simple to follow. If I misread the question, sorry.
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;
}
What I'm trying to do is have a loop to get a users input, convert it to an integer, create a variable and store the integer to that new variable. If the user doesn't input the word "end" it will continue to do this until the user does so. The thing I'm having trouble with is creating the variables. I'd like to just have them a, b, c, d, e, and so on. The rest of the program I can do, just need pointed in the right direction for this.
If you don't know how many values you're going to get, you really need to store them in a Collection such as a List.
What are you going to do with the values once they are all input?
I would use a array for this and it sounds like you need two variables:
String sInput;
int iInput[];
Then in your loop you can test to see if sInput is a number and not "end" after which you can parse it to your array:
iInput[index] = Integer.parseInt(sInput);
later you can then access each element in the array iInput[0], iInput[1]...
Be aware you must define the array size and when you do in Java you can not change it or make it bigger.
I hope this gets you going.
If you are in a loop, odds are you don't need a new variable for every iteration in the loop, so instead of having a solution like
int input1;
int input2;
int input3;
int input4;
int input5;
for (int index = 0; index < 5; index++) {
if (index == 0) {
input1 = getInput();
}
if (index == 1) {
input2 = getInput();
}
if (index == 2) {
input3 = getInput();
}
if (index == 3) {
input4 = getInput();
}
if (index == 4) {
input5 = getInput();
}
}
you can probably live with a solution like
int input;
for (int index = 0; index < 5; index++) {
input = getInput();
... handle input before going through next loop iteration ...
}
note that solutions which use the switch statement are just optimizations of the undesirable "too many if's" solution.