How do I run this program in an applet? - java

package Homework;
import java.util.Scanner;
class FantasyGame{
public static void main ( String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest!");
System.out.println("Enter the name of your character: ");
String name;
name = scan.nextLine();
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest, " + (name) + "! " + "You will now assign attributes to your character, the total value assigned must not exceed 15 or be under 0, or the points will be assigned by default! (Type any NUMBER to continue)");
int ans = scan.nextInt();
System.out.println("Enter Strength (0-15): ");
int str = scan.nextInt();
System.out.println("Enter Health (0-15): ");
int hp = scan.nextInt();
System.out.println("Enter Luck (0-15): ");
int lck = scan.nextInt();
if (str + hp + lck <= 15)
{
System.out.println("Congratulations! You have successfully created your character!");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (str));
System.out.println("Health: " + (hp));
System.out.println("Luck: " + (lck));
}
if (str + hp + lck > 15)
{
System.out.println("You have give your character too many attribute points! Default values have been assigned.");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (5));
System.out.println("Health: " + (5));
System.out.println("Luck: " + (5));
}
}
}
I want to make a text-based game for my history class and I know basic Java enough to make a small one with just variables and stuff but I don't know how I can make it so that it runs directly as an applet with a black background and white text that shows up and responds to what you type, like the code above does in the console.
I've tried the command prompt method but all I get is "Access is Denied."
Also, when I try to export in eclipse, the launch configuration always goes to a class I don't want. Sorry but I am really confused and need a lot of help on this.

to write a simple applet, http://docs.oracle.com/javase/tutorial/deployment/applet/ this tutorial from oracle will walk you through it fairly well, it shouldn't be too hard to rearrange your code then

I figured it out. I just exported my program as a .jar and used Jar2Exe and it worked perfectly. Thanks!

You have not made you class public and that is why you are getting error "Access is denied" because it is not visible any more. Compiler is not able to find that class. Just write
....
//change is here
public class FantasyGame
{
....
}
....
Thanks !

Related

Input not converted to string?

