Right now I cant even compile this program. Im trying to write a program that takes a inputted string and then encrypts the letters by swapping them out with another letter predetermined in a array and then shows you again the original text. any help would be appreciated.
import java.util.Scanner;
public class Array {
private char [] alphabet = new char [25];
private char [] crypt = new char [25];
String oldMessage;
public Array()
{ char[] alphabet = "abcdefghijklmnoptqrstuvwxyz".toCharArray();
char[] crypt = "qwertyuiopasdfghjklzxcvbnm|".toCharArray();
}
public static void run(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a message that you would like to encrypt\n");
oldMessage = scan.nextLine();
String newMessage = "";
for (int i=0; i<oldMessage.length(); ++i) {
int index = alphabet.indexOf(old.charAt(i));
if (index == -1)
newMessage +="?";
else
newMessage += crypt.charAt(index);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {Array myApplication = new Array(); myApplication.run();}
First off, when encountering errors, it's always best to include the error in your question--often it will point you right to the source of the error. What does your compiler say when the build fails?
Next, I'm on my phone right now and can't verify that I've found all the problems, but remember that strings in Java are immutable, meaning that they can't be changed after creation. This means that you can't append to them in the way you're doing. Try using the StringBuilder class to accomplish what you're looking for here, or filling a new array as you go and converting to String at the end.
Also, it looks like you're missing two end braces (the for loop and the run method).
From static method run() you are referring to non-static variables like alphabet, crypt, oldMessage.
This is first that comes into mind
Related
I have a class defined to store configuration data for my application. I want to save the instances of this out to xml and use XStream for this. But I keep getting outofmemory errors when I try to write an instance.
Here is my class definition:
public class Eol_Target_Variable {
String name;
String alias;
long value;
long default_val;
int size;
int scaling;
int div;
Boolean read_access;
Boolean write_access;
public Eol_Target_Variable(String arg_name, String arg_alias, int arg_value, int arg_size, int arg_scaling,int arg_div)
{
name = arg_name;
alias = arg_alias;
value = arg_value;
default_val = 0;
scaling = arg_scaling;
div = arg_div;
size = arg_size;
read_access = true;
write_access = true;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
...etc for all standard getters and setters
Here is my handler for exporting a single object to xml
public void importConfiguration() {
XStream xstream = new XStream(new DomDriver());
Eol_Target_Variable myvar = new Eol_Target_Variable("jamie", "xtracold", 1977, 16, 1, 1);
String myxml = xstream.toXML(myvar);
System.out.print(myxml);
}
Every time I get "Exception in thread "JavaFX Application Thread" java.lang.OutOfMemoryError: Java heap space" thrown. I cannot see why such a simple class would throw the out of memory error. I have managed to output simple String objects using XStream so the library is working, it is just this custom class that seems to cause problems.
I have also tried to increase the heap allocated at startup with the VM arguments -Xms512m -Xmx1024m but that makes no difference.
Thanks
Jamie
Here is the new class declaration
#XStreamAlias("targetVar")
public class Eol_Target_Variable {
String name;
String alias;
long value;
#XStreamAlias("default")
long default_val;
int size;
int scaling;
int div;
#XStreamOmitField
Node node;
#XStreamOmitField
Boolean read_access;
#XStreamOmitField
Boolean write_access;
public Eol_Target_Variable(String arg_name, String arg_alias, int arg_value, int arg_size, int arg_scaling,int arg_div, Node arg_node)
{
name = arg_name;
alias = arg_alias;
value = arg_value;
default_val = 0;
scaling = arg_scaling;
div = arg_div;
size = arg_size;
node = arg_node;
read_access = true;
write_access = true;
}
I also used a different parser as the basic DOMParser never handled the massive amount of data. When I changed to StaxDriver was at least able to see the streams of text in the debug output as XStream traversed the whole scene graph.
XStream xstream = new XStream(new StaxDriver());
xstream.processAnnotations(Eol_Target_Variable.class);
I don't pretend to fully understand why declaring the class inlined causes problems, but I can reason as to why asking XStream to parse a complete Node might cause issues.
If anyone has any experience with XStream and complex data structures, that are declared inside a JavaFX app I would welcome their input.
I'm making a 3 dimensional tic tac toe game. The game is complete and works fine, however, the assignment demands that (for testing game situations) the program take in a file of integers that places pieces on the game board. It takes in the file from the Unix command line.
However, the game is supposed to run from start if no file is entered in command line. I'm getting an out of bounds exception and don't know why for the life of me. Any help would be greatly appreciated.
Portion of code for getting file and storing the integers:
public class Test {
static int board[][][] = new int[4][4][4];
static boolean ComputerMoved = false;
static int[] sums = new int[76];
static int n = 0;
public static void main(String[] args) throws FileNotFoundException {
//Method purpose is to look and see if there is a startup file given to
//initally setup the board. If not, plays an empty board and prompts the
//user for the first move.
Scanner scan = new Scanner(new FileInputStream(args[0]));
if (args.length > 0) {
int size = scan.nextInt();
for (int i = 0; i < size; i++) {
int level = scan.nextInt();
int row = scan.nextInt();
int column = scan.nextInt();
int value = scan.nextInt();
level = level % 4;
row = row % 4;
column = column % 4;
board[level][row][column] = value;
}
}
Hint: It appears that the out of bounds exception is coming not from your array, but rather your scanner. Could it be possible you don't have "enough" numbers to scan?
So my code so far reads in lines from a file, stores them in two separate ArrayLists. Now I'm going to have to make each node in a doubly Linked List contain the line's string and the corresponding integer, but since I cant put two ArrayLists in the declaration for a Linked List, I tried making a Tree map where the key is the string and the value is the corresponding integer. Here's the relevant code
public class FileReaderProgram
{
public static void main(String[] args) throws IOException
{
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
String stringComponent = " ";
int integerComponent = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the absolute path of the file");
String fileName = in.next(); //Gets the file from the user
File inFile = new File(fileName);
**Map<String,Integer> lineCombo = new TreeMap<String,Integer>();**
try
{
Scanner fileReader = new Scanner(inFile); //Constructs Scanner for reading the file
fileReader.useDelimiter("\\n");
while (fileReader.hasNextLine())
{
String line = fileReader.nextLine(); //Gets line from the file
Scanner lineScanner = new Scanner(line); //Constructs new scanner to analyize the line
lineScanner.useDelimiter(",");
stringComponent = lineScanner.next(); //Read first word
while (!lineScanner.hasNextInt())
{
stringComponent = stringComponent + " " + lineScanner.next(); //Checks if more than one word part of string
}
integerComponent = lineScanner.nextInt(); //Read in integer
words.add(stringComponent); //Array of Strings, element number corresponding to the line it came from
numbers.add(integerComponent); //Array of Ints, same thing as above
**lineCombo.put(stringComponent, integerComponent);**
}
}
So when I run the file:
example string,1
another example,42
data,200
final,150
it prints out {another example=42, data=200, example string=1, final=150}
Why is it putting the strings in the wrong order?
What is the most efficient way of getting the symbol for a single member of a class?
import 'dart:mirrors';
class TestClass{
void iWantThisSymbol(){}
void butNotThisOne(){}
}
/**
* I can get all the symbols and filter down but this isn't nice
*/
void main(){
var allSymbols = reflectClass(TestClass).instanceMembers.keys;
var justTheSymbolIWant = allSymbols.where((symbol) => symbol.toString().contains('iWantThisSymbol')); // this doesnt seem very efficient or maintainable
}
var justTheSymbolIWant = reflectClass(TestClass).instanceMembers[#iWantThisSymbol]
Although, to be a bit pedantic, you're not get getting a Symbol, you're using a Symbol (#iWantThisSymbol) to get a member, which in this case is a method. So I would rewrite this as:
import 'dart:mirrors';
class TestClass{
void iWantThisMethod(){}
void butNotThisOne(){}
}
void main(){
var justTheMethodIWant = reflectClass(TestClass).instanceMembers[#iWantThisMethod];
}
Also, a few things about that use of where():
If you do want to filter a list of Symbols, you don't need to them convert to a String, you can just compare symbol instances directly.
.where() returns an iterable, even if there's only one item that matches. You probably want firstWhere() which always returns a single item.
var justTheSymbolIWant = allSymbols.firstWhere((symbol) => symbol == #iWantThisSymbol);
I came up with the following code to calculate the factorial of a given number:
import java.lang.*;
import java.math.*;
import java.io.*;
import java.util.*;
#SuppressWarnings("unused")
class factorial_1{
public static void main(String args[]) throws IOException
{
System.out.println("enter a number: ");
String strPhone = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strPhone = br.readLine();
BigInteger number = new BigInteger (strPhone);
BigInteger fact = new BigInteger("1");
BigInteger i = new BigInteger("1");
BigInteger step = new BigInteger("1");
final long start = System.currentTimeMillis();
final long durationInMilliseconds = System.currentTimeMillis()-start;
for ( ; i.compareTo(number) <= 0; i=i.add(step)){
fact = fact.multiply(i);
}
System.out.println("execute Long-Running Task took " + durationInMilliseconds + "ms.");
System.out.println("the factorial of "+ number +" is "+ fact);
}
}
if you execute the code, it reads a number from the keyboard and then
prints out its factorial
I exported the code as a .jar file and tried to give the number (10) as input, from the terminal
I did as this post says How to execute jar with command line arguments but nothing happened until I typed again the number
-----------Terminal-----------
roditis#NiSLab-pc2:~/Desktop$ java -jar import_number.jar 10
enter a number:
10
execute Long-Running Task took 0ms.
the factorial of 10 is 3628800
-----------Terminal-----------
Im new to linux / programming and I really look forward for your help
Thanks in advance
Roditis
You should try putting the value in quotes like roditis#NiSLab-pc2:~/Desktop$ java -jar import_number.jar "10"
Remember that your main function takes an array of String objects like so public static void main(String[] args).
EDIT
Sorry, I see that you are not reading the args[] parameter at all. If you provide "10" as an argument to your program, then args[0] will contain that value. Please check if(args.length >= 1) in your case before accessing args.