I am very new to Java and writing this program to shuffle words and fix the suffle words. The following is my program. After I call mix(), I would like to be able to assign the output of word to team array within main.
For some reason, I can call mix() it works but I cannot access word which is in the shuffle function. Since I am in main and all these function within main, I thought I can access the variables. Any ideas what I am missing here?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
//System.out.println(input);
if(input==1) {
mix();
System.out.println(word);
char team[]=word.toCharArray();
for(int i=0;i<team.length;i++){
System.out.println("Data at ["+i+"]="+team[i]);
}
}
else{
System.out.println("this is exit");
}
}
static void mix()
{
String [] lines=new String[1000];//Enough lines.
int counter=0;
try{
File file = new File("input.txt");//The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag=true;
while(true){
try{
lines[counter]=buffer.readLine();//Store a line in the array.
if(lines[counter]==null){//If there isn't any more lines.
buffer.close();
fileReader1.close();
break;//Stop reading and close the readers.
}
//number of lines in the file
//lines is the array that holds the line info
counter++;
}catch(Exception ex){
break;
}
}
}catch(FileNotFoundException ex){
System.out.println("File not found.");
}catch(IOException ex){
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter ) + 0;
System.out.println(lines[pick]);
///scramble the word
shuffle(lines[pick]);
}
static void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
String word=output.toString();
}
}
Return string value from shuffle() method using return statement:
static String shuffle(String input) {
// . . .
return output.toString();
}
...and then use it in mix:
String word = shuffle(lines[pick]);
But it is better to read basic java tutorials before programming.
In Java, variables cannot be seen outside of the method they are initialized in. For example, if I declare int foo = 3; in main, and then I try to access foo from another method, it won't work. From the point of view of another method, foo does not even exist!
The way to pass variable between methods is with the return <variable> statement. Once the program reaches a return statement, the method will quit, and the value after the return (perhaps foo) will be returned to the caller method. However, you must say that the method returns a variable (and say what type is is) when you declare that method (just like you need to say void when the method does not return anything!).
public static void main(String[] args){
int foo = 2;
double(foo); //This will double foo, but the new doubled value will not be accessible
int twoFoo = double(foo); //Now the doubled value of foo is returned and assigned to the variable twoFoo
}
private static int double(int foo){//Notice the 'int' after 'static'. This tells the program that method double returns an int.
//Also, even though this variable is named foo, it is not the same foo
return foo*2;
}
Alternatively, you could use instance variable to have variables that are accessible by all the methods in your class, but if you're new to Java, you should probably avoid these until you start learning the basics of object-oriented programming.
Hope this helps!
-BritKnight
Related
import java.util.*;
import java.io.*;
public class comparing{
static ArrayList <compare> events = new ArrayList<compare>();
public static void main(String[]args){
try{
Scanner in = new Scanner(new File("events.txt"));
File output = new File("chines.txt");
Scanner sc = new Scanner(output);
PrintWriter printer = new PrintWriter(output);
while(in.hasNext()){
int temp = in.nextInt();
String temptwo = in.nextLine();
//String s = ;
events.add(new compare(temp,temptwo));
//System.out.println("Next word is: " + temp);
Collections.sort(events);
for(int i = 0;i<events.size();i++){
printer.write(events.get(i));
System.out.println(events.get(i));
}
}
}
catch(Exception e){
System.out.println("Invalid file name");
}
}
My code above reads from a file it sorts the data then prints it out. What I would like to do is write this sorted data to another file but I keep getting the following error:
comparing.java:27: error: no suitable method found for write(compare)
printer.write(events.get(i));
You're declaring events to be an ArrayList, meaning that it contains java.lang.Object elements, thus printer.write(java.lang.Object) is what's being searched for by the compiler.
You're adding an object of your undisclosed class compare, so even declaring ArrayList<compare> wouldn't help. Hopefully your compare class has a meaningful toString, so that you can use ArrayList<compare> events, combined with printer.write(event.toString());
See the docs.
There is no write(Object) method. You can change it to write(events.get(i).toString()) to convert it to a String first.
Alternatively, use print instead of write for more input options. See write() vs print().
It can take a object as argument and calls the String.valueOf(obj) method for you:
printer.print(events.get(i));
Add this code instead of your loop
for (int i = 0; i < events.size(); i++)
{
printer.write(String.valueOf(events.get(i)));
out.write(" ");
}
This essentially is a small code I'm writting for practice that requires me to use StringTokenizer. I've done the same kind of programs before , but now when I store the strings in an array and try to print them it show's a null pointer exception. Any help?
import java.util.*;
public class board1
{
String key;
String m[];
//function to accept the sentence
void getsent()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a sentence terminated by'.' or '?'");
String take=in.nextLine();
StringTokenizer taken=new StringTokenizer(take);
int numtokens=taken.countTokens();
String m[]=new String[numtokens];
for(int i=0;i<m.length;i++)
{
m[i]=taken.nextToken();
}
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]);
}
}
// function to display
void display()
{
System.out.println("The words seperately right now are:");
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]+"\t");
System.out.println();
}
}
// main to get functions
public static void main(String args[])
{
board1 ob= new board1();
ob.getsent();
ob.display();
}
}
You're shadowing the variable m. Replace
String m[] = new String[numtokens];
with
m = new String[numTokens];
I think because you are shading properties. You have an array called m into which you are putting tokens in getSent, but display is using the m array defined in the class to which you haven't added anything.
Print out the size of m in display, this will show you that you are not adding anything to the property called m.
I'm running out of patience and needs this problem fixed. This program is intended to retrieve data from two text files as two string arrays, then use a mergesort algorithm to sort the results. My issue is during the conversion to an integer array. I return the array I created, and see that there is data stored. However, when running an loop and checking if any index is null, I find that the program believes them all to be null.
import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class MergeInventories
{
public static File inv1 = new File("H:\\Senior Year\\CompSci\\Projects\\storeOneInv.txt");
public static File inv2 = new File("H:\\Senior Year\\CompSci\\Projects\\storeTwoInv.txt");
//the two text files I'm retrieving data from
public static String[] store1; //string array in question
public static String[] store2;
public static void header()
{
System.out.println("Keenan Schmidt");
System.out.println("AP Computer Science");
System.out.println("Merge Inventories");
System.out.println("...finally...");
}
public static void main() throws FileNotFoundException
{
header();
readFiles(inv1,store1); //converts file to string array
sort(); //converts string[] to int[]
//System.out.print(readFiles(inv1,store1));
//System.out.print(readFiles(inv2,store2);
}
public static String[] readFiles(File file, String[] store)
{
try {
Scanner scanner = new Scanner(file);
int i = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
i++;
}
store = new String[i];
i = 0;
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
store[i] = line;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return store;
}
public static int[] sort()
{
int[] items = new int[store1.length];
for(int i = 0; i < store1.length; i++)
{
if(store1[i] != null) //this is the line where the error occurs
{
try{
items[i] = Integer.parseInt(store1[i].replaceAll("[^0-9]"," "));
} catch (NumberFormatException nfe) {};
}
}
return items;
}
private void mergeSort(String[] arr1, String[] arr2)
{
}
private void merge(int low, int med, int hi)
{
}
}
As azurefrog mentions in a comment, Java arrays are pass by value (the reference to the array) so that when you reassign the store variable in the method, the original array you passed in doesn't get the new reference assignment.
Since you want to re-use this method multiple times to make different arrays, I would suggest making a new array everytime inside the method. No need to pass it in.
static String[] readFiles(File file){
String[] store =null;
//rest of method this same
}
Then in your calling code:
store1 = readFiles(inv1);
store2 = readFiles(inv2);
You are getting a NullPointerException when trying to access store1 because you never give store1 a value other than null, because Java is pass-by-value.
You create a new array, but you only assign it to store, which is a local variable in readFiles(), and that assignment has no effect on the store1 variable.
You do return that value from your method, but you neglected to assign it in the invoking code.
Replace
readFiles(inv1,store1); //converts file to string array
with
store1 = readFiles(inv1,store1); //converts file to string array and saves it in store1
so that the created array is assigned to store1.
As dkatzel points out, this means that there is no longer any point in passing store1 into the method in the first place. It would be a good idea to follow his advice on cleaning up the method.
You can use a List at first because the file could be of unknown size, then convert the List to an Array (using toArray), and then you will know the length to which you should initialize the int array and your code can proceed as expected.
either change to this: store1 = readFiles(inv1,store1);
or in readFiles() use this.store1 instead
public class mainTest {
public static void main(String[] args) throws Exception {
Scanner KB = new Scanner(System.in);
String VehiclesFile = "Vehicles.txt";
File file1 = new File(VehiclesFile);
Scanner infile1 = new Scanner(VehiclesFile);
Vehicle[] Vehicles = new Vehicle[0];
try {
Scanner scanner = new Scanner(file1);
int lineCount = 0;
while (scanner.hasNextLine()) {
lineCount++;
scanner.nextLine();
}
Vehicles = new Vehicle[lineCount];
scanner = new Scanner(file1);
int VehicleCount = 0;
while (scanner.hasNextLine()) {
String[] temp1 = scanner.nextLine().split(",");
// file has been read into temp1[] now to use Vehicles
// class type
Vehicles[VehicleCount] = new Vehicle();
Vehicles[VehicleCount].setregistration(temp1[0]);
Vehicles[VehicleCount].setmake(temp1[1]);
Vehicles[VehicleCount].setModel(temp1[2]);
Vehicles[VehicleCount].setyear(temp1[3]);
Vehicles[VehicleCount].setodometer(temp1[4]);
Vehicles[VehicleCount].setowner(temp1[5]);
VehicleCount++;
}
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to find ");
}
//*******This is where I need to access the class to print****************
System.out.println (Vehicle.class.getClasses());
}
}
I cannot seem to understand how to reference a specific part of the class/array of class objects
The class for Vehicle is in defined with get/set so I didn't include the code.
System.out.println(Arrays.toString(Vehicles));
Make sure that the vehicle class has toString() method overriden. Otherwise it will just print out the references.
See:
How to override toString() properly in Java?
If you want to print off data from the Vehicle objects you'll have to loop through that array and call the getter methods you mentioned before.
It should be something like
for(Vehicle v : Vehicles)
{
System.out.print(v.getYear() + " " + v.getMake() + " " + v.getModel());
}
Seems to me like you're mixing up the concept of classes and objects. Class is short for classification, so a class is a type of something. An object is a single instance of a class. So it's a single item of a certain type.
What you have is an array of objects, not classes, and you want to print the information of each object. So say you have five vehicles in your array, you will have to call the function System.out.println(/*data to print*/) five times. One for each element in the array.
To omit repetition, you can use a loop:
for (int index = 0; index < Vehicles.length; ++i) {
System.out.println(Vehicle[index].getMake());
// do the same to print other attributes of the Vehicle class
}
My program is suppose to take a text file, read the first four names, create a random number between 1-4, and then assign the names to 4 different teams based on what the random number was. For instance, if the number was 3, then the first name would go to team 3, second name to team 4, etc. etc.(repeat process until there are no more names) I believe I have all of the code for that correct, the problem is I can't figure out how to return all the names I have put into the arrays that were brought into the method. Here is my code:
public static void main(String args[]) throws IOException
{
BufferedReader girlFile = new BufferedReader(new FileReader("girls40.txt"));
PrintWriter teamFile = new PrintWriter(new FileWriter("xxxxxxx-teamlist.txt"));
String team1[] = new String[20];
String team2[] = new String[20];
String team3[] = new String[20];
String team4[] = new String[20];
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
}
public static String[] loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile)
{
int n;
int random;
String name1;
String name2;
String name3;
String name4;
while((name1=girlFile.readLine())!=null)
{
name2=girlFile.readLine();
name3=girlFile.readLine();
name4=girlFile.readLine();
random = 1 + (int)(Math.random() * 4);
if(random==1)
{
team1[n]=name1;
team2[n]=name2;
team3[n]=name3;
team4[n]=name4;
}
if(random==2)
{
team1[n]=name4;
team2[n]=name1;
team3[n]=name2;
team4[n]=name3;
}
if(random==3)
{
team1[n]=name3;
team2[n]=name4;
team3[n]=name1;
team4[n]=name2;
}
if(random==4)
{
team1[n]=name2;
team2[n]=name3;
team3[n]=name4;
team4[n]=name1;
}
n++;
}
return team1[],team2[],team3[],team4[];
}`
The main method was given to me, so it cannot be changed.
If there is more code in main method than you've posted here. You'll have to mention what is the variable n and how is it being used else follow the answer.
main Method can't be changed
In your main method,
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
} // End of Main Method
You have not used returned value n for nothing. So it really doesn't matter what you return from method loadTeams() as long as it is an int.
Also, here loadTeams() returns an String[] which can't be assigned be int n, you'll have to change return type of loadTeams() to int as
public static int loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile) {
/*
...
*/
return 0; // whatever, it isn't being used
}
This the solution if you can't change the main method.
The call to loadTeams() expects a return value of type int. Not an array or multiple arrays. If you can't change the main method then loadTeams should return an integer.
// ...
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
// ...
you don't have to return anything, arrays created in main() will be passed to your method by reference, you can fill them there, and after execution of your method, values will be kept in these arrays
The loadTeams should return an int and not String[].
There is no need to return arrays. Changes made in the arrays in the loadTeams methods will be reflected back to the array in main method.