While loop runs once? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
The split function does not work. for the last print statement, it gives me an arrayoutofbound error. Any help?
while (inFile.hasNext())
{
String clean = inFile.nextLine();
String[] nm = clean.split(",");
for (int i = 0; i < nm.length; i++)
{
System.out.println("at index "+ i +" string is "+nm[i]);
}
System.out.print("at index"+2+"Strin"+nm[3]);
}
text file :
input1,2,3,4,5
input2,2,3,4,5
input3,3,4,5,6
input4,3,4,5,6
input5,3,4,5,6
output:
at index 0 string is input1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at filereader.FileReader.main(FileReader.java:33)
Java Result: 1

The code seems to be proper to me and it should not fail like this. Only reason i can see is if there is a blank line in your input file, in which case System.out.print("at index"+2+"Strin"+nm[3]); will return a ArrayOutOfBoundException at nm[3]
Alternatively you can write your code like this:
while (inFile.hasNext())
{
String clean = inFile.nextLine();
if(clean != null && clean != ""){
String[] nm = clean.split(",");
for (int i = 0; i < nm.length; i++)
{
System.out.println("at index "+ i +" string is "+nm[i]);
}
System.out.print("at index"+2+"Strin"+nm[3]);
}
}
Hope this works.

This gives you error:
System.out.print("at index"+2+"Strin"+nm[3]);
And that is because you either have one blank line or a line where there are less than 4 comma separated items. Try this:
System.out.print("at index"+2+"Strin"+nm[nm.length-1]);

Maybe the array nm does not have 4 elements at line
System.out.print("at index"+2+"Strin"+nm[3]);
Check that the arrays contains at least 4 element before printing the 4th element.
// create a new scanner with the specified String Object
Scanner inFile = new Scanner(s);
while (inFile.hasNext())
{
String clean = inFile.nextLine();
String[] nm = clean.split(",");
for (int i = 0; i < nm.length; i++)
{
System.out.println("at index "+ i +" string is "+nm[i]);
}
if (nm.length > 3) {
System.out.print("at index"+2+"Strin"+nm[3]);
}
}

Related

