GOAL: To ask user for # of points. Then user will input "1 4", where 1 is the x and 4 is the y. I will take the sub-string to get 1 and 4 separately then make them an int so I can make them a Point.
I keep getting "java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
this is taking place on line 25, but not 24. When I use 3 instead of the length it also gives me this error.
This is a fragment of code:
public String run() {
String line = "";
String first = "";
String second = "";
int j = 0; int n = 0;
System.out.println("How many inputs do you want to enter?");
Scanner sc = new Scanner(System.in);
while(j == 0){
if(sc.hasNextInt()){
n = sc.nextInt();
Point[] points = new Point[n];
sc.close();
j++;
}
else {
System.out.println("invalid input");
}
}
Scanner scan = new Scanner(System.in);
for(int i = 0; i <= n; i++){
System.out.println("Enter x and y:");
line = scan.next();
first = line.substring(0,1);
second = line.substring(2,line.length());
}
scan.close();
origin(points);
return "";
}
See if this works for you. I'm not sure what your j variable was doing, your for-loop for the points was going out of bounds on the array, you are closing System.in between two separate Scanners, and obviously something wrong is happening with your substring logic.
This code fixes all those problems and runs great for me.
public String run() {
Scanner sc = new Scanner(System.in);
int n = numberPrompt("How many inputs do you want to enter?\n", "Invalid input");
Point[] points = new Point[n];
for(int i = 0; i < n; i++){
System.out.println("Enter x and y:");
String line = sc.nextLine();
String[] data = line.split("\\s+");
if (data.length >= 2)
{
int x = Integer.parseInt(data[0]);
int y = Integer.parseInt(data[1]);
points[i] = new Point(x, y);
}
}
System.out.println(Arrays.asList(points));
origin(points);
return "";
}
private int numberPrompt(String prompt, String error) {
Integer number = null;
boolean isValid;
String input;
Scanner sc = new Scanner(System.in);
do {
isValid = true; // reset the validity
System.out.print(prompt);
input = sc.nextLine();
try {
number = Integer.parseInt(input);
} catch (NumberFormatException e) {
isValid = false;
if (!(error == null || error.isEmpty())) {
System.out.println(error);
}
}
} while (!isValid);
return number;
}
Related
Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10]; //Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x=0; x<myArr1.length; x++) {
myArr1[x] = scanner.nextDouble(); //Gets user input
} //end of for
double sum1 = 0;
for(double x=0; x<myArr1.length; x++) {
sum1 += myArr1[(int) x]; //Defines sum1
} //end of for
double[] myArr2 = new double[10]; //Creates array
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int y=0; y<myArr2.length; y++) {
myArr2[y] = scanner.nextDouble(); //Gets user input
} //end of for
double sum2 = 0;
for (double y=0; y<myArr2.length; y++) {
sum2 += myArr2[(int) y];
} //end of for
System.out.println("Sum of first 10 elements is: " + sum1); //Prints sum of first 10 elements
System.out.println("Sum of second 10 elements is: " + sum2); //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) { //Catches errors in user input
System.out.println("Invalid input. Try again: ");
System.out.println("");
} //end of catch
}//end of do
while(z==1);
return;
}
}
You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, "Please enter a value: ", "Improper type, try again: ");
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}
Here is an example from your code.
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a number: ";
String error = "Invalid input, try again";
double[] myArr1 = new double[10]; // Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x = 0; x < myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for
Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.
or you can using while loop and a boolean value to get a number
Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false;
}catch(InputMismatchException e){
System.err.println("invalid input");
}
}
I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20]; //creates array
boolean on = true; //sets value "on"
while (on) { //starts while loop
System.out.println("Enter 20 numbers: ");
System.out.println("");
for (int i = 0; i < array.length; i++) { //creates user input prompt
Scanner input = new Scanner(System.in); //gets user input
try {
array[i] = input.nextDouble(); //assigns user input to array[i]
}/*end of try*/ catch (Exception e) { //catches invalid input
System.err.println("Invalid Input. Try again: ");
i = i - 1; //decrements index of re-entered number
} //end of catch
} //end of for
double x = 0;
for (int z = 0; z < 10; z++) {
x += array[z];
} //end of for
System.out.println("Sum of first 10 numbers = " + x); //adds first 10 numbers in array and assigns them to x
System.out.println("");
double y = 0;
for (int z = 10; z < 20; z++) {
y += array[z];
} //end of for
System.out.println("Sum of last 10 numbers = " + y); //adds last 10 numbers in array and assigns them to y
on = false; //breaks while loop
} //end of while
}
}
I am trying to ask scanner input until I get a valid answer but my while loop is not ending. First I am asking for user input, and then if the input is valid I am printing out the coordinates and if it is not valid I am throwing an error and asking for input again.
This is my code:
public static String[] positionQuery(int dim, Scanner test_in) {
String[] coordinates;
Scanner stdin = new Scanner(System.in);
System.out.println("Provide origin and destination coordinates.");
System.out.println("Enter two positions between A1-H8:");
String s1 = stdin.nextLine();
coordinates = s1.split(" ");
String origin = coordinates[0];
String dest = coordinates[1];
while (!validCoordinate(origin,dim) || !validCoordinate(dest,dim) || coordinates.length != 2) {
System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
Scanner stdin2 = new Scanner(System.in);
System.out.println("Provide origin and destination coordinates.");
System.out.println("Enter two positions between A1-H8:");
String s2 = stdin.nextLine();
coordinates = s1.split(" ");
String origin2 = coordinates[0];
String dest2 = coordinates[1];
}
return coordinates;
}
How can I fix it? I also tried a do while loop but still the loop is not terminating:
public static boolean validCoordinate(String coordinate, int dimension) {
String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int [] numbers = new int [dimension];
int one = 1;
for(int i = 0; i < dimension; i++){
numbers[i] = one + i;
}
String[] validC = new String [dimension]; //if the first char is a letter + a number that is determined my the dimension (string concat
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++){
validC [i] = alphabet[j] + Integer.toString(numbers[j]);
}
}
for(int i = 0; i < dimension; i ++) {
if(validC[i].equals(coordinate)) {
return true;
}
else {
return false;
}
}
return true;
}
This is the final code but still not ending :/
public static String[] positionQuery(int dim, Scanner test_in) {
Scanner scanner = new Scanner(System.in);
System.out.println("Provide origin and destination coordinates.");
System.out.println("Enter two positions between A1-H8:");
while(true) {
String line = scanner.nextLine();
String[] coordinates = line.split(" ");
if(coordinates.length == 2) {
String origin = coordinates[0];
String dest = coordinates[1];
if(validCoordinate(origin, dim) && validCoordinate(dest,dim)) {
return coordinates;
}
}
System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
}
}
I have a txt file where there are multiple paragraphs and they are delimited by a "%". I'm trying to find the maximum characters for every line in every separate paragraphs in order to make a padding. My problem is that it finds the maximum number of character overall, instead of finding the max in every paragraph/
int nmar = 0;
int max = 0;
while (input.hasNextLine()) {
input.useDelimiter("%");
String nume = input.next();
lines = linii;
Scanner scan = new Scanner(nume);
while (scan.hasNextLine()) {
String linecount = scan.nextLine();
nmar = linecount.length();
if (nmar > max) {
max = nmar;
} else if (nmar == 0) {
break;
}
System.out.println(max);
}
}
I moved the nmar and max inside the while to reset them at every paragraph, seems to work.
int nmar, max;
while (input.hasNextLine()) {
nmar = 0;
max = 0;
input.useDelimiter("%");
String nume = input.next();
Scanner scan = new Scanner(nume);
while (scan.hasNextLine()) {
String linecount = scan.nextLine();
nmar = linecount.length();
if (nmar > max) {
max = nmar;
} else if (nmar == 0) {
break;
}
}
System.out.println(max);
}
With this input
dkdjdhd\ndpepe%nd\njkfdlfrkefjrekl%dffd
I get
7
15
4
I know there's some way to change a string into an integer but it's not really working out for me when I try to do it.
I was asked to take in an integer 'n' and 'a' string 's' and print 's' 'n' times
Here's my code and my main question / question is how do I easily turn the string into an integer so I can multiply the two together:
public static void main(String args[])
{
System.out.println("Enter the number of times you want to print a string");
Scanner n = new Scanner(System.in);
int x = n.nextInt();
System.out.println("Enter the string you want printed");
Scanner y = new Scanner(System.in);
String s = y.nextLine();
}
You only need one Scanner, and if I understand your question then you might use a loop like, also an int n.
System.out.println("Enter the number of times you want to "
+ "print a string");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
for (int i = 0; i < n; i++) {
System.out.print(s);
}
System.out.println();
Of course, you could put the loop in a method like
private static String multiply(String str, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
Then you could call it like,
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
System.out.println(multiply(s, n));
I'm trying to figure out if there is a way for the user to enter two values on one line and put each value in a separate variable.
For example, I have an integer variable "x" and an integer variable "y". I prompt the user saying: "Enter the x and y coordinates: ". Lets say the user types: "1 4". How can I scan x=1 and y=4?
Scanner scn = new Scanner(System.in);
int x = scn.nextInt();
int y = scn.nextInt();
You could do it something like this:
public class ReadString {
public static void main (String[] args) {
System.out.print("Enter to values: x y");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String values = null;
try {
values = br.readLine();
String[] split = values.split(" ");
if(split.length == 2)
{
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
}else{
//TODO handle error
}
} catch (IOException ioe) {
System.out.println("IO error!");
System.exit(1);
}
}
}
String[] temp;
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
int[] arr = new int[2];
for (int i = 0; i < arr.length; ++i){
try{
int num = Integer.parseInt(in.next()); // casting the input(making it integer)
arr[i] = num;
} catch(NumberFormatException e) { }
}
input is your input of type String
String[] values = input.split(" ");
x = Integer.valueOf(values[0]);
y = Integer.valueOf(values[1]);