My program is not ending - java

My program does not end. I am a beginner and am having trouble understanding why. It was working fine before I changed the name, so I copied it to another file, but it still does not end.
import java.util.Scanner;
public class Fan
{
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
//first input
System.out.println("Enter your first input: ");
String first = s.nextLine();
String[] firstsplit = first.split(", ");
//second input
System.out.println("Enter your second input: ");
String second = s.nextLine();
String[] secondsplit = second.split(", ");
//third input
System.out.println("Enter your third input: ");
String third = s.nextLine();
String[] thirdsplit = third.split(", ");
//fourth input
System.out.println("Enter your fourth input: ");
String fourth = s.nextLine();
String[] fourthsplit = fourth.split(", ");
//fifth input
System.out.println("Enter your fifth input: ");
String fifth = s.nextLine();
String[] fifthsplit = fifth.split(", ");
for (int a = 0; a<=firstsplit.length-1; a++)
{
//skipping over values that say how many pieces are on board
for (int i = 3; i <= 12; i++)
{
//compatible with piece numbers up to 12(max)
if (Integer.parseInt(firstsplit[0])==i) {
while (i >= 1 && i <= Integer.parseInt(firstsplit[i])) {
continue;
}
System.out.println(firstsplit[i]);
}
}
}
}
}
I would be grateful for any advice.

The problem is here:
while (i >= 1 && i <= Integer.parseInt(firstsplit[i])) {
continue;
}
This is an infinite loop since you never change the value of i inside it. Just comment it to make your application finish. Then, spend some time thinking about how to fix it or what are you trying to accomplish with this loop.

Related

Java array linear search always returns "Book is not found"?

When I insert the arguments the search always returns "not found" - even though the searched value was input into the array?
import java.util.Scanner;
public class assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] BookID = new String [3];
String [] Booktitle = new String [3];
//input the BookID
System.out.println("Enter the 12 BookID");
for (int a = 0 ; a < BookID.length; a++)
{
System.out.print("BookID :");
BookID[a] = sc.next();
}
//Input the book title
for (int b = 0 ; b < Booktitle.length ; b++)
{
System.out.print("Booktitle :");
Booktitle[b] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter BookID to find :");
for(int c = 0; c < BookID.length; c++)
{
searchValue = sc.next();
if(searchValue.equals(BookID))
System.out.print("BookID is found : ");
else
System.out.print("BookID is not found : ");
}
}
}
I'm expecting the result to return like so: if input BookID 112. The Linear search would return "The BookID is found :" instead of the else statement.
Try printing out the value of the bookId you wanna find to see if there anything with the string that could cause it to not be equals. Also, you could convert the string to an integer with:
Integer.parseInt("BookId");
The equals would have less chance of failing, you could also change de the array for an array of int instead of String.
This code has some basic things right, but it could be a bit better. Some of the changes I made are for keeping Java conventions (so the code is easier to read and understand) and some are functional. I added them as comments.
import java.util.Scanner;
public class Assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] bookIDs = new String [3]; //lowercase for the attribute name (convention)
String [] bookTitles = new String [3]; //plural for the array (convention)
//input the BookID
System.out.println("Enter the Book ID");
for (int i = 0 ; i < bookIDs.length; i++) { //you can re-use the i in all loops
System.out.print("Enter " + i + " Book ID: ");
bookIDs[i] = sc.next();
}
//Input the book title
for (int i = 0 ; i < bookTitles.length ; i++) {
System.out.print("Enter " + i + " Book title: ");
bookTitles[i] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter Book ID to find: ");
searchValue = sc.next(); //NOTE: this is your first mistake. read out of the loop
for(int i = 0; i < bookIDs.length; i++) {
if(searchValue.equals(bookIDs[i])) { //NOTE: this is your second mistake - you wanted the array value, not the array
System.out.println("BookID is found in position "+i);
break; //suggestion - stop the loop when found.
}
else {
System.out.println("BookID is not found in position "+i);
}
}
sc.close(); //NOTE: important to close scanners at the end.
}
}
Good luck with your studies.

Comparing Strings ( the user types as many as he wants) and then telling which one is first (based on which first letter comes first) using for loop

