• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!

Help with Java

Status
Not open for further replies.
Level 4
Joined
Nov 24, 2012
Messages
68
Hey everyone. This may sound awkward but, I need help with my Java homework. I have a good idea on what it should look like but, I can't seem to figure out what to type and how to type it to get it to work.

I am currently right here on assignment 1. (there is a picture of my source code)

*Modify the program so that it asks the user to input a String after the list has been input and tells the user if that String exists in the list.

*Modify the program so that if the String in previous step has been found, it asks the user to input another String and it replaces the original String with the new String. Print out the list after the String has been replaced.

I do know how to tell the program to tell the user to input a String but, how to do it after the list??? and to replace it???
 

Attachments

  • assignment 1.JPG
    assignment 1.JPG
    71.3 KB · Views: 354
Last edited:
Level 4
Joined
Nov 24, 2012
Messages
68
Post the code in code tags or JASS tags if preferred.

Like this?

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> toDoList = new ArrayList<String>();
System.out.println("Enter items for the list, when prompted.");
boolean done = false;
Scanner keyboard = new Scanner(System.in);

while (!done)
{
System.out.println("Type an entry:");
String entry = keyboard.nextLine( );
toDoList.add(entry);
System.out.print("More items for the list? ");

String ans = keyboard.nextLine( );
if (!ans.equalsIgnoreCase("yes"))
done = true;
}

System.out.println("The list contains:");
int listSize = toDoList.size( );
for (int position = 0; position < listSize; position++)
System.out.println(toDoList.get(position));

}
}

Any help is appreciated :)
 

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
Code:
import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListDemo
{
   public static void main(String[] args)
   {
      ArrayList<String> toDoList = new ArrayList<String>();
      System.out.println("Enter items for the list, when prompted.");
      boolean done = false;
      Scanner keyboard = new Scanner(System.in);

      while (!done)
      {
          System.out.println("Type an entry:");
          String entry = keyboard.nextLine( );
          toDoList.add(entry);
          System.out.print("More items for the list? ");

          String ans = keyboard.nextLine( );
          done = !ans.equalsIgnoreCase("yes");
      }

      System.out.println("The list contains:");
      int listSize = toDoList.size( );
      for (int position = 0; position < listSize; position++)
          System.out.println(toDoList.get(position));

      System.out.println("Enter string to search for.");
      String find = keyboard.nextLine( );
      boolean found = false;
      for( String s : toDoList ){
        if(s.equals(find)){
          found = true;
          break;
        }
      }

      if(!found){
        System.out.println("No such element in list.");
        return;
      }

      System.out.println("Enter string to replace with.");
      String replace = keyboard.nextLine( );

      for( int i = 0 ; i < toDoList.size( ) ; i+= 1 ){
        if(toDoList.get(i).equals(find)){
          toDoList.remove(i);
          toDoList.add(i, replace);
        }
      }
   }
}

I am not used to the replaceAll method of Java 8. I am guessing they would want you to use that. How I expect it works is you make a light class of type UnaryOperator<String> and implement the appropriate methods such that all occurrences of that string return the new string otherwise the string is returned unchanged.
 
Level 4
Joined
Nov 24, 2012
Messages
68
Code:
import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListDemo
{
   public static void main(String[] args)
   {
      ArrayList<String> toDoList = new ArrayList<String>();
      System.out.println("Enter items for the list, when prompted.");
      boolean done = false;
      Scanner keyboard = new Scanner(System.in);

      while (!done)
      {
          System.out.println("Type an entry:");
          String entry = keyboard.nextLine( );
          toDoList.add(entry);
          System.out.print("More items for the list? ");

          String ans = keyboard.nextLine( );
          done = !ans.equalsIgnoreCase("yes");
      }

      System.out.println("The list contains:");
      int listSize = toDoList.size( );
      for (int position = 0; position < listSize; position++)
          System.out.println(toDoList.get(position));

      System.out.println("Enter string to search for.");
      String find = keyboard.nextLine( );
      boolean found = false;
      for( String s : toDoList ){
        if(s.equals(find)){
          found = true;
          break;
        }
      }

      if(!found){
        System.out.println("No such element in list.");
        return;
      }

      System.out.println("Enter string to replace with.");
      String replace = keyboard.nextLine( );

      for( int i = 0 ; i < toDoList.size( ) ; i+= 1 ){
        if(toDoList.get(i).equals(find)){
          toDoList.remove(i);
          toDoList.add(i, replace);
        }
      }
   }
}