While loop is broken, even though parameters are correct [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am extremely confused about why my code is not running. I end up being in a loop that lasts forever that I assume is the while loop that happens after the print statement. The print statement that is listed prints true, so the while loop should go through at least one iteration... right?
This does not happen, my code ends up running forever, and does not end up printing anything else.
(Also just ignore the if statement with the %, I am testing on a small scale before going big.)
Scanner scan = new Scanner(file);
FileWriter fw = new FileWriter(modifiedCSV);
int counter = 0;
System.out.println(scan.hasNextLine() && counter < 10);
while(scan.hasNextLine() && counter < 10);
{
System.out.println("test");
if(counter%1000000==0)
{
System.out.println("Normalizing Line: " + counter);
}
String line = scan.nextLine();
String[] lineData = line.split(",");
System.out.println("!!!!!!");
double normalizedDistance = (Double.parseDouble(lineData[3])-minDistance)/(maxDistance-minDistance);
double normalizedAngle = (Double.parseDouble(lineData[7])-minAngle)/(maxAngle-minAngle);
double normalizedFlux = (Double.parseDouble(lineData[8])-minFlux)/(maxFlux-minFlux);
fw.write(line + "," + normalizedDistance + "," + normalizedAngle + "," + normalizedFlux + "\n");
counter++;
}
Your while loop is empty since there is a semicolon at the end of the line with the while statement.
while(scan.hasNextLine() && counter < 10);

reverse element of the array in java? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to print the array in reverse order but I don't know why it's not working. I want to reverse them using the way I have mentioned below, in a single line, but my logic is not working.
void dynamicinputArraytwo() throws IOException {
int buffer;
int i,jo,io;
System.out.println("Enter size");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
buffer = Integer.parseInt(br.readLine());
float arrtwo[]=new float[buffer];
for( i=0;i< arrtwo.length;i++){
System.out.println ("Enter elements of array=");
arrtwo[i] = Float.parseFloat(br.readLine());
}
for (int jx=0; jx < arrtwo.length; jx++){
System.out.println("array before reverse "+arrtwo[jx] + " ");
}
float arrthree[];
arrthree = new float[arrtwo.length];
for(io=0,jo=arrtwo.length; jo>=0;io++,jo--){
arrthree[io] = arrtwo[jo] ;
}
for(io=0; io < arrtwo.length; io++){
arrtwo[io] = arrthree[io] ;
}
for (int jx=0; jx < arrtwo.length; jx++){
System.out.println("array after reverse "+arrtwo[jx] + " ");
}
}
Your first problem is here:
for(io=0,jo=arrtwo.length; jo>=0;io++,jo--){
arrthree[io] = arrtwo[jo] ;
}
The last index of an array is length - 1 because arrays are indexed starting at 0, so you'll have an exception (i.e. arrtwo[arrtwo.length] is not a valid index in the array). You should set jo to arrtwo.length - 1 initially instead.

Java specific character counter [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So I am trying to prompt the user to enter any words into a string. Then I want to prompt them to count the number of occurrences for whatever letter they want to count. So if they enter words in a string like "this is a test" and they search "t" for example, the return would be 3 t's in the string "this is a test". I am a little confused as to where to go from here...
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
String s = "";
System.out.print("Enter a string of words or type done to exit: ");
inputValue = input.readLine();
System.out.print("Which letter would you like to count: ");
s = input.readLine();
int counter = 0;
I am thinking about maybe doing a for loop and do something like counter++.
Answer provided by Jean above is correct but I would like use a different method to calculate number of occurrence of a character in a String.
String string = "this is a testing string";
int count = string.length() - string.replaceAll("t", "").length();
Or
int counter = string.split("t").length - 1;
You would need to escape meta characters if you are to check character like $.
Using Apache commons-lang you could simply do
int counter = StringUtils.countMatches(s, intputValue);
But if you really want to code it, then you could use
public int count(String fullString, char valueToCount)
{
int count = 0;
for (int i=0; i < fullString.length(); i++)
{
if (fullString.charAt(i) == valueToCount)
count++;
}
return count;
}
Another solution would consist of replacing everything in your string except the input char and return the length of the trimmed string.
return s.replaceAll("[^" + inputValue + "]", "").length();

separate too long words in string in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a String with some text, f.e.
"Thisisalongwordtest and I want tocutthelongword in pieces"
Now I want to cut the to longs word in 2 pieces with a blank. The word should be cut if it's longer than 10 characters.
The result should be:
"Thisisalon gwordtest and I want tocutthelo ngword in pieces"
How can I achieve this efficiently?
are you looking for this? or I misunderstood the question?
String newString = oldStr.replaceAll("\\w{10}","$0 "))
with your example, the newString is:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Edit for Pshemo's good comment
to avoid to add space after words with exact 10 chars:
str.replaceAll("\\w{10}(?=\\w)","$0 "));
.replaceAll("(\\w{10})(?=\\w)", "$1 ")
Tested with:
test("abcde fghij klmno pqrst");
test("abcdefghijklmnopqrst");
test("abcdefghijklmnopqrstuv");
test("abcdefghij klmnopqrstuv");
test("abcdefghij klmnopqrst uv");
separate text into words. (by space)
cut long words and replace source word with new words
assemble text again
Note, that this approach will kill multiple-spaces.
(?=\w{10,}\s)(\w{10})
Should be replaced by
"\1 "
you can use replace function.
If it has number or special characters
(?=\S{10,}\s)(\S{10})
can be used.
This is the code i wrote check it once.....
public class TakingInput {
public static void main(String[] args) {
String s="Thisisalongwordtest and I want tocutthelongword in pieces";
StringBuffer sb;
String arr[]=s.split(" ");
for(int i=0;i<arr.length;i++){
if(arr[i].length()>10){
sb=new StringBuffer(arr[i]);
sb.insert(10," ");
arr[i]=new String(sb);
}
}
for(String ss: arr){
System.out.println(ss);//o/p: "Thisisalon gwordtest and I want tocutthelo ngword in pieces"
}
}
}
This code will do exactly what you want.
First create a method that splits a String if its longer than 10 chars:
String splitIfLong(String s){
if(s.length() < 11) return s + " ";
else{
String result = "";
String temp = "";
for(int i = 0; i < s.length(); i++){
temp += s.charAt(i);
if(i == 9)
temp += " ";
result += temp;
temp = "";
}
return result + " ";
}
}
Then use Scanner to read every word in the sentence seperated by a white space" ":
String s = "Thisisalongwordtest and I want tocutthelongword in pieces";
String afterSplit = "";
Scanner in = new Scanner(s);
Then call the splitIfLong() method for every word in the sentence. And add what the method returns to a new String:
while(in.hasNext())
afterSplit += splitIfLong(in.next());
Now you can use the new String as you wish. If you call:
System.out.println(afterSplit);
it will print:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Hope this helps

If statement isn't taking my string values and evaluating them as a boolean (java beginner problems) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
//Program always prints the line written in the if statement.
//Also, eclipse returns an error every time I try to add an else statement
import java.util.Scanner;
import java.util.Arrays;
public class Practice {
public static void main(String[] args)
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of artists you would like to search: ");
int number = input.nextInt();
String junk = input.nextLine();
String []artist = new String[number];
for(int i=0; i < number ; i++)
{
artist[i]= input.nextLine();
}
System.out.println("Here is the list of artists you searched for: " + Arrays.toString(artist) + ". Is this correct?");
String check = input.nextLine();
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false); //this continually returns both print statements in and out of the if statement even if I input something other than yes or y and I have no idea why
{
System.out.println("Cool! Enjoy your search!"); //this always prints no matter what
}
System.out.println("Please try again! Sorry for the inconvenience!"); //won't let me add an else statement
You have a dangling ; at the end of your condition
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false) // ; was here
{
}
Remove it. This is known as an empty statement. You could rewrite it as
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false)
;
{
System.out.println("Cool! Enjoy your search!"); //this always prints no matter what
}
Since a block { /* ... */ } is valid code, it will get executed no matter what.
Your "if-then" statement is being treated as a regular end statement since there is a semicolon ";" added before the scope of your "if-then" block "{ }" begins.
Oracle shows that before you start writing the body of the statement, use brackets
int choice = input.nextInt(); //How does the steak taste?
if(choice == 1) {
String Steak = "Amazing"
System.out.println(choice);
}
The variable "choice" ends with a semicolon and is now declared with a value that the user will input. Since the if-then statement is not finished after the header, brackets containing the body with further statements (each ending with a semicolon) can be executed.

Categories