Ignoring characters using Scanner in Java - java

I want to take a multiple coordinate points, say (35,-21) (55,12)... from standard input and put them into respective arrays.
Let's call them x[] and y[].
x[] would contain {35, 55, ...} and y[] would contain {-21, 12, ...} and so forth.
However, I can't seem to find a way to get around the parenthesis and commas.
In c I was using the following:
for(i = 0; i < SIZE; i++) {
scanf("%*c%d%*c%d%*c%*c",&x[i],&y[i]);
}
However in Java I can not seem to find a way to get around the non-numeric characters.
I currently have the following in Java, as I am stuck.
double[] x = new double[SIZE];
double[] y = new double[SIZE];
Scanner sc = new Scanner(System.in);
for(int i=0; i < SIZE; i++) {
x[i] = sc.nextDouble();
}
So the question:
How would I ignore characters when reading in doubles from scanner?
A quick edit:
My goal is to keep the strict syntax (12,-55) on user input, and being able to enter multiple rows of coordinate points such as:
(1,1)
(2,2)
(3,3)
...

nextDouble() tries to fetch a double number from the input. It is simply not meant to parse the input stream and figure by itself how to interpret that string to somehow extract a number.
In that sense: a scanner alone simply doesn't work here. You could look into using a tokenizer - or you use scanner.next() to return the full string; to then do either manual splitting/parsing, or you turn to regular expressions to do that.

I would do it in multiple steps for improved readability. First it's the System.in retrieving using a scanner and then you split in order to get each group of coordinates separately and then you can work on them later, for whatever purposes.
Something similar to this:
Scanner sc = new Scanner(System.in);
String myLine = sc.nextLine();
String[] coordinates = myLine.split(" ");
//This assumes you have a whitespace only in between coordinates
String[] coordArray = new String[2];
double x[] = new double[5];
double y[] = new double[5];
String coord;
for(int i = 0; i < coordinates.length; i++)
{
coord = coordinates[i];
// Replacing all non relevant characters
coord = coord.replaceAll(" ", "");
coord = coord.replaceAll("\\(", ""); // The \ are meant for escaping parenthesis
coord = coord.replaceAll("\\)", "");
// Resplitting to isolate each double (assuming your double is 25.12 and not 25,12 because otherwise it's splitting with the comma)
coordArray = coord.split(",");
// Storing into their respective arrays
x[i] = Double.parseDouble(coordArray[0]);
y[i] = Double.parseDouble(coordArray[1]);
}
Keep in mind that this is a basic solution assuming the format of the input string is strictly respected.
Note that I actually cannot fully test it but there should remain only some light workarounds.

Mentioned that the user input is strictly restricted to (12,-55) or (1,1) (2,2) (3,3) ... formats the below code works fine
Double[] x = new Double[5];
Double[] y = new Double[5];
System.out.println("Enter Input");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
input = input.trim();
int index = 0;
while(input != null && input != "" && input.indexOf('(') != -1) {
input = input.trim();
int i = input.indexOf('(');
int j = input.indexOf(',');
int k = input.indexOf(')');
x[index] = Double.valueOf(input.substring(i+1, j));
y[index] = Double.valueOf(input.substring(j+1, k));
System.out.println(x[index] + " " + y[index]);
input = input.substring(k+1);
index++;
}
Here I have got the user input in string format and then trim method is called on it to remove the leading and tailing white spaces.
In the while loop the substring between '(' and ',' is taken into x[] and the substring between ',' and ')' is taken into y[].
In the loop the index is incremented and the input string is modified to the substring after the first occurrence of ')' and till the end of the string.
The loop is repeated till there is no occurrence of ')' or the input is null.

Related

Max limit on number of input in vs code 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.

How to check for a specific number of integers in a string