I am not used to the replaceAll method of Java 8. I am guessing they would want you to use that. How I expect it works is you make a light class of type UnaryOperator<String> and implement the appropriate methods such that all occurrences of that string return the new string otherwise the string is returned unchanged.

No my Professor doesn't require me to use the replaceAll method. Actually I never seen the replaceAll method if I remember correctly. I use Netbeans IDE 7.4

:ogre_icwydt: for the replacing of the Strings inputted. Now I get it. I will do the final small step.
Thank you Dr Super Good :)
+rep

Is it possible if I may ask for your assistance one last time please if you have time? Thank you again Dr Super Good.
 
Last edited:

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
No my Professor doesn't require me to use the replaceAll method. Actually I never seen the replaceAll method if I remember correctly.
It is new to Java 8. Which was released a few months ago.

I use Netbeans IDE 7.4
That has nothing to do with it. The method availability is based on your SDK / standard version and nothing to do with the IDE (although that may require patching to recognize it).

Be default everyone should be using Java 8 soon when all the security certificates expire on Java 7.

for the replacing of the Strings inputted. Now I get it. I will do the final small step.
It is already there though...

Is it possible if I may ask for your assistance one last time please if you have time? Thank you again Dr Super Good.
Sure what is the problem?
 
Level 4
Joined
Nov 24, 2012
Messages
68
Quote:
No my Professor doesn't require me to use the replaceAll method. Actually I never seen the replaceAll method if I remember correctly.
It is new to Java 8. Which was released a few months ago.

Oh I didn't know that.

Quote:
I use Netbeans IDE 7.4
That has nothing to do with it. The method availability is based on your SDK / standard version and nothing to do with the IDE (although that may require patching to recognize it).

Be default everyone should be using Java 8 soon when all the security certificates expire on Java 7.

My textbook never had anything about this. I should google to find out more.

Quote:
for the replacing of the Strings inputted. Now I get it. I will do the final small step.
It is already there though...

Sorry. I forgot to mention that he would like the list to be shown again after the replacement. It's simple so I can do that thanks :)

Quote:
Is it possible if I may ask for your assistance one last time please if you have time? Thank you again Dr Super Good.
Sure what is the problem?

My last assignment. My professor this time didn't give me clues on where to start. And because of that I'm lost. I don't know where and how to start unlike previous assignments he had a clue on what to look for. This one no pointers X(

- Write a program that will make a copy of a text file, line by line.

- Read the name of the existing file and the name of the new file – the copy from the keyboard. (I get how to do this.)

- Use the methods of the class File to test whether the original file exists and can be read. (???)

- If not, display an error message and abort the program. (I have a good idea of what to do here)

- If the original file exists and there isn’t a file with the same name as the new file, copy the file. (???)

- If a file with the name of the new file exists, display a warning message and allow the user to either abort the program, overwrite the existing file, or enter a new name for the file. (how to make three options? with if else?)

- Create the existing file with a text editor (e.g. you may use Word but save the file as a text (.txt) file). (I'm guessing I'm suppose to create a random .txt document)

Thanks Dr Super Good
 

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
My textbook never had anything about this. I should google to find out more.
Due to possible security exploits in certain Java releases, Oracle maintains a release timeline. Each release of Java is designed to automatically stop working when it exceeds a certain age forcing the user to update to a new version. This minimizes the maximum life time of exploits as after a release containing the exploit is a certain age it will no longer be usable.

- Use the methods of the class File to test whether the original file exists and can be read. (???)
Create a new File object. According to the API this is done simply like this...

Code:
String path = ... // put your string here, from the command line.
File source = new File(path);

You can then use the methods described in the API to check the validity of the file since the File object itself is just a reference to a file structure and does not need to link to an existing object. I cannot tell you what these methods are as it appears the Java API website is down (or not available from this internet connection).

- If the original file exists and there isn’t a file with the same name as the new file, copy the file. (???)
Create a File object like above and resolve it. If it exists you do whatever. If it does not exist you copy it by getting a Scanner from the source file (I believe you can pass the File object directly to an overload of the Scanner constructor) and an OutputStream of the destination file and in a loop reading in new lines from the Scanner object and using Println on the OutputStream to write the lines until EoF (End of File) is reached.