First I have to ask the user to type a number. That number will decide how many sentences he has to type (should be >2 ) and then I have to compare those sentences. I have to tell which one comes first ( based on alphabet letters order). This is all I have done so far. I don't know how to compare Strings since I don't know how many the user will type and don't have names for them.
import java.util.*;
public class Sentences {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.println("Type a number > 2");
number = scan.nextInt();
}
scan.nextLine();
String sentence;
int y = 0;
for (int i = 0; i < number; i++) {
System.out.println("Type a sentence");
sentence = scan.nextLine();
}
}
}
You were close. Instead of a single variable(sentence), you need an array(sentences[]) as shown below:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.print("Type a number > 2: ");
number = Integer.parseInt(scan.nextLine());
}
String[] sentences = new String[number];
int y = 0;
for (int i = 0; i < number; i++) {
System.out.print("Type a sentence: ");
sentences[i] = scan.nextLine();
}
Arrays.sort(sentences);
for (String sentence : sentences) {
System.out.println(sentence);
}
}
}
To sort String sentences[], you need to use Arrays.sort(sentences) as shown above.
A sample run:
Type a number > 2: 0
Type a number > 2: 3
Type a sentence: Hello world
Type a sentence: You are awesome
Type a sentence: My name is Jane
Hello world
My name is Jane
You are awesome
[Update]
As per your clarification, you wanted to print only one sentence which is the lowest in alphabetical order. It is like tracking the minimum number from a list of numbers.
The algorithm is as follows:
Store the first input to a variable, say lowestAlphabetical.
In a loop, compare the value of lowestAlphabetical with the next input and if the next input is lower in alphabetical order put the next input into lowestAlphabetical.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.print("Type a number > 2: ");
number = Integer.parseInt(scan.nextLine());
}
// Scan the first sentence
System.out.print("Type a sentence: ");
String sentence = scan.nextLine();
// Since we have only one sentence till now, it is also the lowest in
// alphabetical order
String lowestAlphabetical = sentence;
// Loop for next inputs
for (int i = 1; i < number; i++) {
System.out.print("Type the next sentence: ");
sentence = scan.nextLine();
if (sentence.compareTo(lowestAlphabetical) < 0) {
lowestAlphabetical = sentence;
}
}
System.out.println(lowestAlphabetical);
}
}
A sample run:
Type a number > 2: 3
Type a sentence: Hello world
Type the next sentence: Good morning
Type the next sentence: My name is Jane
Good morning

Asking user to enter specific number of strings then adding each string to array?

