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 6 years ago.
Improve this question
Can't figure out the small error I've made. This example is from the Absolute java textbook.
public class Display1_7 {
public static void main(String[] args) {
String sentence = "I hate text processing!";
int position = sentence.indexOf("hate");//finding the position of hate in variable sentence
String ending = sentence.substring(position = "hate".length());/*cuts out the first half
of the sentence*/
System.out.println("0123456789");
System.out.println(sentence);
System.out.println("The word \"hate\" starts at index "
+ position);/*example of using quotes inside a string,
also demonstrates concatenation of a variable*/
sentence = sentence.substring(0, position) + "adore"+ ending;//I think I did this wrong?
System.out.println("The changed string is:");
System.out.println(sentence);
}//end of main
}
The expected output is
The output I get is
You use an = instead of a + when you try to determine ending.
String ending = sentence.substring(position + "hate".length());
...should do the trick
The problem was that your String ending = sentence.substring(position ="hate".length()); should be String ending = sentence.substring(position +"hate".length());
Indeed, the ending is the position of hate (returned by IndexOf()) to which you add the length of the word that you want to remove (in this case "hate").
The assignment you had in your code actually changed the value of position which switched from 2 to 4 (the length of hate). Thus, not only was the ending string wrong but your position was also wrong, making the final String exactly what you had.
So here is a corrected (and working) version of your code
public class Display1_7 {
public static void main(String[] args) {
String sentence = "I hate text processing!";
int position = sentence.indexOf("hate");//finding the position of hate in variable sentence
String ending = sentence.substring(position +"hate".length());/*cuts out the first half
of the sentence*/
System.out.println("0123456789");
System.out.println(sentence);
System.out.println("The word \"hate\" starts at index "
+ position);/*example of using quotes inside a string,
also demonstrates concatenation of a variable*/
sentence = sentence.substring(0, position) + "adore"+ ending;
System.out.println("The changed string is:");
System.out.println(sentence);
}
}
Small note, I would avoid comments like "end of main", I mean there's just no point to them at all, anyone can understand that it was the end of main :). From what I gathered you're a beginner but still, this sort of comments just make useful comments fade away.
Related
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 2 years ago.
Improve this question
I'm sorry if I'm not able to explain the question. When I take user input it prints only the first word of the string.
Help me understand what I'm missing, or why is it not working when I take user input.
When I pass the input, "This is Mango", it prints only
This.
Instead I want to print it as This
is
Mango
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the String: ");
String str= in.next();
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.println(words[i]+" ");
If I give a hard-coded string, it is able to save it in array.
String str = "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.println(words[i]+" ");
When I run the above code, it prints as
This
is
a
sample
sentence
Change this line:
String str = in.next();
to this:
String str = in.nextLine();
This way, your Scanner object will read the whole line of input.
If you only use next() it only reads the input until it encounters a space. Meanwhile, nextLine() reads the whole line (so until you escape to the next line when providing input). Also note that if you would like to read other data types you would need to use the corresponding function. For example, to read an integer you should use nextInt().
Hope this helps!
Im working on a Java program in class and im unsure why or how this is failing considering I get the correct print out when the program is ran.
Here is the code I have:
import java.util.Scanner;
public class TextAnalyzer {
// Create scanner
private static Scanner scnr = new Scanner(System.in);
// Create text string
private static String text;
public static void main(String[] args) {
System.out.println("Enter a sentence or phrase: ");
// Scan for text input
text = scnr.nextLine();
System.out.println("You entered: " + text);
// Call getNumOfCharacters
int count = getNumOfCharacters();
System.out.println();
System.out.println("Number of characters: " + count);
// Call outputWithoutWhitespace
String modifiedstring = outputWithoutWhitespace();
System.out.println("String with no whitespace: " + modifiedstring);
}
// Method outputs string without spaces
private static String outputWithoutWhitespace() {
text = text.trim().replaceAll(" ", "");
return text;
}
// Method to return number of characters
private static int getNumOfCharacters() {
return text.length();
}
}
The output passes on all levels, it's the Unit test for the number of characters in the input that is failing and I really just need some guidance as a new student to Java programming.
Here is a printout of the tests:
My assumption is that the getNumOfCharacters() is returning the number of characters AFTER the whitespaces have been removed, but I could be wrong.
Any help/guidance would be greatly appreciated.
Your assumption is correct and the problem is that you are replacing text with the stripped text:
private static String outputWithoutWhitespace() {
text = text.trim().replaceAll(" ", "");
return text;
}
... and now getNumOfCharacters() is returning the stripped length, which is no longer e.g. 46.
That is, when you hit this line in main:
String modifiedstring = outputWithoutWhitespace();
It has the side-effect of replacing text, since that's precisely what you told outputWithoutWhitespace() to do. So by the time main ends, text now contains the modified text, and subsequent calls to getNumOfCharacters() fail the unit tests.
Your printed output is misleading (still prints "46") because you compute and store the character count before you mess up text in outputWithoutWhitespace().
This is a good exercise in how to process and manage data, and a good learning experience for you. It's also a nice demonstration of the value of unit tests in quality control; you should remember this lesson.
Here's a hint: Based on your application requirements, does outputWithoutWhitespace() really need to store the trimmed text? Or does it just need to return it?
In the future, for debugging, consider:
Stepping through in a debugger where possible to examine what's happening along the way.
Adding diagnostic printouts, for example, print the value of text in getNumOfCharacters() to verify that it is what you think it is. Especially given your assumption that the problem was here and the failed unit test, this would be a good place to start investigating.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Like topic says I'm looking for the best way to:
I got .txt file. In this file there are for example:
Matthew Sawicki 25\n
Wladimir Putingo 28\n
Barracko Obamaso 27
Whats the best way to write a program that opens this file, checks out the biggest number and then prints out that?
I was thinking about: open file -> check each line with hasNextLine method saving the biggest number (addin i for measuring the lines - 1, 2, 3) and then close file and open again and then somehow prints out that line
Ok there goes edit then.
By the way I have to write name of file in console to open it. And I have to use Scanner.
My code:
Scanner scanner= new Scanner (System.in);
File file = new File (scanner.nextLine);
scanner = new Scanner (file);
int temp=O;
int i=0;
while (scanner.hasNextLine) {
String word1=scanner.next;
String word2=scanner.next;
String word3=scanner.next;
If(word3>temp)
temp3=word;
i++; // now i get the i id of the line with the biggest number
And now I'm thinking bout reopen file and loop again to print out that line with the biggest number(By for instance if(newWord3==temp))
is it a good idea? And how to reopen the file? can anyone continue the code?
Assuming that this file will always be in the same format here's a snippet that does what you want with no checking to make sure that anything is in the wrong place/format.
//Create a new scanner pointed at the file in question
Scanner scanner= new Scanner(new File ("C:\\Path\\To\\something.txt"));
//Create a placeholder for the currently known biggest integer
int biggest = 0;
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
//This line assumes that the third word separated by spaces is an
// integer and copies it to the `cndt` variable
int cndt = Integer.parseInt(s.split(" ")[2]);
//If cndt is bigger than the biggest recorded integer so far then
// copy that as the new biggest integer
biggest = cndt > biggest ? cndt : biggest;
}
//Voila
System.out.println("Biggest: " + biggest);
You'll want to verify that the number in question is there, and that you can handle the case that a line in your text file is malformed
There are several ways to do what you want. The way you described can work, but as you noted it requires to scan the file twice (in the worst case, which is when the row you have to print is the last one).
A better way which avoid to reopen the file again is to modify your algorithm to save not only the biggest number and the corresponding row number, but saving the whole line if the number is bigger than the one previously saved. Then, when you're done scanning the file you can just print the string you saved, which is the one containing the biggest number.
Note that your code will not work: the if is comparing a String with an int, and also there's no temp3 variable (that's probably just a typo).
To follow my suggestion you should have something like this:
int rowNumber = Integer.parseInt(word3);
if(rowNumber > temp) {
temp = rowNumber;
tempRow = word1 + " " + word2 + " " + word3;
}
then you can just print out tempRow (which you should define outside the while loop).
It's all fine now. I've made a simple mistake in my file (an empty enter at the end) so i coudnt figure out how to do it.
Thanks for ur effort and gl!.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Write a program that consists of three classes. The first class will be the actual program.
The second class will simply convert a string to lower case.
The third class will have three methods: I have been working on this assignment but i need some help. All my previous assignments have been only in one string. So i'm not sure how to get started with this. I will list what i have tried so far.
import java.io.*;
public class A3BE2300780
{
BufferedReader in = getReader ("input.txt");
private static class LowerCase {
public static String convertToLowerCase(String input) {
if (input==null) return "";
return input.toLowerCase();
}
}
public static class ThirdStringManip{
//This method will trim the white space from the
//beginning and end of the string
public static String trimmed(String s){
if (s == null){
return "";
}
return s.trim();
}
//This method will return a trimmed string of size len
public static String trimmed(String s, int len){
String retVal = ThirdStringManip.trimmed(s);
if (len > retVal.length()){
len = retVal.length();
}
return retVal.substring(0,len);
}
//This method will convert all double spaces to a single space
public static String squeeze(String s){
return s.replace(" ", " ");
}
}
//This method will read strings from the input file
//and perform manipulations on each string. The results of the
//manipulations are displayed in the text area
private void displayManipulatedStrings() throws Exception{
while(loop)
{
//Get the next line in the file
String curString = s.nextLine();
//Trim and Squeeze
System.out.print ( "Trim & Squeeze: " + ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)) + "\n");
//Trim, Squeeze, and Shorten to 10 characters
System.out.print ( "Trim, Squeeze, Shorten to 10: " + ThirdStringManip.trimmed(ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)),10) + "\n");
//Trim, Squeeze, lower-case and shorten to 20 characters
System.out.print ( "Trim, Squeeze, Shorten to 20, lower-case: " + toLower(ThirdStringManip.trimmed(ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)),20)) + "\n");
System.out.print ( "\n");
}
}
}
Ok so ... Some JAVA book & online tutorials will help a lot...
To start
Main class is where your main method is. So create a new empty class and add your main method to it.
public static void main (String[] args) {
//inside you can put some logic
}
Create another class and i.e StringConversion and insert a simple method iniside for example
class StringConversion {
private String lowerCaseString = "";
public String stringConversion(String somestring) {
lowerCaseString = somestring.toLowerCase();
return this.lowerCaseString;
}
}
Then create a third class with whatever methods you require
In your main method you can do
StringConversion lowerCaseString = new StringConversion();
String lowerCase = lowerCaseString.stringConversion("SOME STRING");
Then you can just print out the lowerCase string ;)
ALSO NOTE: MEGA ULTRA UBER IMPORTANT
When asking question on StackOverflow do not ASK US to do something for you, You have to show effort and show us what you tried by either explaining nicely or showing to us what have you done and why it didn't work. You can not just dump a homework question and pray that someone will do it for you. it just doesn;t work that way, and often you will find your questions to be locked and closed
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's assume a text file is a Math text book. How should I code to find out the largest number in that file? I'm aware of using StringTokens, parseLong, split, etc. But I can't figure out a proper way to combine them.
To be precise, let's say that text has something like:
Chapter 3.5
Million has 6 zeros. Ex. 6,000,000
Billion has 9 zeros. Ex. 9,000,000,000
Trillion has 12 zeros. Ex. 8,000,000,000,000
The largest number is 8000000000000. How do I extract that?
Thanks in advance.
Use the Scanner interface. This code assumes you pass in the file path as the first argument. The Scanner interface handles commas in numbers. I use BigInteger to handle any size number.
public static void main (String[] args) throws java.lang.Exception
{
BigInteger biggestNumber = null;
Scanner s = new Scanner(new FileReader(args[0]));
while( s.hasNext() ){
if( s.hasNextBigInteger() ){
BigInteger number = s.nextBigInteger();
if( biggestNumber == null || number.compareTo(biggestNumber) == 1 ){
biggestNumber = number;
}
}
else {
s.next();
}
}
System.out.println("Biggest Number: " + biggestNumber.toString());
}
You can play with an online example at: http://ideone.com/zKI5rM . It doesn't read from a file but uses a string in the code instead.
One place this would fail is if the book splits large numbers across lines. I'm not sure what your source material is, but that is something to keep in mind.
Store the largest number seen so far (initially, negative infinity), then go through the entire file extracting each number and if it's greater than the largest number you've stored, store it. At the end, the number stored is the largest number. Use double rather than long to account for very large numbers and noninteger numbers. The simple way to find all integers is to use a Scanner, feeding next() into parseDouble(...) and comparing anything that doesn't throw a NumberFormatException.
The easiest way would be to parse the text file line by line.
You can do this using regular expressions to see if you have any number formats located in the current line. If you do then you can check to see if it's larger than the previously found number.
Here is an excellent tutorial on regular expressions if you haven't came across them yet.
http://www.vogella.com/articles/JavaRegularExpressions/article.html
You can use BigInteger
public class Test {
public static void main(String[] arg) {
String line = "215,485,454,648,464";
String line1 = "5,454,546,545,645";
List<BigInteger> list = new ArrayList<BigInteger>();
list.add(new BigInteger(line.replaceAll(",", "")));
list.add(new BigInteger(line1.replaceAll(",", "")));
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}
}
Output: largest: 215485454648464
For your situation
public static void main(String[] args){
Scanner input = new Scanner(new File("yourFile.txt");
List<BigInteger> list = new ArrayList<BigInteger>();
while (input.hasNextLine()){
String line = input.nextLine();
String[] tokens = line.split("\\s+");
String number = token[5].trim(); // gets only the last part of String
list.add(new BigInteger(line.replaceAll(",", "")));
}
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}