Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm trying to create a simple 20 questions game, by taking user input to take user input and I'm fairly new to programming java.
I have set up all the strings for my questions and I want to ask the user if they want to play. I was trying to set up a if-then statement with the user input, with the number 1 being Yes and number 2 being No.
How could I set this up? I tried with my if(in.nextInt() = a) statement but I know that's not right. I know I need to reference the previous user input, but how do I do that? Thanks for all your help in advance.
import java.util.*;
public class twentyq {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int a = 1;
int b = 2;
// all the Strings needed for Questions[represented by the Q(1-20) variable] and their Answers[represented by the AQ(1-20) variable]
String Q1;
String Q2;
String Q3;
String Q4;
String Q5;
String Q6;
String Q7;
String Q8;
String Q9;
String Q10;
String Q11;
String Q12;
String Q13;
String Q14;
String Q15;
String Q16;
String Q17;
String Q18;
String Q19;
String Q20;
String AQ1;
String AQ2;
String AQ3;
String AQ4;
String AQ5;
String AQ6;
String AQ7;
String AQ8;
String AQ9;
String AQ10;
String AQ11;
String AQ12;
String AQ13;
String AQ14;
String AQ15;
String AQ16;
String AQ17;
String AQ18;
String AQ19;
String AQ20;
// The questions and their answers in numerical order question first then answer immediately following.
Q1 = "Where would you find the Sea of Tranquility?";
AQ1 = "The Moon.";
Q2 = "What is the Capital of Spain";
AQ2 = "Madrid.";
Q3 = "What is the painting, La Gioconda, more usually known as?";
AQ3 = "The Mona Lisa.";
Q4 = "Which chess piece can only move diagonally?";
AQ4 = "A Bishop.";
Q5 = "What is the oldest surviving printed book in the world?";
AQ5 = "The Diamond Sutra, dated at 868 AD.";
Q6 = "Costing around $2,600 per pound, and made only to order by Knipschildt, what is the name of this chocolate truffle?";
AQ6 = "Chocopologie";
Q7 = "Who invented TV?";
AQ7 = "George Carey, a Boston civil servant, first thought up television in 1876. John Logie Baird is often quoted as its inventor but his ideas didn't come along until the 1920's.";
Q8 = "What is allspice alternatively known as?";
AQ8 = "Pimento.";
Q9 = "In publishing, what does POD mean?";
AQ9 = "Print on demand.";
Q10 = "What is John Leach famous for making?";
AQ10 = "Pottery.";
Q11 = "When was the euro introduced as legal currency on the world market?";
AQ11 = "1st January, 1999.";
Q12 = "How many valves does a trumpet have?";
AQ12 = "3.";
Q13 = "Which kind of bulbs were once exchanged as a form of currency?";
AQ13 = "Tulips.";
Q14 = "Name the director of the Lord of the Rings trilogy.";
AQ14 = "Peter Jackson.";
Q15 = "Name the largest fresh water lake in the world?";
AQ15 = "Lake Superior.";
Q16 = "Name the seventh planet from the sun.";
AQ16 = "Uranus.";
Q17 = "Which country is Prague in?";
AQ17 = "Czech Republic.";
Q18 = "What is the oldest film ever made, and when was it made?";
AQ18 = "Roundhay Garden Scene, made in 1888.";
Q19 = "Name the three primary colors.";
AQ19 = "Red, yellow and blue.";
Q20 = "How old is the world's oldest dictionary?";
AQ20 = "Cuniform tablets with bilingual Sumerian-Akkadian word-lists have been dated to 2300 BC.";
System.out.println("Welcome To KCH39's 20 Questions!");
System.out.println("Would you like to play? If yes, press 1 and enter. If not, press 2 and enter.");
in.nextInt();
if (in.nextInt() = a){
system.out.println(Q1);
}
}
}
You are using the assignment operator instead of the equals operator:
if (in.nextInt() == a){
system.out.println(Q1);
}
In your current code, change (in.nextInt() = a) to (in.nextInt() == a)
if(in.nextInt() == a){
System.out.println(q1);
}
= is an assignment operator and == (equality operator) is used for comparsion.
Source
Use equals operator (==) rather then assignment(=)....
in.nextInt();
if (in.nextInt() == a){
system.out.println(Q1);
}
other option is to assign that value first to another int and then check
int b == in.nextInt()
if(b==a)
Your program throws following compiler error. Insteed of comparing you are trying to assign value of 'a' into in.nextInt() which is impossible.
twentyq.java:120: error: unexpected type
if (in.nextInt() = a){
^
required: variable
found: value
1 error
So it must be fixed as follows(i.e use double equals):
if (in.nextInt() == a){
System.out.println(Q1);
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'll keep this short. I don't know why I'm getting NumberFormatException in my code. Any help would be much appreciated.
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void loadFiles() throws IOException {
Info i = new Info();
Song s = new Song();
int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7;
s.id = i.getSongTxt(a);
s.titulo = i.getSongTxt(b);
String ano = i.getSongTxt(c);
s.id1 = i.getSongArtistsTxt(a);
s.artista = i.getSongArtistsTxt(b);
s.id2 = i.getSongDetailsTxt(a);
String tempo = i.getSongDetailsTxt(b);
String explicita = i.getSongDetailsTxt(c);
String popularidade = i.getSongDetailsTxt(d);
String dancabilidade = i.getSongDetailsTxt(e);
String vivacidade = i.getSongDetailsTxt(f);
String volume = i.getSongDetailsTxt(g);
String[] ano1 = new String[ano.length()];
String[] tempo1 = new String[tempo.length()];
String[] explicita1 = new String[explicita.length()];
String[] popularidade1 = new String[popularidade.length()];
String[] dancabilidade1 = new String[dancabilidade.length()];
String[] vivacidade1 = new String[vivacidade.length()];
String[] volume1 = new String[volume.length()];
ano = ano.replaceAll("\\s+", "");
ano1 = ano.split(" ");
tempo1 = tempo.split("");
for(int n = 0; n < 7; n++){
s.ano[n] = Integer.parseInt(ano1[n]);
}
System.out.println(Arrays.toString(ano1));
}
public static void main(String[] args) throws IOException {
Info i = new Info();
loadFiles();
}
}
and this is what the error looks like.
Exception in thread "main" java.lang.NumberFormatException: For input string: "[2012,2013,2012,2013,2012,2013,2012]"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at pt.ulusofona.aed.deisiRockstar2021.Main.loadFiles(Main.java:44)
at pt.ulusofona.aed.deisiRockstar2021.Main.main(Main.java:55)
Process finished with exit code 1
Any ideas as to why it's giving me this error?
Read the Javadoc.
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Your input string "[2012,2013,2012,2013,2012,2013,2012]" is not a number. So that input cannot be processed as a number.
No more specific diagnosis can be made as you have shown too much code that does not matter, not enough code that does matter, and no example data.
I suggest reading the Help section of Stack Overflow to learn how to ask better questions. Specifically: How to create a Minimal, Reproducible Example.
"How do I stop it?"
Look at how you (supposedly) splitting the ano string.
ano = ano.replaceAll("\\s+", "");
ano1 = ano.split(" ");
That says:
Replace all whitespace with ... nothing. That is: remove all whitespace.
Split using a single space as the separator.
Which plainly doesn't make sense. You have removed the very characters that you are telling split to split on!
But that's wrong anyway, because the actual string you are attempting to process clearly also contains ',', '[' and ']' characters, and they shouldn't be part of the number strings.
So what you need to do is redesign the way you are splitting the ano string into a sequence of number strings ... so that it will work with your input.
Hint: find and read the javadocs for String.split(...) and Pattern.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is the code I'm working with and I got some errors I need help with so this code can work perfectly.
I got some errors on length cannot be resolved or not part of a field
the type of the expression must be an array type but it resolved to String
package daintree;
import java.util.*;
public class daintree {
String[] book = {
"Absolute Java",
"JAVA: How to Program",
"Computing Concepts with JAVA 8 Essentials",
"Java Software Solutions",
"Java Program Design"};
int[] amount = {5, 0, 5, 5, 1};
boolean[] eBook = {true, true, false, false, true};
String cart = " ";
public static void main(String[] args) {
}
public void addBooks() {
Scanner input = new Scanner(System.in);
System.out.print("Enter title to search for: ");
String book = input.nextLine();
for (int i = 0; i < book.length; i++) {
if (book[i].toLowerCase().startsWith(book.toLowerCase())) {
if (amount[i] > 0 || eBook[i] == true) {
cart = book[i];
System.out.println("The following title is a match:");
System.out.println("1. " + cart);
System.out.println("\n0. Cancel");
} else {
System.out.println("There is no title starting with that");
}
break;
}
I got some errors on length cannot be resolved or not part of a field
the type of the expression must be an array type but it resolved to
String
You have defined two variables with same name.
String[] book = {
"Absolute Java",
"JAVA: How to Program",
"Computing Concepts with JAVA 8 Essentials",
"Java Software Solutions",
"Java Program Design"};
String book = input.nextLine();
When it comes to the below line, programme is trying to check the length of the String book instead of the String[] book. Also in book[i]. Programme is trying to get an element from String book instead of the String[] book.
for (int i = 0; i < book.length; i++) {
if (book[i].toLowerCase().startsWith(book.toLowerCase())) {
if (amount[i] > 0 || eBook[i] == true) {
cart = book[i];
System.out.println("The following title is a match:");
System.out.println("1. " + cart);
System.out.println("\n0. Cancel");
} else {
System.out.println("There is no title starting with that");
}
break;
}
}
What you need to do is define the string array of books as String[] bookArr. Then change the book.length to bookArr.length and book[i] to bookArr[i]
Why are the variable q2,q3 not being initialized, yet q1 is?
This is how the outcome should be similar to:
WELCOME TO MITCHELL'S TINY ADVENTURE!
You are in a creepy house! Would you like to go "upstairs" or into
the "kitchen"?
kitchen
There is a long countertop with dirty dishes everywhere. Off to one
side there is, as you'd expect, a refrigerator. You may open the
"refrigerator" or look in a "cabinet".
refrigerator
Inside the refrigerator you see food and stuff. It looks pretty
nasty. Would you like to eat some of the food? ("yes" or "no")
no
import java.util.Scanner;
public class App1 {
public static void main(String[] Args) {
Scanner keyboard = new Scanner(System.in);
String q1;
String q2;
String q3;
String a = "upstairs";
String b = "kitchen";
String c = "refrigerator";
String d = "cabinet";
String e = "yes";
String f = "no";
String g = "hallway";
String h = "bedroom";
String i = "bathroom";
System.out.println("Welcome To Mitchell's Tiny Adventure!");
System.out.println();
System.out.println("You are in a creepy house, would you like to go upstairs or into the kitchen?");
System.out.print(">");
q1 = keyboard.nextLine();
System.out.println();
if (q1.equals(a)) {
System.out.println("Upstairs you see a hallway. At the end of the hallway is the master");
System.out.println("\"bedroom\". There is also a \"bathroom\" off the hallway. Where would you like");
System.out.println("to go?");
System.out.print(">");
q2 = keyboard.nextLine();
System.out.println();
} else if (q1.equals(b)) {
System.out.println("There is a long countertop with dirty dishes everywhere. Off to one");
System.out.println("side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\"");
System.out.println("or look in a \"cabinet\".");
System.out.print(">");
q2 = keyboard.nextLine();
System.out.println();
}
if (q2.equals(c)) {
System.out.println("Inside the refrigerator you see food and stuff. It looks pretty nasty.");
System.out.println("Would you like to eat some of the food? (\"yes\" or \"no\")");
System.out.print(">");
q3 = keyboard.nextLine();
System.out.println();
} else if (q2.equals(d)) {
System.out.println("Inside the cabinet is the boogie man, Are you scare? \"yes or no\"");
q3 = keyboard.nextLine();
System.out.println();
}if (q2.equals(g)){
System.out.println("You fall in the hallway can you make it? \"yes or no\"");
q3 = keyboard.nextLine();
System.out.println();
}else if (q2.equals(h)){
System.out.println("You run into the bedroom were there are monsters live are you afraid \"yes or no\"");
q3 = keyboard.nextLine();
System.out.println();
}else if(q2.equals(i)){
System.out.println("You run into the bathroom do you have to use it \"yes or no\"");
q3 = keyboard.nextLine();
System.out.println();
}
}
}
Every variable needs to be initialized, before it is accessed the very first time. This can happen automatically for constants and fields, but it needs to be done manually for local variables. So the developers has to decide which value should be the first value for a variable. Mostly it is either null (for object types) or 0/false (for primitive types).
So, now about your question:
Why are the variable q2,q3 not being initialized, yet q1 is?
About q1: the first time you try to read the reference "in" that variable is here:
if (q1.equals(a)) {
but before that, you're having this assignment:
q1 = keyboard.nextLine();
Here you initialize the variable q1 with the returned reference of the keyboard.nextLine() method call.
Now about q2:
(The problem with q2 and q3 are the same, so I just focus on q2).
You have this assignment in both the if and the else if block:
q2 = keyboard.nextLine();
So you try to assign it to another user input if q1 equals "upstairs" or "kitchen". But what will q2 be, if q1 is neither of them? Maybe it is "garden" or "downstairs", then q2 will remain uninitialized and the compiler can detect that, hence the error.
You must think about what to do if q1 is neither of them. You could ask the user again, until you get a valid answer. Or you can exit the program, if such situation is not allowed. It is up to you.
You could also initialize q2 and q3 with a certain default value to avoid that error and to avoid unexpected exceptions like a NullPointerException. It can be done like this:
String q2 = "";
String q3 = "";
In the first section, if all your tests for q1 were false, q2 would remain uninitialized, but you reference q2 in the 2nd section; similarly for q3.
If a code path exists that allows a local variable to be referenced without first being initialized, this compile error will occur.
Note that the compiler does not examine the logic aspects of the code, so for example this will fail to compile:
String a = "foo";
String s;
if (a.equals("foo")) {
s = "bar";
} else if (!a.equals("foo")) {
s = "baz";
}
System.out.println(s); // error
Even though we can see that logically s must be initialized, the compiler sees only boolean methods, which may result in s not being assigned.
You must initialize local variables before you use them. Try
String q1 = "";
String q2 = "";
String q3 = "";
well in line 42 :
if (q2.equals(c)) {
and in line 53 :
} else if (q2.equals(d)) {
you attempt to call the equals() method in an uninitialized variable (String q2) , try to initialize them first or check them for null values , it depends on how you want to handle each case
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
In Java, I am creating a program that asks the user to think of someone they know.
Then, my program asks that they enter the first letter of their first name, and the last letter of their last name, with no spaces.
I want my program to then look through an array of whole names, find the one whose first letter matches the first letter of user input, with the corresponding last letter of their last name.
here is my program so far:
import java.util.* ;
public class Guesser
{
public static void main(String[] args)
{
Scanner UserInput = new Scanner(System.in);
String [] names = {"firstname lastname " + "etc"}; //example name array
System.out.print( "Hello! I am a robot. I might be smart, but I don't know. Please play a game with me to help me see if I am smart." + "\n" + "What I want you to do is think of someone you know." + "\n" + "Enter the first letter of their first name, and the last letter of their last name. Please no spaces. Then, press enter. " );
String TheirGuess = UserInput.nextLine(); //get their input, assign a string to it
System.out.println("You entered: " + TheirGuess);
char FirstChar = TheirGuess.charAt(0); // get the the first char
char SecondChar = TheirGuess.charAt(1); // get the second char
System.out.println("I will now think of someone whose first name starts with " + FirstChar + " and last name ends with " + SecondChar );
UserInput.close();
}
}
How would I search in my string array for a name that has FirstChar as the first character and SecondChar as the last char?
This can be done in 1 line of code.
// Assuming you have populated a Set (actually any Collection) of names
Set<String> names;
List<String> matchedNames = names.stream()
.filter(s -> s.matches(userInput.replaceAll("^.", "$0.*")))
.collect(Collectors.toList());
If you just want to print the matches, it's even simpler:
names.stream()
.filter(s -> s.matches(userInput.replaceAll("^.", "$0.*")))
.forEach(System.out::println);
This code recognises that you can have multiple matches.
Although this may seem like spoon feeding, value to you of this answer is figuring out how it works.
The efficient way to do this would be to use two TreeSet objects. One contains Names and the other contains Last names. Then you can use subSet() method to get entries. So, example:
TreeSet<String> names = new TreeSet<>();
names.add("Antonio");
names.add("Bernard");
names.add("Peter");
names.add("Zack");
Set<String> bNames = names.subSet("B", "C");
Note, that this implementation is case sensitive. But with few adjustments you can fix it - I'm leaving this to you.
Havn't written in Java for a while, but it should go something like this:
String names[] = new String[] { "AAA BBB", "CCC DDD", "EEE FFF" };
Scanner input = new Scanner(System.in);
String userInput = input.nextLine().toLowerCase();
String result = "None";
for (String name : names) {
String[] nameSplitted = name.toLowerCase().split(" ");
if (nameSplitted[0].charAt(0) == userInput.charAt(0) &&
nameSplitted[1].charAt(0) == userInput.charAt(1)
) {
result = name;
break;
}
}
System.out.println("Result is: " + result);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hi i'm trying to make a questions game to try my knowledge and abilities
anyway i'm trying to use an integer to be the points and every question the user
answer gets a special amount of points anyway i was trying to do like this
switch (Ques){ case 1 : //first question about India and where it is in the map
System.out.println("in what continent India is?");
Scanner IndiaAns = new Scanner(System.in); //Scanner to receive user answer
String IndiaAns2 , IndiaAnswer ; //strings to be used to receive user input and matching with the correct ones
IndiaAns2 = IndiaAns.nextLine(); //Scanner will work here and receive...
IndiaAnswer = "asia"; //the correct answer here and will be matched with user ones
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
case 2:
System.out.println("the Appstore founds in any phone model?");
Scanner Appstore =new Scanner(System.in);
String AppstoreAns1 ,AppstoreAns2; //strings saving
AppstoreAns1 = Appstore.nextLine(); //Scanner
AppstoreAns2 = "iphone"; //matching with user answer
if (AppstoreAns1 == AppstoreAns2)
{ int Threepoints = 3; Points = +Threepoints;} else { Points = +0;}
.. there's two other case and the points integer is in not in the code sample area is in upper line any ways if the full codes its necessary i'll put it
About your code ,
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
Should be something like
if(indiaAns2.equals(indiaAnswer)){
points += QUESTION_1_POINTS;
}
Where QUESTION_1_POINTS is defined as a constant like `
public static final int QUESTION_1_POINTS =2;
There you are assigning to points variable , points + QUESTION_1_POINTS.
points += someInteger --> points = points + someInteger
Some advices,
1) Follow Java Code Conventions , variable names start with lower-case
2) For object comparision always use equals() instead of ==
Example:
Change
if (IndiaAns2 == IndiaAnswer)
to:
if (indiaAns2.equals(indiaAnswer))
3) You need to make switch statement
switch(condition){
case 1:
//code
break;
case 2:
//code
break;
default:// some code;
}