Max limit on number of input in vs code java - java

I am trying some algorithm which requires large no of input samples for testing but at a time I cannot take input more than certain number of times.
N = sc.nextInt();
...
int[] arr = new int[N];
for(int i=0; i<N; i++){
arr[i] = sc.nextInt();
}
for(int elem: arr){
System.out.println(elem+" ");
}
Input format is
N
//HERE GOES ARRAY ELEMENTS
where N- no of element in array
I'm using this user input test_case_1, but I can only input fraction of the given values.
I wanted to know what is restricting the number of input in vscode

Usually, using a scanner is perfectly alright. But with input samples of up to 90 000, which seems to be test case 1, it might be very slow due to excessive flushing.
Something like this might be more effective:
BufferedReader br = new BufferedReader(new FileReader("temp_code_input.txt"));
...
int N = Integer.parseInt(br.readLine());
...
StringTokenizer st = new StringTokenizer(br.readLine());
/*
Assumes every input is on the same line. If not, create a new StingTokenizer
for each new line of input.
*/
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
for (int elem : arr) {
System.out.println(elem)
}

I'm just manually inputting the values by pasting it
It would be easier for you to just read this input from a file with the Scanner class.
String s = Files.readString("PATH_TO_YOUR_FILE", StandardCharsets.US_ASCII);
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// find the next int token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is a int, print found and the int
if (scanner.hasNextInt()) {
//Store the data here ...
}
// if no int is found, print "Not Found:" and the token
System.out.println("Not Found :" + scanner.next());
}

When i test the input you provided, it stops and not accept more numbers when i paste them, so i ask in github: Limit max number of terminal input then get the reply:
when I paste your example input into the terminal, it succeeds
(although takes quite awhile) - what you might be seeing is the output
(pasted text) trimmed relative to what you're expecting because of the
maximum terminal scrollback which can be configured with
terminal.integrated.scrollback
So please waiting because it would succeed that pasting the input. Enlarge the value of terminal.integrated.scrollback in Settings.json to check the output.

Related

How to separate integer inputs

I need to use scanner to get 2 inputs.
1st input is a sequence of integers that I need to store in ArrayList.
2nd input should go right after the first one and it's integer as well.
My question is - how do I stop accepting input for ArrayList and tell the machine to ask for a second number.
I ended with something like this but it does not of course work because it just keeps asking for integers for arraylist. And yes, I need to use ArrayList for the task, since I don't know how many integers there will be. I also haven't learned List interface yet so I need to use what I have in my disposal.
while (scanner.hasNextInt()) {
numbers.add(scanner.nextLine());
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
}
I managed to solve it this way, though probably not optimal
String inputString = scanner.nextLine();
String[] inputArray = inputString.split(" ");
int[] numberArray = new int[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
numberArray[i] = Integer.parseInt(inputArray[i]);
}
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
if your input sequence is something like 23 34 54 46 then you can use this
Scanner scanner = new Scanner(System.in);
String integers = scanner.nextLine();
StringTokenizer string = new StringTokenizer(integers);
ArrayList<Integer> list = new ArrayList<Integer>();
while(string.hasNextToken()){
list.add(Integer.parseInt(string.nextToken()));
}

How would I go about using an integer delimiter? (Java)