New to java. I need to ask the user the number of strings (consisting only of upper and lowercase letters, spaces, and numbers) they want to input. These strings need to be stored in an array. Then I created a boolean method to be able to tell if those strings are palindromic (ignoring spaces and cases). If it is palindromic then I add to the result list to print later on. I am confused on how to ask the user to input that exact amount of strings and how to check each individual string. I must use StringBuilder. This is what I have so far (it's kind of a mess, sorry). I feel like I'm using the StringBuilder/array wrong, how can I fix this?
public class Palindromes {
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder(numOfStrings);
for(int n=0; n < paliString; n++){
paliString[n] = scan.nextLine();
scan.nextLine();
String[] stringPali = new String[numOfStrings];
StringBuilder str = paliString;
if(isPali(userString)){
paliString = append.userString;
}
System.out.println("The palindromes are: " + userString ";");
}
static boolean isPali(String userString) {
int l = 0;
int h = userString.length() - 1;
// Lowercase string
userString = userString.toLowerCase();
// Compares character until they are equal
while (l <= h) {
char getAtl = userString.charAt(l);
char getAth = userString.charAt(h);
// If there is another symbol in left
// of sentence
if (!(getAtl >= 'a' && getAtl <= 'z'))
l++;
// If there is another symbol in right
// of sentence
else if (!(getAth >= 'a' && getAth <= 'z'))
h--;
// If characters are equal
else if (getAtl == getAth) {
l++;
h--;
}
// If characters are not equal then
// sentence is not palindrome
else
return false;
}
// Returns true if sentence is palindrome
return true;
}
}
SAMPLE RESULT:
Enter the number of strings: 8
Enter the strings:
Race Car
Mountain Dew
BATMAN
Taco Cat
Stressed Desserts
Is Mayonnaise an instrument
swap paws
A Toyotas a Toyota
The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota
As I think the best way to answer this is to help you learn in small steps, I tried to stick with your initial idea on how to solve this and edited your main method with minimal changes.
This one does the trick.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
if (paliString.length() > 0) {
paliString.append("; ");
}
paliString.append(userString);
}
}
System.out.println("The palindromes are: " + paliString);
}
Key changes:
I added scan.nextLine(); right after reading the number of strings. This handles the newline you get when the user hits enter.
You don't need to initialize the StringBuilder with numOfStrings. This just preallocates the size of the StringBuilder in characters. Not the number of strings. Either way, it's not necessary. StringBuilder grows as needed.
I suggest you inspect what I did inside the for-loop. This was the biggest mess and changed significantly.
Last but not least: Writing the result needs to be outside of the for-loop, after all palindromes have been added to the StringBuilder.
Edit
Based on your comment, in this next iteration, I changed the usage of StringBuilder to the usage of an ArrayList. (Which is something completely different)
I am using it here because Lists in Java grow on demand. And since the number of palindromes is probably not equal to the number of input strings, this is the way to go. To really assign it to an array, one could always call String[] paliStringsArray = paliStrings.toArray(new String[]{}); but as ArrayLists already use an underlying array and are not necessary to to generate the output you want, I didn't put it into the new version.
Please compare the differences of this step to the previous version. I also added this String.join("; ", paliStrings) part, which creates the output you want.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
And now to the last step. Arvind Kumar Avinash actually solved a part that I also missed in the initial question. (I'll read more carefully in the future). He was validating the user input. So for the last iteration, I added his validation code in a modified way. I put it into a method as I think that makes things clearer and gets rid of the necessity of a the boolean valid variable.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = readNextLine(scan);
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
static String readNextLine(Scanner scanner) {
while (true) {
String userString = scanner.nextLine();
if (userString.matches("[A-Za-z0-9 ]+")) {
return userString;
} else {
System.out.println("Error: invalid input.");
}
}
}
I need to ask the user the number of strings (consisting only of upper
and lowercase letters, spaces, and numbers) they want to input. These
strings need to be stored in an array.
I have done the above part of your question. I hope, this will give you direction to move forward.
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
System.out.print("Enter a string consisting of only letters and digits: ");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: a
Error: invalid input.
Enter the number of strings: 3
Enter a string consisting of only letters and digits: Arvind
Enter a string consisting of only letters and digits: Kumar Avinash
Enter a string consisting of only letters and digits: !#£$%^&*()_+
Error: invalid input.
Enter a string consisting of only letters and digits: Hello #
Error: invalid input.
Enter a string consisting of only letters and digits: Hello 123
Feel free to comment in case of any doubt/issue.
Wish you all the best!
[Update]
Based on your request, I have posted the following update which asks for the strings only once and then allows the user to enter all the strings one-by-one:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
System.out.println("Enter " + numOfStrings + " strings consisting of only letters and digits: ");
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: 3
Enter 3 strings consisting of only letters and digits:
Arvind
Kumar
He$ll0
Error: invalid input.
Avinash
Feel free to comment in case of any doubt.

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 to read the user inputs(including spaces) line by line with Scanner?

I need to read user inputs line by line (may be included spaces). I had already read Scanner doesn't see after space question. So I used with scanner.nextLine() but this method does not help my program. Below is my sample program ....
public class TestingScanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many friends do you have ?");
int size = sc.nextInt();
String[] names = new String[size];
for (int i = 0; i < size; i++) {
System.out.println("Enter your name of friend" + (i + 1));
names[i] = sc.nextLine();
}
System.out.println("*****************************");
System.out.println("Your friends are : ");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
System.out.println("*****************************");
}
}
While runnig my program , after inserted no: of friend , my program produces two lines as below. How can I solve it ? Thanks.
After int size = sc.nextInt(); use sc.nextLine() to consume the newline characters, otherwise, they will be consumed by nextLine() in your loop and that is not what you want.
Solution
int size = sc.nextInt();
sc.nextLine();

Categories

Resources