im struggling with the below question.
Question: Input contains the number of blocks n (1 ≤ n ≤ 20) and weights of the blocks w1, …, wn (integers, 1 ≤ wi ≤ 100000) delimited by white spaces. the input should be taken from the user.
please find my code:
public static void main(String[] args) {
int b1 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of blocks: ");
b1 = in.nextInt();
if (b1<=20) {
in.nextLine();
int[] arr = new int[b1];
for (int i=0; i<b1; i++) {
System.out.println("Enter a weights of ths blocks: ");
if (arr[i]<=100000) {
arr[i] = in.nextInt();
}
}
}
i dont think this is the right way coz the input should be delimited with spaces..
i was thinking about the ways to proceed but couldnt come up with any solution. can u please help me our on this guys. thanks.
The input can be given at command line as "input1 input2 input3" (Weights separated by spaces)
You can use Scanner to read the input. Consider the sample code below:
Assuming the input is only integers.
Scanner scanner = new Scanner(System.in);
int numOfBlocks = scanner.nextInt();
int weightArray[] = new weightArray[numOfBlocks];
for(int i=0;i<numOfBlocks;i++)
{
weightArray[i] = scanner.nextInt();
}
scanner.close();
//your logic
There's a very easy way to read input delineated by spaces: use string.split(delimit):
String input = "this is a test";
String[] tokens = input.split(" ");
That'll give you an array, tokens, of "this", "is", "a", and "test".
Then you can convert to an int array like this:
int[] inputNumbers = new int[tokens.length];
for(int i = 0; i < tokens.length; i++) {
inputNumbers[i] = Integer.parseInt(tokens[i]);
}
Just make sure that you are sure that you have numbers as an input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With