So I am trying to read a file using a scanner. This file contains data where there are two towns, and the distance between them follows them on each line. So like this:
Ebor,Guyra,90
I am trying to get each town individual, allowing for duplicates. This is what I have so far:
// Create scanner for file for data
Scanner scanner = new Scanner(new File(file)).useDelimiter("(\\p{javaWhitespace}|\\.|,)+");
// First, count total number of elements in data set
int dataCount = 0;
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.println();
dataCount++;
}
Right now, the program prints out each piece of information, whether it is a town name, or an integer value. Like so:
Ebor
Guyra
90
How can I make it so I have an output like this for each line:
Ebor
Guyra
Thank you!
Assuming well-formed input, just modify the loop as:
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.print(scanner.next());
System.out.println();
scanner.next();
dataCount += 3;
}
Otherwise, if the input is not well-formed, check with hasNext() before each next() call if you need to break the loop there.
Try it that way:
Scanner scanner = new Scanner(new File(file));
int dataCount = 0;
while(scanner.hasNext())
{
String[] line = scanner.nextLine().split(",");
for(String e : line) {
if (!e.matches("-?\\d+")) System.out.println(e);;
}
System.out.println();
dataCount++;
}
}
We will go line by line, split it to array and check with regular expression if it is integer.
-? stays for negative sign, could have none or one
\\d+ stays for one or more digits
Example input:
Ebor,Guyra,90
Warsaw,Paris,1000
Output:
Ebor
Guyra
Warsaw
Paris
I wrote a method called intParsable:
public static boolean intParsable(String str)
{
int n = -1;
try
{
n = Integer.parseInt(str);
}
catch(Exception e) {}
return n != -1;
}
Then in your while loop I would have:
String input = scanner.next();
if(!intParsable(input))
{
System.out.print(input);
System.out.println();
dataCount++;
}

How do I take a users input, add that to a new scanner, and then scan the input into an array?

I'm trying to create a program that takes the user's input and then scans the user's input into an array with a for loop. That way I can loop through the array to find if the string is a word palindrome or not. A word palindrome differs from a palindrome in that it is the whole word in reverse rather than each individual letter in reverse. When the program that I wrote prints it just prints null, which I believe means that it's not storing what the scanner scanned.
Below is what I've written:
String userInput, scannedWord;
Scanner keyboard = new Scanner(System.in); //scanner for user input
System.out.print("Please enter a sentence: ");
userInput = keyboard.nextLine(); //stores user input
Scanner stringScan = new Scanner(userInput); //scanner to scan through user input
int userInputLength = userInput.length(); //to find word count
int wordCount = 0; //for array size
for (int i = 0; i < userInputLength; i++) //finds word count
{
while(stringScan.hasNext())
{
scannedWord = stringScan.next();
wordCount = wordCount + 1;
}
}
String stringArray[] = new String[wordCount];
for (int i = 0; i < userInputLength; i++) //should store scanned words into the array
{
while (stringScan.hasNext())
{
scannedWord = stringScan.next();
stringArray[i] = scannedWord;
}
}
System.out.println(Arrays.toString(stringArray)); //how I've checked if it's storing
You've got some funky logic going on here. A few things:
userInput = keyboard.nextLine(); //stores user input
int userInputLength = userInput.length(); //to find word count
userInputLength is the length of the userInput string, which is the number of characters in the string, not the number of words.
It looks like the while loop is used simply to calculate the required size of the array, but the outer for loop is not required. You're effectively saying, for every character in the input string, while the scanner has another word, count the word, which doesn't make much sense.
You do something similar in your second for loop, which also doesn't make much sense.
for (int i = 0; i < userInputLength; i++) //finds word count
{
while(stringScan.hasNext())
{
scannedWord = stringScan.next();
wordCount = wordCount + 1;
}
}
It would be easier to use a List and save yourself the trouble that comes with fixed size arrays. You can just initialize the list and add things to it without caring about how big it is.
List<String> words = new ArrayList<String>();
words.add(word1);
words.add(word2);
Here's some code to simplify your problem a little:
Scanner keyboard = new Scanner(System.in); //scanner for user input
System.out.print("Please enter a sentence: ");
String userInput = keyboard.nextLine(); //stores user input
Scanner stringScan = new Scanner(userInput); //scanner to scan through user input
List<String> words = new ArrayList<String>();
while (stringScan.hasNext())
{
String scannedWord = stringScan.next();
words.add(scannedWord);
}
System.out.print(Arrays.toString(words.toArray())); // nasty! but you can see what's in the array for debugging

Ending a while loop without a sentinel