I'm just getting started with Java (via an edX class), and one of the assignments is to create a vacation planner program that gathers information from the user. When I run the code in terminal, it works, but the strings "name" and "place" are not displayed correctly. Instead, the lines after the string declarations are displayed as "Nice to meet you + name + where are you traveling to?". Am I missing something that would have the input assigned to "name" displayed in the sentence?
The code below is for 1 of 4 methods that will be in the program. Image of my output:
import java.util.Scanner;
public class projectplanner{
public static void main(String[] args) {
partOne();
partTwo();
partThree();
partFour();
}
public static void partOne() {
[enter image description here][1] Scanner input = new Scanner(System.in);
System.out.print("Welcome to Vacation Planner!");
System.out.print("What is your name?" + "");
String name = input.nextLine();
System.out.println("Nice to meet you " + name + "where are you travelling to?");
String place = input.nextLine();
System.out.println("Great! " + place + " sounds like a great trip.");
}

Capturing first word and assigning a variable

public static void main(String[] args) {
// Create a usable instance of an input device
Scanner sc = new Scanner(System.in);
// Prompt user for input
System.out.println("Please enter you first name:");
// Capture first word and assign it to A Variable
String firstName;
firstName = sc.next();
//Construct the greeting
System.out.println("Hello, " + sc.next() + "!");
I am able to output the name on the screen but I have to type it in twice. I believe it is due to the sc.next statement but I am not for certain.
Yes, it is due to the sc.next() because you are doing it twice.
Change your last line to
System.out.println("Hello, " + firstName + "!");
use
System.out.println("Hello, " + firstName + "!");
after first sc.next() it's empty (also look nextLine)
The problem is that you call sc.next() twice:
firstName = sc.next(); // 1st time
//Construct the greeting
System.out.println("Hello, " + sc.next() + "!"); //2nd time
Please use the assigned variable firstnameinstead:
firstName = sc.next();
//Construct the greeting
System.out.println("Hello, " + firstName + "!");
This should fix you issue.
System asks you to enter 'first name' for 2 times because you calling sc.next() for two times.
To prevent this you can do it this way:
...
//Construct the greeting
System.out.println("Hello, " + firstName + "!");
...
or even this way, if you will not use String firstName in the future:
...
System.out.println("Please enter you first name:");
//Construct the greeting
System.out.println("Hello, " + sc.next() + "!");
...
I will also prefer to use nextLint() instead of next() because it automatically moves the scanner down after returning the current line.
If you interested you can take a look here:
https://stackoverflow.com/a/22458766/8913124

Counter Occurrences of User Specified String in a Text File

Count keeps coming up zero. I'm just trying to read the text file and look for the word, and display the count back to the user.
I'm not sure where it's falling apart. The If statement I think, but not sure where the syntax is going wrong. Thanks for any help!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.*;
public class TextSearchFromFile
{
public static void main(String[] args) throws FileNotFoundException
{
boolean run = true;
int count = 0;
//greet user
JOptionPane.showMessageDialog(null,
"Hello, today you will be searching through a text file on the harddrive. \n"
+ "The Text File is a 300 page fantasy manuscript written by: Adam\n"
+ "This exercise was intended to have the user enter the file, but since \n"
+ "you, the user, don't know which file the text to search is that is a \n"
+ "bit difficult.\n\n"
+ "On the next window you will be prompted to enter a string of characters.\n"
+ "Feel free to enter that string and see if it is somewhere in 300 pages\n"
+ "and 102,133 words. Have fun.",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
while (run)
{
try
{
//open the file
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
//prompt user for word
CharSequence findWord = JOptionPane.showInputDialog(null,
"Enter the word to search for:",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
count = 0;
while (scanner.hasNext())
{
if ((scanner.next()).contains(findWord))
{
count++;
}
} //end search loop
//output results to user
JOptionPane.showMessageDialog(null,
"The results of your search are as follows: \n"
+ "Your String: " + findWord + "\n"
+ "Was found: " + count + " times.\n"
+ "Within the file: An Ever Throne Tale 1.txt",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
} //end try
catch (NullPointerException e)
{
JOptionPane.showMessageDialog(null,
"Thank you for using the Text Search.",
"Text Search",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} //end run loop
} // end main
} // end class
EDIT:
Need help again. The instructor changed the parameters of the project and now I need to find word fragments like "th" or "en" and count those as well.
This I feel is beyond what he has taught and I have no idea how to make that work. I've googled until I can't google anymore.
You have to provide a File Object to Scanner in order to read the file, currently everything is getting searched in a String "An Everthrone Tale 1.txt"
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
And for searching a word, you need to do like this:
while (scanner.hasNext())
{
if (findWord.equals(scanner.next()))
{
count++;
}
}
and if you want to perform case-insensitive search then use String#equalsIgnoreCase instead of String#equals
Hope this helps

NoSuchElement Exception Error

I seem to be having some trouble getting my code to run properly here. What this is supposed to do is it is supposed to read from a text file and find the name, quantity, and price of an item on each line then format the results. The tricky bit here is that the items have names that consist of two words, so these strings have to be differentiated from the quantity integer and price double. While I was able to get this working, the problem that I am having is with a singe space that is at the very end of the text file, right after the last item's price. This is giving me a java.util.NoSuchElement Exception: null, and I cannot seem to move past it. Can someone help me to work out a solution? The error is on thename = thename + " " + in.next();
while (in.hasNextLine())
{
String thename = "";
while (!in.hasNextInt())
{
thename = thename + " " + in.next();
thename = thename.trim();
}
name = thename;
quantity = in.nextInt();
price = in.nextDouble();
}
You need to make sure the Name quantity price string is properly formatted. There might not be enough tokens in the string. To check that there are enough tokens for the name:
while (!in.hasNextInt())
{
thename = thename + " ";
if (!in.hasNext())
throw new SomeKindOfError();
thename += in.next();
thename = thename.trim();
}
You don't have to throw an error, but you should have some kind of code to handle this issue properly according to your needs.
The problem is in the logic of your inner while loop:
while (!in.hasNextInt()) {
thename = thename + " " + in.next();
}
In English, this says "while there's not an int available, read the next token". The test does nothing to help check if the next action will succeed.
You aren't checking if there is a next token there to read.
Consider changing your test to one that makes the action safe:
while (in.hasNext()) {
thename = thename + " " + in.next();
thename = thename.trim();
name = thename;
quantity = in.nextInt();
price = in.nextDouble();
}

Why does the compiler complain "while expected" when I try to add more code?

Write a program with a word containing # character as an input. If the word doesn't contain #, it should prompt the user for a word with #. Once a word with # is read, it should output the word then terminate.
This is what I have done so far:
public class find {
public static void main(String[] args) {
System.out.println(" Please enter a word with # ");
Scanner scan = new Scanner(System.in);
String bad = "#";
String word = scan.next();
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
}
}
I can get it to terminate after a word containing "#" is given as input, but if I try to add a Scanner to the line after "please try again", it says while expected.
I think issue is you are missing surrounding braces for do/while:
do
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
while ( !word.contains( bad ));
should be:
do
{
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
}while ( !word.contains( bad ));
Some people may not like this, but my suggestion is always use open/close braces. In this case, for the code if/else also. It avoids lot of confusion.
This is where your problem lies:
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
You need to put braces from where the loop starts until it ends. |So this thing should like:
do {
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
} while(!word.contains(bad));
For Better Practice You should Check do...while loops here.
The problem with your code is it is not re-reading the word in your loop.
Modify your loop like this (minimum change to your code).
do {
word = scan.next();
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
}
while (!word.contains(bad));
And yes as others have pointed out try to use braces especially with nested constructs.
There are two issues.
Your code is not using the braces properly
you are not attempting to read the new word if right word is not entered.
Also I prefer while loop better in the case as opposed to do-while loop as below.
Scanner scan = new Scanner ( System.in );
String required= "#";
System.out.println( " Please enter a word with # " );
String word = scan.next() ;
//check if the right word(containing #) is entered,
//if not then loop until it is enteres
while((!word.contains(required)){
System.out.println( " Please try again " );
//read the new word as input from the user
word = scan.next() ;
}
//right word is entered, display it
System.out.println(word);
Also please note that when you use scan.next(), it reads each word separately if entered in the same line.

Categories