So, I am SUPER new to Java, but I am trying to make a class-specific program so that I can work on a game within Java. Here is my code:
import java.util.Scanner;
public class boxtype {
public static void main(String args[]) {
String[] melee = {"Crowbar", "Bowie Knife", "Butterfly Knife", "Knuckleduster"};
String[] pistol = {"Colt .22", "Magnum .45", "P250", "9mm Pistol"};
String[] assault = {"AK47", "M4A1", "M16", "SMG", "Mac10", "Minigun (HGE)"};
String[] shotgunsniper = {"Shotgun", "Benelli S90", "Sniper Rifle"};
String[] attachments = {"Laser Sight", "Silencer", "Scope", "Auto-target"};
Scanner scan = new Scanner(System.in);
String xy = scan.nextLine();
if (xy.equals("spyclass")) {
spyClass();
}
}
private static void spyClass(String[] assault, String[] attachments, String[] pistol) {
// TODO Auto-generated method stub
System.out.println("Spy class: ");
System.out.println("Primary weapon: " + assault[2] + " + " + attachments[2]);
System.out.println("Secondary weapon: " + pistol[1] + " + " + attachments[2]);
System.out.println("");
}
}
Basically what happens, is Eclipse returns an error saying that "spyClass is not applicable". I'm still researching how to fix, but yeah.
in the call to spyClass you're not passing the parameeters
It should be:
if (xy.equals("spyclass")) {
spyClass(assault, attachments, pistol);
}
Your spyClass method expects a bunch of arguments, but you aren't giving it any. The line that says
spyClass();
should perhaps be something like
spyClass(assault, attachments, piston);
spyClass probably shouldn't be static and you need to pass the arguments to it when you call it in your main method. spyClass(assault, attachments, pistol);
Related
I'm trying to allow jargo to ignore any amount of "junk-be-here" strings. How can I do that? This is the code I've come up with:
#Test
public void testUsage() throws Exception
{
Argument<Integer> nrOfPotatoes = Arguments.integerArgument("-n").build();
ParsedArguments parsedArguments = CommandLineParser.withArguments(nrOfPotatoes).parse("-n", "123", "junk-be-here");
int potatoesToPlant = parsedArguments.get(nrOfPotatoes);
System.out.println("Hold on, planting " + potatoesToPlant + " potatoes");
}
But I get:
se.softhouse.jargo.ArgumentExceptions$UnexpectedArgumentException: Unexpected argument: junk-be-here, previous argument: 123
at se.softhouse.jargo.ArgumentExceptions.forUnexpectedArgument(ArgumentExceptions.java:299)
at se.softhouse.jargo.CommandLineParserInstance.getDefinitionForCurrentArgument(CommandLineParserInstance.java:329)
at se.softhouse.jargo.CommandLineParserInstance.parseArguments(CommandLineParserInstance.java:262)
at se.softhouse.jargo.CommandLineParserInstance.parse(CommandLineParserInstance.java:234)
at se.softhouse.jargo.CommandLineParserInstance.parse(CommandLineParserInstance.java:228)
at se.softhouse.jargo.CommandLineParser.parse(CommandLineParser.java:224)
at
.....
You can use an indexed argument (by specifying no names to the argument), and set variableArity (any amount of arguments is allowed).
#Test
public void testUsage() throws Exception
{
Argument<List<String>> junk = Arguments.stringArgument().variableArity().build();
Argument<Integer> nrOfPotatoes = Arguments.integerArgument("-n").build();
ParsedArguments parsedArguments = CommandLineParser.withArguments(junk, nrOfPotatoes).parse("-n", "123", "junk-be-here");
int potatoesToPlant = parsedArguments.get(nrOfPotatoes);
System.out.println("Hold on, planting " + potatoesToPlant + " potatoes");
System.out.println("Junk:" + parsedArguments.get(junk));
}
This prints:
Hold on, planting 123 potatoes
Junk:[junk-be-here]
I've been teaching myself java and I've stuck on a problem that no matter what I do can't seem to solve. I've done some research but all the options provided don't seem to work. Hopefully you guys might be able to teach me something.
I have a .txt file that contains:
AccountName1:Password1
AccountName2:Password2
AccountName3:Password3
AccountName4:Password4
AccountName5:Password5
The elements of the file are then read and inserted into a List:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public abstract class AccountFileReader {
private static Scanner sc;
public static void main(String[] args) {
try {
// Enables ability to find file in any OS.
String file = File.separator + "some folder name"
+ File.seperator + "AccNamePw.txt";
File f = new File(file);
sc = new Scanner(f);
List<AccountInfo> accounts = new ArrayList<AccountInfo>();
String name = "";
String password = "";
while (sc.hasNext()){
// Reads and checks if there is a new line
String line = sc.nextLine();
// Creates delimiter to make the different elements on file f
String[] details = line.split(":");
// Initializes 1st element
name = details[0];
// Initializes 2nd element
password = details[1];
// Creates new object "a" that has the 2 elements from each line
AccountInfo a = new AccountInfo(name, password);
// Adds the "a" object to the "accounts" List
accounts.add(a);
}
// Iterates list and prints out the list
for(AccountInfo a: accounts){
// The hiccup is in here somewhere. This for loop isn't working in
// a way I think it's supposed to.
// Create new object of the getter, setter class to use in this loop
AccountInfo namPw = new AccountInfo(name, password);
name = namPw.getName();
password = namPw.getPassword();
System.out.println(a.toString() + " " + name
+ " " + password);
}
} catch (FileNotFoundException e) {e.printStackTrace();}
}
}
The getter/setter class is as follows:
public class AccountInfo{
private String name;
private String password;
public AccountInfo(String name, String password) {
this.setName(name);
this.setPassword(password);
}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setPassword(String password) { this.password = password; }
public String getPassword() { return password; }
public String toString(){ return name + " "+ password; }
}
My output is:
AccountName1:Password1 AccountName5:Password5
AccountName2:Password2 AccountName5:Password5
AccountName3:Password3 AccountName5:Password5
AccountName4:Password4 AccountName5:Password5
AccountName5:Password5 AccountName5:Password5
But I want it to return:
AccountName1:Password1 AccountName1:Password1
AccountName2:Password2 AccountName2:Password2
AccountName3:Password3 AccountName3:Password3
AccountName4:Password4 AccountName4:Password4
AccountName5:Password5 AccountName5:Password5
I know that the a.toString() is returning correctly but my namPw.getName() and namPw.getPassword() are only giving me the last element of the List.
What am I not understanding and or missing? How do I get namPw.getName() and namPw.getPassword() to return the List correctly?
The problem is the declaration of nameand password right before the while loop. These variables store the last encountered username and password. When the while loop ends, these variables store the values AccountName5 and Password5 respectively.
When you enter the second for-loop, you first create a new UserAccount with using nameand password which store AccountName5 and Password5.
If you just want to print this list, you do not need to create a copy of the contents of the list. Just do:
for(AccountInfo a : accounts) {
System.out.println(a.toString() + " " + a.getName() + " " + a.getPassword());
}
It's because of this:
for(AccountInfo a: accounts){
**AccountInfo namPw = new AccountInfo(name, password);**
name = namPw.getName();
password = namPw.getPassword();
System.out.println(a.toString() + " " + name
+ " " + password);
You are looping through the AccountInfo objects you already created and then creating a new AccountInfo object and passing in name and password (which get set each time you read in a new line, so the value for them would be the last thing they would be set to when reading the file)
Not sure why you are creating a new AccountInfo object. But in order to get what you want, you'd need to do this:
AccountInfo namPw = new AccountInfo(a.getName(), a.getPassword());
No need to create new object in loop. You are already getting object in a.
Remove object creation line. It is creating object with name and and password which is never going to change as it is outside the loop.
Checkout the following solution:
for(AccountInfo a: accounts){
name = a.getName();
password = a.getPassword();
System.out.println(a.toString() + " " + name + " " + password);
}
I'm trying to write a program to decode Adobe key code into text, however the string array that I'm using doesn't seem to change values when passing through if statements within my for loop. Here is the code (I haven't implemented the print out section as I could not get my test of the the array switching values to work):
import java.util.Scanner;
public class Decode {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("Enter collected data:");
String data = input.nextLine();
input.close();
String[] splitdata = data.split("\\s+");
int datalength=splitdata.length;
for (int i=0; i<datalength; i++){
if (splitdata[i]=="1")
splitdata[i]="\n";
if (splitdata[i]=="8")
splitdata[i]="**backspace**";
if (splitdata[i]=="9")
splitdata[i]="**tab**";
if (splitdata[i]=="13")
splitdata[i]="**enter**";
if (splitdata[i]=="16")
splitdata[i]="**shift**";
if (splitdata[i]=="17")
splitdata[i]="**control**";
if (splitdata[i]=="19")
splitdata[i]="**pause/break**";
if (splitdata[i]=="20")
splitdata[i]="**capslock**";
if (splitdata[i]=="27")
splitdata[i]="**esc**";
if (splitdata[i]=="32")
splitdata[i]="\\s+";
if (splitdata[i]=="33")
splitdata[i]="*page up**";
if (splitdata[i]=="34")
splitdata[i]="**page down**";
if (splitdata[i]=="35")
splitdata[i]="**end**";
if (splitdata[i]=="36")
splitdata[i]="**home**";
if (splitdata[i]=="37")
splitdata[i]="**left**";
if (splitdata[i]=="38")
splitdata[i]="**up**";
if (splitdata[i]=="39")
splitdata[i]="**right**";
if (splitdata[i]=="40")
splitdata[i]="**down**";
if (splitdata[i]=="45")
splitdata[i]="**insert**";
if (splitdata[i]=="46")
splitdata[i]="**delete**";
if (splitdata[i]=="48")
splitdata[i]="0";
if (splitdata[i]=="49")
splitdata[i]="1";
if (splitdata[i]=="50")
splitdata[i]="2";
if (splitdata[i]=="51")
splitdata[i]="3";
if (splitdata[i]=="52")
splitdata[i]="4";
if (splitdata[i]=="53")
splitdata[i]="5";
if (splitdata[i]=="54")
splitdata[i]="6";
if (splitdata[i]=="55")
splitdata[i]="7";
if (splitdata[i]=="56")
splitdata[i]="8";
if (splitdata[i]=="57")
splitdata[i]="9";
if (splitdata[i]=="S-65")
splitdata[i]="a";
if (splitdata[i]=="S-66")
splitdata[i]="b";
if (splitdata[i]=="S-67")
splitdata[i]="c";
if (splitdata[i]=="S-68")
splitdata[i]="d";
if (splitdata[i]=="S-69")
splitdata[i]="e";
if (splitdata[i]=="S-70")
splitdata[i]="f";
if (splitdata[i]=="S-71")
splitdata[i]="g";
if (splitdata[i]=="S-72")
splitdata[i]="h";
if (splitdata[i]=="S-73")
splitdata[i]="i";
if (splitdata[i]=="S-74")
splitdata[i]="j";
if (splitdata[i]=="S-75")
splitdata[i]="k";
if (splitdata[i]=="S-76")
splitdata[i]="l";
if (splitdata[i]=="S-77")
splitdata[i]="m";
if (splitdata[i]=="S-78")
splitdata[i]="n";
if (splitdata[i]=="S-79")
splitdata[i]="o";
if (splitdata[i]=="S-80")
splitdata[i]="p";
if (splitdata[i]=="S-81")
splitdata[i]="q";
if (splitdata[i]=="S-82")
splitdata[i]="r";
if (splitdata[i]=="S-83")
splitdata[i]="s";
if (splitdata[i]=="S-84")
splitdata[i]="t";
if (splitdata[i]=="S-85")
splitdata[i]="u";
if (splitdata[i]=="S-86")
splitdata[i]="v";
if (splitdata[i]=="S-87")
splitdata[i]="w";
if (splitdata[i]=="S-88")
splitdata[i]="x";
if (splitdata[i]=="S-89")
splitdata[i]="y";
if (splitdata[i]=="S-90")
splitdata[i]="z";
if (splitdata[i]=="96")
splitdata[i]="0";
if (splitdata[i]=="97")
splitdata[i]="1";
if (splitdata[i]=="98")
splitdata[i]="2";
if (splitdata[i]=="99")
splitdata[i]="3";
if (splitdata[i]=="100")
splitdata[i]="4";
if (splitdata[i]=="101")
splitdata[i]="5";
if (splitdata[i]=="102")
splitdata[i]="6";
if (splitdata[i]=="103")
splitdata[i]="7";
if (splitdata[i]=="104")
splitdata[i]="8";
if (splitdata[i]=="105")
splitdata[i]="9";
if (splitdata[i]=="106")
splitdata[i]="*";
if (splitdata[i]=="107")
splitdata[i]="+";
if (splitdata[i]=="109")
splitdata[i]="-";
if (splitdata[i]=="110")
splitdata[i]=".";
if (splitdata[i]=="111")
splitdata[i]="/";
if (splitdata[i]=="112")
splitdata[i]="**F1**";
if (splitdata[i]=="113")
splitdata[i]="**F2**";
if (splitdata[i]=="114")
splitdata[i]="**F3**";
if (splitdata[i]=="115")
splitdata[i]="**F4**";
if (splitdata[i]=="116")
splitdata[i]="**F5**";
if (splitdata[i]=="117")
splitdata[i]="**F6**";
if (splitdata[i]=="118")
splitdata[i]="**F7**";
if (splitdata[i]=="119")
splitdata[i]="**F8**";
if (splitdata[i]=="120")
splitdata[i]="**F9**";
if (splitdata[i]=="122")
splitdata[i]="**F11**";
if (splitdata[i]=="123")
splitdata[i]="**F12**";
if (splitdata[i]=="124")
splitdata[i]="**F13**";
if (splitdata[i]=="125")
splitdata[i]="**F14**";
if (splitdata[i]=="126")
splitdata[i]="**F15**";
if (splitdata[i]=="144")
splitdata[i]="**NumLock**";
if (splitdata[i]=="145")
splitdata[i]="**ScrLock**";
if (splitdata[i]=="186")
splitdata[i]=";";
if (splitdata[i]=="187")
splitdata[i]="=";
if (splitdata[i]=="188")
splitdata[i]=",";
if (splitdata[i]=="189")
splitdata[i]="-";
if (splitdata[i]=="190")
splitdata[i]=".";
if (splitdata[i]=="191")
splitdata[i]="/";
if (splitdata[i]=="192")
splitdata[i]="`";
if (splitdata[i]=="219")
splitdata[i]="[";
if (splitdata[i]=="220")
splitdata[i]="**backslash**";
if (splitdata[i]=="221")
splitdata[i]="]";
if (splitdata[i]=="222")
splitdata[i]="'";
}
System.out.println(splitdata[0]);
}
}
For example if I type 8 I should get a print that reads backspace, however it simply outputs 8. I'm sure it's a simple mistake that I've overlooked, but I'm pretty new to java so any help would be greatly appreciated.
Try this example:
import java.util.Scanner;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println ("Enter collected data:");
String data = input.nextLine();
input.close();
String[] splitdata = data.split("\\s+");
int datalength=splitdata.length;
for (int i=0; i<datalength; i++)
{
if (splitdata[i].equals("1") )
splitdata[i]="**newline**";
else if (splitdata[i].equals("8") )
splitdata[i]="**backspace**";
else if (splitdata[i].equals("9") )
splitdata[i]="**tab**";
else if (splitdata[i].equals("13") )
splitdata[i]="**enter**";
else if (splitdata[i].equals("16") )
splitdata[i]="**shift**";
else
System.out.println("oops!, no match for: " + splitdata[i]);
}
for(String s: splitdata)
{
System.out.println(s);
}
}
}
Apart from this, if you are allowed to collections then I would
suggest you to use HashMap instead atleast you can rid of this ugly
if-else
I am have trouble creating an array or object(with multiple fields) and sending it to an array-list. Any help would be greatly appreciated. I have spent hours looking through every video on YouTube with the words object and array-list in them and have been unable to find much help.
The program needs to prompt the user to pick a option (1. AddItem) then prompt the user for the name and format (dvd, vhs) and save multiple objects with these variables in an array-list. I either keep having the location where it is saved in memory returned to me or instead of multiple objects one large object is created.
Library:
import java.util.Scanner;
import java.util.ArrayList;
public class Library {
static ArrayList<Object> items = new ArrayList<Object>();
static int menuOption;
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
String title, format;
boolean right = false;
do{
displayMenu();
if (menuOption == 1){
System.out.println("Enter Title: ");
title = scan.next();
System.out.println("Enter format: ");
format = scan.next();
addNewItem(title, format);
} else {System.out.println(items);
}
} while (!right);
}
static int displayMenu(){
System.out.println("Menu: ");
System.out.println("1. Add New Item");
menuOption = scan.nextInt();
return menuOption;
}
static void addNewItem(String title, String format){
MediaItem b = new MediaItem();
b.setTitle(title);
b.setFormat(format);
items.add(b);
}
}
MediaItem:
public class MediaItem {
String title;
String format;
MediaItem(){
title = null;
format = null
}
MediaItem(String title, String format){
title = new String();
format = new String();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
The program will run if you:
1 - Change the line
static ArrayList<Object> items = new ArrayList<Object>();
to
static ArrayList<MediaItem> items = new ArrayList<MediaItem>();
2 - Change the line
System.out.println( items );
to
for ( MediaItem mi : items )
{
System.out.println( mi.getTitle() + ", " + mi.getFormat() );
}
3 - Insert a ";" at the end of the line
format = null
I did it here and it worked.
I either keep having the location where it is saved in memory returned to me
I am guessing you ran into this when you tried to either use System.out.println() to print a MediaItem, or you otherwise tried to automatically convert an object to a string. Whatever approach you took when you were seeing the memory addresses is probably the right way to do it, your problem was only in your displaying of the data.
Consider:
MediaItem item = ...;
System.out.println(item);
By default, Java doesn't know how to convert arbitrary objects to strings when you do stuff like that, and so it just spits out the class name and memory address. You either need to print the fields separately (e.g. Java knows how to display a String already), like:
System.out.println("Title: " + item.getTitle() + " Format: " + item.getFormat());
Or you can override toString() (declared in Object) to provide a custom string conversion:
class MediaItem {
...
#Override public String toString () {
return "Title: " + title + " Format: " + format;
}
}
And then you can print it directly:
System.out.println(item);
It is the default base implementation of Object.toString() that produces those strings with the memory address in them.
Based on your description, I'm guessing you had a roughly working implementation but ran into this issue and ended up changing around (and breaking) a bunch of other unrelated things to try and fix it.
So I'm working on a program to interface with a file based database. Mostly I'm trying to figure out how to work with it so that I can make objects and store their information in the database so that I can pull the data later.
IE Object Taylor
Name = Taylor
Age = 20
School = Whatever
So that I can get back on and call that information up when queried.
This is an example of an object I want to store. I may be doing this part wrong.
package com.catalyse.db;
public class Taylor implements java.io.Serializable
{
public String name = "Taylor M May";
public int age = 20;
public String school = "UC Boulder";
}
The DB structure I'm using is based on RandomAccessFile and I didn't make it, I'm just trying to figure out how to implement it.
package com.catalyse.db;
import java.util.*;
import java.util.Scanner;
/**
* Simple test class for the RecordsFile example. To run the test,
* set you CLASSPATH and then type "java hamner.dbtest.TestRecords"
*/
public class Run {
static void log(String s) {
System.out.println(s);
}
private static String name()
{
Scanner name = new Scanner(System.in);
String name1 = name.next();
return name1;
}
public static void main (String[] args) throws Exception {
System.out.println(new Date());
Scanner SC = new Scanner(System.in);
log("What would you like to name the database?");
String filename = SC.next();
log("creating records file...");
RecordsFile recordsFile = new RecordsFile(filename+".records", 64);
log("adding a record...");
RecordWriter rw = new RecordWriter("foo.username");
rw.writeObject(new Taylor());
recordsFile.insertRecord(rw);
log("reading record...");
RecordReader rr = recordsFile.readRecord("foo.username");
Taylor name = (Taylor)rr.readObject();
System.out.println("\tlast access was at: " + name.toString());
log("test completed.");
}
}
And here is what I get back from it,
Wed Nov 20 11:56:04 MST 2013
What would you like to name the database?
save3
creating records file...
adding a record...
reading record...
last access was at: com.catalyse.db.Taylor#50aed564
test completed.
My problem is that I want it to return information about the class, not just its name and location in the DB.
You need to override the toString method.
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Name: ");
sb.append(this.name);
//rest of fields
return sb.toString();
}
As a matter of clarity, you are not returning its location in the database. You are getting back the object hashValue + the class name.
At this point
Taylor name = (Taylor)rr.readObject();
You can access whatever information you like in the object, e.g.
Taylor name = (Taylor)rr.readObject();
System.out.println(name.age + ", " + name.name + ", " + name.school);
Alternatively, just add a
public String toString()
{
return name + ", " + age + ", " + school;
}
method in Taylor and then output it like so
Taylor name = (Taylor)rr.readObject();
System.out.println(name);
Now, concerning...
System.out.println("\tlast access was at: " + name.toString());
name.toString() isn't really required. If you append an object to a String then it automatically calls that objects toString() method to get a value.
Lastly, I'd like to note that generally we don't access object members like name, school and age by just accessing them. We generally make them private members then add methods to get and set them, so that we control and can track how they are manipulated.