I have an array that can store up to 500 values. when I input 500 values, everything works as it should.. However, I would like to input as many values as I want, 500 or less, and still get an output. for example getting the average for any amount of numbers , 500 or less.
heres my while loop I have now that will not terminate until 500 numbers is reached:
public class StatsPackage{
static InputStreamReader isr = new InputStreamReader (System.in);
static BufferedReader br = new BufferedReader (isr);
String [] inputs = new String [500];
static int inputs2[] = new int [500];
double [] scores = new double [500];
int count;
static int lowest, temp, i = 0;
static double sum, mean, median, sumOfSquares, variance, stdDev;
static boolean even = (inputs2.length & 1) == 0;
static boolean odd = (inputs2.length % 1) != 0;
static double calcMean (int inputs2[],int count) throws IOException{
while(i < inputs2.length){
String inputs = br.readLine();
String [] Values = inputs.split ("\\s+");
inputs2 [i] = Integer.parseInt(Values[0]);
i++; }//end of while loop
for (i = 0; i < inputs2.length; i++){
sum = sum + inputs2[i];
}
mean = (sum/count);
return mean;
}
inputs is my number input string, values is a string array, and i parse the strings from "values" into my integer array, 'inputs2'
Any thoughts or help on how to terminate the loop early?
Sample Input-
49 66 73 56 3 39 33 77 54 29
Sample Output-
Mean: 47.90
Median: 51.50
Variance: 458.29
Standard Deviation: 21.41
You need end-users to tell you when they are done entering their numbers. This could be done in a number of ways. End-users could
Enter an agreed-upon number (say, -1),
Enter an empty string, or
Close the input stream by pressing Ctrl+D on UNIX or Ctrl+Z on Windows
In all cases you would need to store the count of how many elements you have stored in your inputs2 array, and use that index to run loops examining the active portion of the array. This is sub-optimal for two reasons:
You may allocate more memory than you actually need, and
Your users may want to enter more data than you have provisioned.
To fix both these problems, use ArrayList<Integer> instead of an array.
Here is an example implementation that exits when the user enters an empty line:
List<Integer> inputs2 = new ArrayList<Integer>();
while(true) {
String inputs = br.readLine();
String [] values = inputs.split ("\\s+");
if (values.length() == 0)
break; // Users entered an empty line, so we exit
for (int i = 0 ; i != values.length() ; i++) {
inputs2.add(Integer.parseInt(Values[i]));
}
} //end of while loop
Use a special value as loop terminator, eg, "-1", then use it in you while condition to end your loop. You could also check for this condition in the body of the while block and use the break statement.

JAVA- Returning an Array to main

In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main. When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.
In main:
// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);
In getAnswers():
// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
String input; // Holds user input.
Scanner keyboard = new Scanner(System.in);
// Request user input.
System.out.println("Enter the answers for the the multiple choice exam.");
// Loop to receive input into array.
for (int index = 0; index < 20; index++)
{
System.out.print("Enter number " + (index + 1) +": ");
input = keyboard.nextLine();
array2 = input.toCharArray();
}
return array2;
}
try
array2[index] = input.charAt(0);
after you obtain the value into the input variable instead of assigning it a new char array every time through the loop.
Right now you're creating a new array2 with each input and thereby destroying any previous input with the previous array2 that you created.
If you absolutely need to create a char array, why not append the String answers into a StringBuffer object, and then when done, call toString().toCharArray() on the StringBuffer.
Myself, I'd create an ArrayList and just append the response to the ArrayList and at the end return the ArrayList.
It is not good idea to modify the method param. You can try :
public static char[ ] getAnswers(char array2[ ])
{
String input; // Holds user input.
Scanner keyboard = new Scanner(System.in);
// Request user input.
System.out.println("Enter the answers for the the multiple choice exam.");
String tmp = "";
for (int index = 0; index < 20; index++)
{
System.out.print("Enter number " + (index + 1) +": ");
input = keyboard.nextLine();
tmp += input.chaAt(0); // check length is > 0 here
}
return tmp.toCharArray();
}

Categories

Resources