- If a file with the name of the new file exists, display a warning message and allow the user to either abort the program, overwrite the existing file, or enter a new name for the file. (how to make three options? with if else?)
Or a case statement or any way you want.
 
Level 4
Joined
Nov 24, 2012
Messages
68
Due to possible security exploits in certain Java releases, Oracle maintains a release timeline. Each release of Java is designed to automatically stop working when it exceeds a certain age forcing the user to update to a new version. This minimizes the maximum life time of exploits as after a release containing the exploit is a certain age it will no longer be usable.


Create a new File object. According to the API this is done simply like this...

Code:
String path = ... // put your string here, from the command line.
File source = new File(path);

You can then use the methods described in the API to check the validity of the file since the File object itself is just a reference to a file structure and does not need to link to an existing object. I cannot tell you what these methods are as it appears the Java API website is down (or not available from this internet connection).


Create a File object like above and resolve it. If it exists you do whatever. If it does not exist you copy it by getting a Scanner from the source file (I believe you can pass the File object directly to an overload of the Scanner constructor) and an OutputStream of the destination file and in a loop reading in new lines from the Scanner object and using Println on the OutputStream to write the lines until EoF (End of File) is reached.


Or a case statement or any way you want.


Thank you Dr Super Good. I'm sorry for a slow response going study on my other finals.

+rep


package project4;

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Project4
{

public static void main(String[] args)
{
System.out.print("Enter file name: ");
Scanner keybaord = new Scanner(System.in);
String fileName = keyboard.next();
Scanner inputStream = null;
System.out.println("fileName");
File fileObject = new File("old.txt");
String path =
File source = new File(path);

try
{
inputStream = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine();
System.out.println(line);
}
inputStream.close();
}

}
 
Last edited:

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
String variables are strings already. If you use a string of the variable name you just get the variable name.

System.out.println("fileName");
Will print...
fileName
Not the value held by the variable fileName.

File fileObject = new File("old.txt");
Will make a reference to a file in the process directory called old.txt.

String path =
Will throw a syntax error (is not a valid Java expression).

File source = new File(path);
Will throw an error as path is not defined due to the above problem.

You can test if a file exists before opening it.

Yes what you do above will work to some extent for part of the problem. You just need to replace standard out with an output stream to a file.
 
Level 4
Joined
Nov 24, 2012
Messages
68
String variables are strings already. If you use a string of the variable name you just get the variable name.


Will print...
fileName
Not the value held by the variable fileName.


Will make a reference to a file in the process directory called old.txt.


Will throw a syntax error (is not a valid Java expression).


Will throw an error as path is not defined due to the above problem.

You can test if a file exists before opening it.

Yes what you do above will work to some extent for part of the problem. You just need to replace standard out with an output stream to a file.

oh yeah did not see that thank you.(facepalm)

well I made a directory but, doesn't seem like its working?

String path = C:\\Library\\Documents\\NetBeansProjects\\Project4;

its from hard drive C in the libraries folder > documents > NetBeansProjects > Project4. this is where the old.txt is at.

"You just need to replace standard out with an output stream to a file."
this sounds simple but, I'm not positive how to program that? is it like this?

public static PrintWriter openOutputTextFile
(String fileName) throws FileNotFoundException
{
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
PrintWriter outputStream = null;
try
{
outputStream = openOutputTextFile("old.txt");
}

Thanks +rep
 

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
String path = C:\\Library\\Documents\\NetBeansProjects\\Project4;
Is not a valid string. String constants have to be in inverted commas ("").

Try...
String path = "C:\\Library\\Documents\\NetBeansProjects\\Project4";

this sounds simple but, I'm not positive how to program that? is it like this?
Yes basically like that.
 
Level 4
Joined
Nov 24, 2012
Messages
68
Is not a valid string. String constants have to be in inverted commas ("").

Try...
String path = "C:\\Library\\Documents\\NetBeansProjects\\Project4";


Yes basically like that.

Ok. Thank you that worked.
The #1 line I get an error message of "illegal start of expression." what am I missing? Also for #8 what do I catch that with? the FileNotFoundException?

01. public static PrintWriter openOutputTextFile
02. (String fileName) throws FileNotFoundException
03. {
04. PrintWriter toFile = new PrintWriter(fileName);
05. return toFile;
06. }
07. PrintWriter outputStream = null;
08. try
09. {
10. outputStream = openOutputTextFile("old.txt");
11. }

Thanks for your time :)
+rep
 
