Why is the while loop never ending? - java

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.");
}
}

Related

Finding multiple set of given words in a paragraph array

I'm searching for word(s) in a string array and if found I want to return their line.
I have tried to divide the searched input in an array and then search it in the paragraph array line by line. Which does not really work.
public static void main(String[] args) {
String paragraph[] = new String[10];
String toBeSearched;
String curSearch;
boolean intIndex = false ;
paragraph[0] = "Hello my name is";
paragraph[1] = "Jack the reaper";
paragraph[2] = "what up";
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int j = 0 ;j <=10 ; j++) {
curSearch = divide[j];
for (int k = 0; k <=paragraph[j].length() ; k++) {
intIndex = paragraph[j].contains(curSearch);
if(intIndex == true) {
System.out.printf("Found at line %d \n",j );
}
}
}
Assuming I can search for at most 10 words at a time.
Lets say user enters : "Hello name the up"
I want the answer : At line 1
At line 1
At line 2
At line 3
If I ask for a word in the 2nd or the 3rd index of the paragraph it does not work I dont understand why (getting no error messages)
Here is a working code compare it to yours and figure out the issue:
public static void main(String[] args)
{
String paragraph[] = {"Hello my name is","Jack the reaper", "what up"};
String toBeSearched;
String curSearch;
boolean intIndex = false ;
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int i = 0; i < divide.length ; i ++) {
String word = divide[i];
for(int y = 0; y < paragraph.length ; y++) {
if(paragraph[y].contains(word)) {
System.out.println(word+ "found at line: "+ y);
}
}
}
}

Removing a user defined element from a user defined string array [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have an assignment due in about 6 hours and I really need help. I stayed up all night working on this but I can't seem to figure it out.
Basically what I need to do is, I have a user defined array. I'm supposed to take that array and manipulate that string into a variety of things. I've gotten most of it but I can't seem to remove a user defined element in the user defined string. I've tried using a for loop to try and find the specific character that the user wants to remove but I can't seem to get it to compile or write properly. This is my code so far:
import java.util.Scanner;
import java.util.Arrays;
public class StringManipulator {
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equals("Print Reverse") || choice.equals("print reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equals("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equals("Replace Single") || choice.equals("replace single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
else if (choice.equals("Remove") || choice.equals("remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
char charRemove = ridOf2.charAt(0);
for (int i = 0; i < array.length; i++) {
if(userStr.charAt(i) != ridOf2) {
userStr += userStr.charAt(i);
}
}
}
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
The only section that i'm actually worried about at this moment is the
else if(choice.equals("Remove")
section of the code.
Give this a shot explanation further down
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equalsIgnoreCase("Print Reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equalsIgnoreCase("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equalsIgnoreCase("Replace Single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
This is the section I changed .equalsIgnoreCase compares them ignoring case as expected. Then I made sure the user only entered one char and if more ignore them. Then changed the char remove to be a string of only the first char(because you cannot replace with a char it needs to be a string) then I replaced the char to be removed in the string with nothing essentially removing it and set the user string to the new user string
else if (choice.equalsIgnoreCase("Remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
String charRemove = String.valueOf(ridOf2.charAt(0));
userStr = userStr.replaceAll(charRemove, "");//This will replace the first char the enter with nothing
}
End of section
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
String's replace should do it -
public class Test
{
public static void main(String [] args) {
String s = "Hello World";
s = s.replace(" ", "");
System.out.println(s);
}
}

How is my String Index Out of Bounds?

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;
}

How do I add user input to an Array in java?

public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
for (i= 1; i <= n; i++) {
String g = a + i;
System.out.println(g);
}
}
This is my program. It gets user input for the Class and prints the Roll Number for the students.
For example: If the class is 10A and the number of students is 10, it prints a series like 10A1 , 10A2, 10A3 ... 10A10
How do I get the program to store these as elements in an array?
For example:
array[0] = 10A1;
array[1] = 10A2;
array[2] = 10A3;
etc.
Your code should look like this:
public static void main (String args[])
{
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
String []strings = new String[n]; // Creating an are of string with the given number
for(i= 0; i < n ;){
strings[i] = a + ++i; // Storing strings on to the array !
System.out.println(strings[i-1]);
}
}
You can just edit each index in your current for loop:
String[] arr;
for(i=0; i < n ; i++){
int j = i+1;
String g = a + j;
System.out.println(g);
arr[i] = g;
}
So all your printed g's will be part of the array arr.
First, declare a String array of the appropriate size.
Second, in your for loop, assign the strings you are currently printing, to positions in the array.
String[] things = new String[n];
for (i=1; i <= n; i++) {
String g = a + i;
System.out.println(g);
things[i-1] = g;
}
The strings are now in an array.
Following code is modified, for storing values in array.
public static void main(String[] args) {
// TODO code application logic here
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
String[] arr = new String[n]; // create string array of size n.
for(i= 1; i <= n ; i++){
String g = a + i;
System.out.println(g);
arr[i-1]=g; // assign your g veriable vale to array index
}
for(String s : arr){
System.out.println(s); // print your array
}
}

JAVA: Get 2 values for integer variables from the user in 1 line?

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]);

Categories

Resources