I have a program where i require the user to enter coordinates as a string. In order to make input easier to read and make inputs like (x,y) and x , y equal I first change all non numeric characters to " " then i try and use the .matches function to check for exactly two occurrences of integers
input = input.replaceAll("[^0-9]"," ");
Scanner lineRead = new Scanner(input);
System.out.println(input);
if(! (input.matches( "[//d] {2}" ) )
{
bad input
}
else
{
xPosition = lineRead.nextInt();
yPosition = lineRead.nextInt();
}
but no matter what I input the expression returns false. Im new to using regex is my syntax wrong or is this just not something I can do?
Rather than test the input against a regex, I believe the preferred way to use Scanner is to read the two ints you want, and catch certain exceptions if scanning does not succeed.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()
e.g.
input = input.replaceAll("[^0-9]"," ");
Scanner lineRead = new Scanner(input);
System.out.println(input);
try {
xPosition = lineRead.nextInt();
yPosition = lineRead.nextInt();
} catch (
InputMismatchException |
NoSuchElementException |
IllegalStateException ex) {
bad input
}
If you do want a regex that tests the input for the presence of at least two integers, I think the following would do:
\d+.*\b\d+
That's, one or more digits (\d+), followed by anything (.*), followed by a word boundary (\b), followed by another one-or-more-digits (\d+)
Use \\s*\\d+\\s+\\d+\\s* instead of [//d] {2}.
You can avoid using a regex and just "searching" for the first and the second number. You start when you hit a number between 0 and 9 and stop, when you hit a non-digit. Repeat the same for the second number and you are good to go!
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
/* Search the first number */
int i = 0;
while (i < string.length() && !Character.isDigit(string.charAt(i))) i++;
int j = i;
while (j < string.length() && Character.isDigit(string.charAt(j))) j++;
int firstCoordinate = Integer.parseInt(string.substring(i, j));
/* Search the second number */
i = j + 1;
while (i < string.length() && !Character.isDigit(string.charAt(i))) i++;
j = i;
while (j < string.length() && Character.isDigit(string.charAt(j))) j++;
int secondCoordinate = Integer.parseInt(string.substring(i, j));

Integers from a String to an Int array

I'm writing a simple tic tac toe game and need to accept user input during their turn. The player should simply provide a set of coordinates for where to place their token (1,1) to (3,3). I am supposed to be able to accept input as either "2 1" or "2,1" or "2, 1". So I need to be able to take their String input and pull out each of the two numbers, regardless of delimiter and use them to assign their token to the specified cell in the 3x3 array.
The major catch is only being able to utilize stuff we've been taught already (this is the first quarter of Java). This is the first seven chapters of Building Java Programs which consists of Scanner, conditionals/logic, loops and arrays. No patterns, matchers, lists, etc.
Is there a way to accomplish this using only the String class, scanner, or arrays?
Just using the String class, you can use String.split() to get an array of strings which can then be parsed to Integers
public class Example{
public static void main(String []args){
String str = "2 1";
// first split the original string on a comma
String[] str_arr = str.split(",");
// if the length is one then there were no commas in the input, so split again on white space
if (str_arr.length == 1){
str_arr = str.split(" ");
}
int[] int_arr = new int[str_arr.length];
// assign the string array to an int array
for (int i = 0; i < str_arr.length; i++){
int_arr[i] = Integer.parseInt(str_arr[i]);
}
// output to console
for (int j : int_arr){
System.out.println(j);
}
}
}
Updated
Forgot to add "" to convert char to String.
Scanner input = new Scanner(System.in);
String userInput;
String[] coordinates = new String[2];
char character;
int length;
userInput = input.nextLine();
length = userInput.length();
if(length > 2){
coordinates[0] = "" + userInput.charAt(0);
character = userInput.charAt(2);
if(character != ',' && character != ' '){
coordinates[1] = "" + character;
}
else{
coordinates[1] = "" + userInput.charAt(3);
}
}
Explained:
We use an Array to store the two positons you need.
We use a Character to store read in input positions.
We get the length of the read input. This is to validate if it is correct. Since the correct input should be at least more than 2 characters.
We know that the first position is valid so we assign it immediately.We also know that the second position cannot be valid so we skip it (charAt(2) and not charAt(1)) Then we check if the third position is valid if not we assign the fourth position.
Goodluck!

Java. Quadratic formula program with variables a, b, and c read from file. Unexpected error

I'm making a program that reads from a file 3 numbers, doubles or integers, per line except the first one. The first line is the the number of lines after. The 3 numbers in each line are variables a, b, and c in the quadratic formula. Then the program is supposed to return the difference between the + and - part of the formula. Here is an example of what the file may contain.
3
1 2 4
1.5 3.12 4.31
0.09 5 2
My problem is the when using scanner to turn the tokens in the file into doubles so that they can be inputted to the quadratic formula, I am getting the following error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "­1"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
at java.lang.Double.parseDouble(Double.java:540)
at gorf.main(gorf.java:23)
here is part of my code:
int lines = Integer.parseInt(sc.nextLine());
double a;
double b;
double c;
String line = "";
Scanner abc = new Scanner(line);
for(int count = 0; count < lines; count++)
{
line = sc.nextLine();
abc = new Scanner(line);
a = Double.parseDouble(abc.next());
b = Double.parseDouble(abc.next());
c = Double.parseDouble(abc.next());
}
Your file is not clean. You have hidden non-visible characters in there.
Use the following code to uncover the character that is causing you grief:
int lines = Integer.parseInt(sc.nextLine());
double a;
double b;
double c;
String line = "";
Scanner abc = new Scanner(line);
for (int count = 0; count < lines; count++) {
line = sc.nextLine();
abc = new Scanner(line);
a = Double.parseDouble(readNextAndLog(abc));
b = Double.parseDouble(readNextAndLog(abc));
c = Double.parseDouble(readNextAndLog(abc));
}
readNextAndLog method:
private static String readNextAndLog(Scanner sc) {
String s = sc.next();
for (int i = 0; i < s.length(); i++) {
System.out.println((int)s.charAt(i));
}
return s;
}
Pay attention to the numbers printed just before the exception occurs. The problematic character's Unicode value will be printed there.
You'll then have to figure out how the unexpected got in your file in the first place and get rid of it, or recreate your file from scratch.
EDIT:
Your problematic character is the SOFT HYPHEN (U+00AD) character.
This character is not supposed to be invisible, but is known to be handled/rendered inconsistently. (Yes, SOFT HYPHEN is a hard problem)
Make sure your file doesn't contain that character. Make sure you use an editor that doesn't mess with your file in some unexpected way. An editor like Notepad++ for example.

Convert numbers into word-numbers (using loop and arrays)

How do I write a simple program that converts numbers into word-numbers, using loops and arrays?
like this: input: 1532
output: One Five Three Two
Here's what I tried:
class tallTilOrd
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
String [] tall = {"null", "en" , "to", "tre", "fire" ,
"fem", "seks", "syv", "åtte", "ni", "ti");
System.out.println("Tast inn et ønsket tall");
int nummer = input.nextInt();
for (int i = 0; i<tall.length; i++)
{
if(nummer == i)
{
System.out.println(tall[i]);
}
}
}
}
Scanner input = new Scanner (System.in);
String in = Integer.toString(input.nextInt());
String [] tall = {"null", "en" , "to", "tre", "fire" , "fem", "seks", "syv", "åtte", "ni", "ti"};
for(char c : in.toCharArray()){
int i = (int) (c-'0');
for (int j = 0; j<tall.length; j++) {
if(i == j){
System.out.print (tall[j] + " ");
}
}
}
I give you a hint:
You could convert your Integer input into a String and then process each Character of that string. Check out the javadoc for String to figure out how to do it ;-)
Now I'm not sure this is the perfect way to do it, but it would be a possible one.
Instead of iterating over the length of your tall array, you need to iterate over the digits of nummer (to do this, check out the methods String.valueOf(int), String.charAt(int) and String.length()). Then use those digits as indices for tall to get their string representation.
A few notes:
In the code you provided, you need to use == instead of =. == is for comparison, = is for assignment.
Instead of looping through the predefined array, loop through the input. Instead of treating the number entered as an int, treat it as a string and then convert each character in the string into a number, which you can use as an index to fetch the corresponding string from your array.
Also, note that println prints a newline each time.

Categories

Resources