Level 4
Joined
Nov 24, 2012
Messages
68
Termination of scope above I think. Basically you are declaring a method inside another method or outside a class.


Yes, if you were using eclipse IDE it even tells you what you need to catch.

OK I think since the declaring method inside one is really the problem. how do I solve this I try seperating them but, I think the

public static void PrintWriter openOutputTextFile

has many issues. thats why everything else is not working.
Thanks Dr Super Good :) +rep
 
Level 4
Joined
Nov 24, 2012
Messages
68
You need to post the entire class file if I am to find the cause.

Try using eclipse IDE, it has a lot of helpful features such as real-time syntax checking and will occasionally suggest what may be the cause or a possible solution.

Sorry I forgot about posting the whole thing. I'll see if I can get that eclipse IDE. I don't think it would matter that much of which programs I'm aloud to use. This is what I have so far. Sorry its a mess.

package project4;

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Project4
{

public static void main(String[] args)
{
System.out.print("Enter file name: ");
Scanner keybaord = new Scanner(System.in);
String fileName = keyboard.next();
Scanner inputStream = null;
System.out.println(fileName);
File fileObject = new File("old.txt");
String path = "C:\\Library\\Documents\\NetBeansProjects\\Project4";
File source = new File(path);

try
{
inputStream = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine();
System.out.println(line);
}
inputStream.close();

boolean fileOK = false;
while (!fileOK)
{
if (!fileObject.exists())
System.out.println("No such file");
else if (!fileObject.canRead())
System.out.println("That file is not readable.");
else
fileOK = true;
if (!fileOK)
{
System.out.println("Enter the file name again:");
fileName = keyboard.next();
fileObject = new File(fileName);
}

}

}
public static void PrintWriter openOutputTextFile
{
(String fileName) throws FileNotFoundException
{
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
PrintWriter outputStream = null;
try
{
outputStream = openOutputTextFile("old.txt");
}
catch (FileNotFoundException e)
}

}

Thank you
 

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
I am sorry but your code makes little sense. It seems to be a mess of half-written code with typos and incorrect syntax.

Please learn the basic syntax of JAVA and use an IDE like Eclipse to help generate correct (as far as the java compiler is concerned) Java code. There are tutorials available from Oracle that help explain the syntax of the language. Eclipse IDE will flag up any syntax errors for you to fix as you type.

I cannot really help you learn the basics of Java programming. People far more experienced than I have written guides and examples to help you with that. It also follows a very strict and well defined set of syntax rules just like all programming languages so should not be difficult to learn/understand.

I can help you logically solve problems using Java. Being able to write Java code does not mean you understand how to do everything you want. Logical errors in the code will compile but cause the program to not work as intended. This is the hard part of Java programming and where seeking help is most useful as an extra pair of eyes or someone experienced can often spot these hard to find logical faults that can appear invisible to you.
 
Level 4
Joined
Nov 24, 2012
Messages
68
I am sorry but your code makes little sense. It seems to be a mess of half-written code with typos and incorrect syntax.

Please learn the basic syntax of JAVA and use an IDE like Eclipse to help generate correct (as far as the java compiler is concerned) Java code. There are tutorials available from Oracle that help explain the syntax of the language. Eclipse IDE will flag up any syntax errors for you to fix as you type.

I cannot really help you learn the basics of Java programming. People far more experienced than I have written guides and examples to help you with that. It also follows a very strict and well defined set of syntax rules just like all programming languages so should not be difficult to learn/understand.

I can help you logically solve problems using Java. Being able to write Java code does not mean you understand how to do everything you want. Logical errors in the code will compile but cause the program to not work as intended. This is the hard part of Java programming and where seeking help is most useful as an extra pair of eyes or someone experienced can often spot these hard to find logical faults that can appear invisible to you.

It's alright Thank you Dr Super Good for all your help. I will make sure I get that Eclipse sounds more useful at generating syntax errors than netbeans.
 
Status
Not open for further replies.
Top