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.");
}
Related
I am trying to create a code that accepts a user's full name and returns first and last names and initials. Since a user's name length varies, I did not want to use hard coding, so I extract names and initials programmatically.
However when I run it and enter a name, I get the following error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
I looked into my code carefully and cannot see where exactly I miscalculated on the index range. I tried to find similar questions here, but though I did see similar problems, they have to do with C++ or Perl, not Java.
package nameSubstring;
import java.util.Scanner;
public class NameSubstring {
public static void main(String[] args) {
/*
* This is a program that accepts a user’s full name as a string (e.g. Margaret Thatcher) and displays to the user his/her first name, last name and initials in the following format:
Your first name is Margaret and your last name is Thatcher and your initials are MT.
*/
System.out.println("This program will take your full name and display your first name, last name, and initials.");
Scanner scanner = new Scanner(System.in);
String firstName, lastName, firstNameInitial, lastNameInitial;
System.out.println("Please enter your full name, e.g. Jane Smith:");
String fullName = scanner.next();
int nameSpace = fullName.indexOf(' ');
firstName = fullName.substring(0, nameSpace);
lastName = fullName.substring(nameSpace)+1;
firstNameInitial = firstName.substring(0, 1);
lastNameInitial = lastName.substring(0, 1);
System.out.println("Your first name is " + firstName + ", " + "your last name is " + lastName + ", " + "and your initials are " + firstNameInitial + lastNameInitial + ".");
}
}
Instead of next() use nextLine():
String fullName = scanner.nextLine();
and correct the error with the +1 which must be inside the parenthesis:
lastName = fullName.substring(nameSpace+1);
I just want a simple popup message box that asks for multiple inputs and such.
System.out.println("Please enter Name");
Name = name.nextLine();
System.out.println("Please enter Age");
age=ages.nextInt();
System.out.println("Please enter Gender");
Gender =gender.nextLine();
System.out.println("Please enter Contact Number");
ConNum =number.nextLine();-->
Is there a way to make a gui for this? (its a foundation level project)
Use JOptionPane to take your input:
String name = JOptionPane.showInputDialog(null, "Please enter Name");
Edit:
You could ask the user all the questions on the one box (for this example, ensure they separate the answers by a space).
String input = JOptionPane.showInputDialog(null, "Please enter name.\nPlease enter age.\nPlease enter gender.");
String[] allInput = input.split("\\s+");
System.out.println("Name: " + allInput[0] + " Age: " + allInput[1] + " Gender: " + allInput[2]);
Note: obviously there will be issues, such as not using a space, or using a full name (Jack Sparrow) etc; but it gives you a general idea.
As #notyou mentioned you can use JOptionPane it's very simple to implement it into you code check this example :
import java.io.*;
import javax.swing.*;
public class SystemOutDialog {
public static void main(String[] args) {
// set up a custom print stream
CustomPrintStream printStream = new CustomPrintStream();
System.setOut(printStream);
// from now on, the System.out.println() will shows a dialog message
System.out.println("hello!");
System.out.println("how are you?");
}
}
class CustomPrintStream extends PrintStream {
public CustomPrintStream() {
super(new ByteArrayOutputStream());
}
public void println(String msg) {
JOptionPane.showMessageDialog(null, msg);
}
}
Source link
The assignment:
Write a program (Greetings) that prompts the user to enter the first name, the last name, and year of birth, then it returns a greetings message
in proper format (see the example below).
Create a method(s) that accept the scanner and a prompt as parameters and return the user input. A separate method should accept the user input results as parameters, format and print the results. No print statement or scanner input should happen inside main(). Here is an example dialogue with the user:
Please enter your first name:
tom
Please enter your last name:
cruise
Please enter your year of birth:
1962
Greetings, T. Cruise! You are about 53 years old.
I finished the code, but right now it is giving me a compilation error. How do i fix it?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
Scanner newscanner = new Scanner(System.in);
String ask = ("Please enter your first name: ");
String ask2 = ("Please enter your last name: ");
String ask3 = ("Please enter your year of birth: ");
public static String getString(Scanner newscanner, String ask, String ask2, String ask3){
System.out.println(ask);
String first = newscanner.next();
String firstletter = first.substring(0,1).toUpperCase() ;
return firstletter;
System.out.println(ask2);
String second = newscanner.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
String lastname = y.substring(0,1).toUpperCase();
return lastname;
System.out.println(ask3);
int third = newscanner.nextInt();
int age = (2015 - third);
return age
System.out.println("Greetings, "+ firstletter + ". " + lastname+"!" +" You are about " + age + " years old");
}
}
}
Hard to read, but I think you actually have the getString() method inside your main() method - it needs to be after it, and only be called from inside main(), not defined there.
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
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 !