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.
Related
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.
Write a java programm to print a output like this
input : d3f4cf5
output dddffffcfcfcfcfcf
for(int i=0; i<str.length();i++)
{
if(Character.isDigit(str.charAt(i)))
{r = str.charAt(i);
for(r=1;r<=i;r++) {
System.out.println(str.substring(t, i));
t = ++i;
}
}
if (i==str.length()-1) {
for (r = 1; r <= i; r++) {
System.out.println(str.substring(t));
}
}
}
Well, as Ronald suggested you could split your string and run over the arrays.
For how to split have a look here: Java - Split String by Number and Letters
Let's assume we then just have the array ["d","3","f","4","cf","5"]. You then could do something like this:
for( int i = 0; i < array.length; i += 2 ) {
String letters = array[i];
int count = Integer.parseInt( array[i + 1] );
//loop and print here
}
Note that this always expects the string to start with at least one letter and end with a number. If it doesn't you'd have to handle that explicitly, i.e. don't print anything for the first number if it starts with a number (that could be done by just "printing" an empty string n times) and assume a count of 1 if the input ends with letters.
If you can't use regular expressions for some reason you could also do it while iterating over the characters of the string. You'd then use a combination of the following steps:
If the character is a letter you're in string building mode. You add the character to a temporay string. Initially that temporary string would be empty.
If the character is a digit you're in counting mode. You add the digit to a temporary counter (which you'd first multiply with 10 if you want to support more than one digit numbers). The counter would initially have the value 0.
When you switch from counting mode to string building mode you print the current temporary string as often as you've counted, then reset the counter to 0 and the temporary string to empty ("") and repeat step 1 (you add the current character to the temp string).
When you hit the end of the input you do the same as in step 3. If you need to support input ending in letters you'd probably want to assume a count of 1 so before executing step 3 you'd set the counter (which should still be 0) to 1.
If your input is well formed something like below should work:
public static void main(String[] args){
String input = "d3f4cf5";
System.out.println(uncompress(input));
}
private static String uncompress(String input) {
//Split input at each number and keep the numbers
// for the given input this produces [d3, f4, cf5]
String[] parts = input.split("(?<=\\d+)");
StringBuilder sb = new StringBuilder();
for(String str : parts){
// remove letters to get the number
int n = Integer.parseInt(str.replaceAll("[^0-9]", ""));
// remove numbers to get the letters
String s = str.replaceAll("[0-9]", "");
// append n copies of string to sb
sb.append(String.join("", Collections.nCopies(n, s)));
}
return sb.toString();
}
I am exercising for my course in java and the task is to write a program which has the input of a list separeted with spaces. And the key is to turn the list around, i.e. put the first place on the last second on the one before last and truncate the negatives. But I am keep getting this error of StringIndexOutOfBounds. What seems to be the problem?
public static void main(String args[])
{
Scanner in = new Scanner (System.in);
System.out.println("Insert the list: ");
String input = in.nextLine();
String out = out(input);
System.out.println(out);
}
public static String out (String input){
String reverse = "";
int counter = 0;
while (counter<=input.length()){/*
String min = input.charAt(counter) + input.charAt(counter+1);
int num = Integer.parseInt(min) ;
if ( num>=0 ){*/
reverse+= input.charAt(counter);
counter++;
/*}*/
}
return reverse;
}
I suspect your StringIndexOutOfBounds comes from the fact you are iterating from index 0 to index input.length, so 1 too many.
For the sake of charAt the Strings in Java are 0-indexed, so you start counting from 0 (what you would call 'first' in plain English). In such a situation, the last character is at index length-1.
So, to be specific. Your next thing to fix is the condition in the while loop. I think your intention was to say:
while (counter < input.length()) {
...
Any String has characters from index 0 to length-1. If you would try to do charAt(length), you would end up with StringIndexOutOfBounds.
Change the while line to below & it should work:
while (counter<input.length()){
So my teacher gave me an assignment to do (will be shown below) and I tried to do it but just could not figure it out, here's the assignment:
Consider the following program that allows something like 8 + 33 + 1,345 + 137 to be entered as String input from the keyboard, A Scanner object then uses the plus signs (and any adjoining white space) as delimiters and produces the sum of these numbers (1523).
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1,345 +137 : ");
String s = kb.nextLine( ); //Best to store in a String and then create a new Scanner
//object; otherwise, it can get stuck waiting for input.
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
sum = sum + sc.nextInt( );
}
System.out.println("Sum is: " + sum);
}
}
Now modify the program as to allow either plus or minus signs
^^^THAT WAS THE ASSIGNMENT^^^
Here is my source code:
//I can't get it to work if I use subtraction and addition at the same time but they work separately
import java.util.Scanner;
public class AddEmUp {
public static void main(String[] args) {
//Here we create a String
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine();
//Now we convert the String to a scanner because we will be using Scanner methods
Scanner sc = new Scanner(s);
//Creates sum
int sum = 0;
//Does it's magic if it is addition
if (s.contains("+")) {
sc.useDelimiter("\\s*\\+\\s*");
while (sc.hasNextInt()) {
sum = sum + sc.nextInt();
}
}
//Does it's magic if it is subtraction
if (s.contains("-")) {
sc.useDelimiter("\\s*\\-\\s*");
while (sc.hasNextInt()) {
sum = sc.nextInt();
sum = sum - sc.nextInt();
}
}
//Prints the magic
System.out.println("Sum is: " + sum);
}
}
Can anybody help me solve the problem (First comment in my source code)???
I'm going to help you answer this in a way that's (hopefully) consistent with what you've learned so far. Since you haven't learned about arrays yet and are working with a Scanner with a delimiter pattern, we'll have to work around this constraint.
First, for the purposes of a school assignment, we can probably safely assume that your inputs will follow a particular pattern, along the lines of: (number)(operator)(number)(operator)(number)... and so on; additionally, you're probably not worried about input checking (making sure there are no letters/symbols/etc) or negative numbers, so we'll ignore those scenarios. Since you are only dealing with + and -, your delimiters are "\\s*\\+\\s*" and "\\s*\\-\\s*", respectively. Since these values don't change (they are constants), and (in a real program) would be used multiple times in different places, we typically store these in their own final variables:
final String PLUS = "\\s*\\+\\s*"; // by convention, constants in java are named with all caps
final String MINUS = "\\s*\\-\\s*";
Now, let's look at your sample input: 8 + 33 + 1345 - 137. How can you account for mixed operators?
int sum = 0;
Scanner sc = new Scanner(s); // s = "8 + 33 + 1345 - 137"
//What now?
You can still pull this off with one loop, but it will require some intermediate steps.
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
}
// first pass, temp = "8"
// first pass, temp = "3"
// first pass, temp = "1345 - 137" (!!!)
In the above example, temp would first be "8" (note that it's a String here), then "33" on the next pass, then "1345 - 137" on the third pass. You would typically use Integer.parseInt() to turn a String to an int, like so:
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
sum += Integer.parseInt(temp);
}
// first pass, temp = "8"
// first pass, temp = "3"
// first pass, temp = "1345 - 137", code breaks at Integer.parseInt(temp)
However, this code breaks on the third pass, because "1345 - 137" is clearly not an integer value. This is where storing the value in temp comes into play; you can use a nested loop to evaluate subtraction portions of your expression! You were on the right track with checking for + and - in the input, and here is a more appropriate spot to use it:
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
// check if there are - signs in temp
if(temp.contains("-")){
// if there are, evaluate the subtraction expression
// for this example, temp = "1345 - 137"
Scanner sc2 = new Scanner(temp);
sc2.useDelimiter(MINUS);
int diff = sc2.nextInt(); // diff = 1345
while(sc2.hasNext()){
diff -= sc2.nextInt(); // diff = 1345 - 137 = 1208
}
sum += diff; // adds the result to the sum
} else {
sum += Integer.parseInt(temp); // there is no - sign, so skip ahead and just add to the sum
}
}
You'll notice I didn't check if the input contains a + sign at the beginning before the loop; this is because I'm assuming that even if you enter something like 1 - 5 - 9, the Scanner will still return at least that whole string when sc.next() is called, which will still go into the inner loop, and the expression will still be evaluated. I haven't used a Scanner in a very long time, so if this assumption is incorrect, you'll have to fix that.
User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}