Trying to test my java "skills" and make a text based game--except i can't get the user input. i already importd the scanner class, and it works well w/ integers so idk what the problem is quite frankly. whenever i try to compile it, the lines containing "String name = scanner.next();" show up with a 'Scanner cannot be resolved' error.
import java.util.Scanner;
public class CH1 {
public static void main (String args[]) {
Scanner s= new Scanner( System.in);
int answer;
System.out.println ("You're in grave danger, but first, I must know your name. Will you tell me? ");
answer = s.nextInt();
if (answer == 1) {
System.out.println ("I respect your decision, but I'll need to know your name
if you turn up dead, unless you want to have a one man funeral.");
System.out.println ("What's your name?");
String name = scanner.next();
}
else if (answer == 2) {
System.out.println("Great, now what's your name?");
String name = scanner.next();
}
else {
System.out.println(" Huh? I didn't really get that. (1 for no, 2 for yes.)");
}
}
}
You named that scanner s first!
You can't just use a different name later on!
So simply change the scanner variable name to "scanner" and keep using that name.
Beyond that: Single character variable names are something you almost never do (except for index values in for loops). The point is: variable names should say something about the thing they denote. "s" says nothing!
Related
public static void main(String[] args) {
//For String
Scanner input = new Scanner(System.in);
//For Letter
Scanner word = new Scanner(System.in);
String name;
//Input For a String
System.out.println("Enter A String");
name = input.nextLine();
//Input For a Char
char letter[] = new char[3];
System.out.println("Enter a Letter You Want to Search ");
for(char c : letter)
letter = word.nextLine().toCharArray();
elfish(letter, name);
}
public static void elfish(char letter[], String name) {
if(name.toLowerCase().contains(name.valueOf(letter).toLowerCase())) {
System.out.println("Yes The Letter Contains Elfish");
} else {
System.out.println("You're Word is not in this String");
}
}
i m making the program which is near to completion. It actually searches the desired letter in the string and if condition is true is prints the "if block" and if condition is false "else block" should run but actually its not working now. only "if block" is working. "else block" was also working fine until it was directly placed in main function. please tell me where what is wrong.
You're trying to iterate through letter before putting anything in the array. If you take out the for loop, (leaving the assignment of letter) the code should run properly in many cases. I do not know how you want to validate input.
I'm guessing you are new. Learning to use a debugger can be overwhelming, but it is a powerful tool. It'll be slightly different for every debugger and IDE but the process is the same.
A little more info here: Breakpoints and step by step debug in Java?
However, in this instance finding a guide for your IDE on Google might be the best option.
in my intro to programming class. I am supposed to make a program that asks the user to enter his/her name and then use a while loop to print the name in the following manner:
(user entered Caroline)
C
a
r
o
l
i
n
e
Caroline, there are 8 letters in your first name.
--I've tried a bunch of things but still can't figure it out.--This is what I have so far
Assuming you are correctly getting the user entered string from the STDIN.
You may look to do something like this in your language of choice:
Find the length of your string
Use the while loop, with the condition relating to the length of your string, to move through the string character by character
Print out to a newline each individual character in your string
Feel free to ask questions and I would be happy to elaborate. Adding some examples of your code so far and the problems your facing would be useful.
In C++, this would be:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i=0;
string s;
cin>>s;
while(i<s.length())
{ cout<<i+1<<"."<<cout<<s[i]<<endl;
i++;
}
cout<<s<<", "<<"There are "<<s.length()<<" letters in your first name.";
return 0;
}
This is also very similar in Java, you should be able to derive it looking at this if you expected it in a programming language of your choice.
inside your main method try this:
//Asks user name.
System.out.println("What's your name?");
//Instantiates scanner
Scanner sc = new Scanner(System.in);
//With the scanner it reads user input and save it in the variable name
String name = sc.nextLine();
//It is a good programming practice to close the scanner
sc.close();
/*The loop that for each letter of the name also prints the position
number plus 1*/
int i = 0;
while (i < name.length()) {
System.out.println(i+1 + ". " + name.charAt(i));
i++;
}
As per snap shot shared by OP:
Here, you need to modify this lines:
System.out.println(name.charAt(i));
to
System.out.printf("%d. %c%n",(1+i),name.charAt(i));
Also, change this line:
i++;
}}}
to
i++;
}
System.out.printf("%s, there are %d letters in your first name%n",name,i));
}}
This is my first post here, so I decided to browse around various posts here in order to try and get a feel for how questions should be posted.
Hence, if I mess up please let me know so I can fix my post accordingly ASAP.
So here is my problem:
I started learning Java today and I'm working on just getting a feel for how everything works. I have the code below set to tell if kids are good or bad and display corresponding replays.
Good kids get candy, bad kids get none. I want to be able to limit the users choices to good or bad and have their answer change the Boolean to true or false to run the right if statement.
I saw a Math.random way of doing it but when I tried it I got more problems.
Thank you for your time.
The following is my code:
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int bad = 1;
String a = sc.nextLine();
int answer = candy / kids;
String answer2 = "No Candy";
boolean good = false;
System.out.println(a);
//closeing the scanner
sc.close();
if(bad == 1) {
System.out.println(answer2);
} else {
if(bad == 2)
good = true;
System.out.println(answer);
}
if(good == true) {
System.out.println("Good Job");
} else {
System.out.println("Try again tomorrow!");
}
}
}
For one, it is not necessary to end the scanner before your code ends. You can leave it around, closing it is not necessary. (Unless your IDE forces you to , then yes, you should, but close it at the end just in case. I have Eclipse, so my code still runs without a glitch.)
Another comment is, just for the sake of aesthetics you should concatenate some kind of string on to the end of answer, so the reader understands what the variable means.
One more thing. I often find it helpful to name my scanner something a little more intuitive, such as input. Because after all, that's what it is. (I'm only commenting a lot about your code because you are just beginning to learn things, so you should get into good habits early.)
What you can do in this situation is convert your string inputs to booleans, by using boolean userInput = Boolean.parseBoolean(answer). Then, depending on the input the user gives by using an if statement, they can control the flow of the code.
I cleaned up your code a little bit, if you don't mind.
import java.util.Scanner;
public class lol {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int answer = candy / kids;
String answer2 = "No Candy";
System.out.println("Are youkids good or bad?");
System.out.println("[1] Good = true");
System.out.println("[2] Bad = false");
String a = sc.nextLine();
boolean userInput = Boolean.parseBoolean(a);
if(userInput== false){
System.out.println(answer2);
System.out.println("Try again tomorrow!");
}
else{
System.out.println("Good Job");
System.out.println("You get" +answer+"pieces.");
}
}
}
Seeing as you're just starting out, I'll try and keep it simple. There are plenty of ways to force your reader to say either "good" or "bad" that are better than below, but they require loops (which I assume you haven't touched yet).
Consider the following:
boolean good = false;
if (a.equals("good")) { // they said good
good = true;
} else if (a.equals("bad")) { // they said bad
good = false;
} else { // they said neither
System.out.println("You didn't say a correct word!");
}
You first specify that you have a boolean good (which you can either give a default value as above, or nothing). Then, depending on the user's input, you can set the boolean to be whatever is appropriate.
The reasoning behind having to declare the boolean good above the if statements has to do with the scope of a variable. If your book/teacher hasn't explained what that is, you should look it up now. The TL;DR is that if you only first declare your variable inside the if statements, then it will disappear as soon as you leave the if statements. You can see how in this case that would basically defeat the purpose of the if statements entirely.
You can limit the input by enclosing it in a loop.
List<String> accepted = new ArrayList<String>();
accepted.add("good");
accepted.add("bad");
System.out.println("Good or bad?");
String input = sc.nextLine();
while(!accepted.contains(input)) {
System.out.println("Invalid query '" + input + "'. Try again.");
input = sc.nextLine();
}
The code you have, well I don't know exactly what it's trying to do. It doesn't look functional at all. So where this fits in I'm not 100% sure.
package test;
import java.util.Scanner;
public class app {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
String a="?";
while(!a.equals("good") && !a.equals("bad")){
System.out.println("Was the kid good or bad ?");
a = sc.nextLine();
}
boolean wasKidGood = a.equals("good");
String result = (wasKidGood ? "Good kid gets candy" : "No candy for bad kid");
System.out.println(result);
sc.close();
}
}
Hello, I wrote something, that will help you grasp a while loop and a ternary operator (alternative version of if loop). You also need to pay attention as to where you are allowed to use == and where you should use the equals() method. Regards
I'm having trouble finding out the reason im getting the expected class error. I have a class declared that houses just one main method but even when I comment out everything but the brackets I still get the same error. I've been looking at the four brackets for a while now, and can't seem to figure out what the problem is. How can i tell if two java files are in the same "package?"
Also, it's pointing to after my last bracket for where it thinks the error is.
EDIT: I decided to just write more code and now I'm getting a not a statement error on line 17 of my code. the integer declaration. I'm very confused as to what's happening
import java.util.Scanner;
public class BugTester
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int userMove;
char userDir;
Bug lady = new Bug(1,1,'E');
lady.draw();
lady.printCurrentPosition();
int continue=1;
while (continue ==1)
{
System.out.println("Please enter new Direction");
userDir = (char) System.in.read();
System.out.println("Please enter Distance to be moved");
userMove = in.nextInt();
lady.turn(userDir);
lady.move(userMove);
System.out.println("Again(0 to stop)?");
continue = in.nextInt();
}
}
}
You probably have an invalid invisible char at the end of file. You can go to the end with the cursor and then delete all chars after the last bracket. It has helped for me.
EDIT
Remark about your new code:
The word "continue" is a keyword in Java, you cannot use it as variable name.
I ran into an issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.
The problem is that the program never ends, and from my limited understanding, it seem to get stuck inside the while loop. Could anyone help me a little?
import java.util.Scanner;
public class Test{
public static void main(String args[]){
System.out.print("Enter your sentence: ");
Scanner sc = new Scanner (System.in);
while (sc.hasNext() == true ) {
String s1 = sc.next();
System.out.println(s1);
}
System.out.println("The loop has been ended"); // This somehow never get printed.
}
}
You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.
while(!s1.equals("exit") && sc.hasNext()) {
// operate
}
If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":
while(sc.hasNext()) {
String s1 = sc.next();
if(s1.equals("exit")) {
break;
}
//operate
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:
String s1 = sc.next();
if (s1.equals("exit")) {
break;
}
Break will get you out of the loop.
Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).
it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer.
the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD
If you don't want to use an EOF character for this, you can use StringTokenizer :
import java.util.*;
public class Test{
public static void main(){
Scanner sc = new Scanner (System.in);
System.out.print("Enter your sentence: ");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
while (st.hasMoreTokens() ) {
String s1 = st.nextToken();
System.out.println(s1);
}
System.out.println("The loop has been ended");
}
}
I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.
Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();
Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();
while (input.hasNext()) {
arg.add(input.next().toLowerCase());
}
You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}