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 7 years ago.
Improve this question
A friend and I are making a simple game where it randomly picks one of those names and the user has to guess it until he/she gets it right. , but we are getting an error saying: Exception in thread "main" java.lang.NumberFormatException: For input string: "Adam Kovic". Can anyone please help?
package projectpackage;
import java.util.Random;
import java.util.Scanner;
public class ProjectClass {
public static void main(String eth[]) {
int adam = Integer.valueOf("Adam Kovic");
int bruce = Integer.valueOf("Bruce Greene");
int joel = Integer.valueOf("Joel Ruben");
int spoole = Integer.valueOf("Sean Poole");
int larr = Integer.valueOf("Lawrence Sonntag");
int james = Integer.valueOf("James Willems");
int matt = Integer.valueOf("Matt Peake");
Random r = new Random();
int num[] = { adam, bruce, joel, spoole, larr, james, matt };
}
}
You could get away with just making an array of strings, each element being a string with one of those names, and have a randomized pick between 0 and 6; whichever number it picked would be the specific array element chosen. Then in the code for checking if the player has picked the correct name, simply compare the user's input string to the string array element the randomizer picked.
Because Integer.valueOf() expects a number in string format. example "23".
So it should used in this case Integer.valuOf("23")
Is this for your homework?
public static void main(String eth[]) {
List<String> names = new ArrayList<String>();
names.add("Adam Kovic");
names.add("Adam Kovic 2");
names.add("Adam Kovic 3");
names.add("Adam Kovic 4");
names.add("Adam Kovic 5");
Random r = new Random();
String name = names.get(r.nextInt(names.size()));
boolean guessed = false;
while (!guessed) {
// guess, you can figure out how to get the guess
String guess = "";
//
if (guess.equals(name)) {
System.out.println("you guessed correctly!");
guessed = true;
} else {
System.out.println("Wrong! " + guess + " is incorrect");
}
}
}
Related
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 5 years ago.
Improve this question
I apologize in advance for my post. I decided to register tonight and this is my first post.
A little background about the question.
I am doing a little java project, where I need to take a name from user input, which is saved in a variable. the variable value must then display the output.
my question is. How is it done in java, using the (if) keyword, to use my code to create an if statement that voids my simple i_PlayerName method of any logic error.
to be more specific, how can I make sure that my program will only accept a string value, and if another data type is entered, an output message will be displayed " user input not accepted ".
lastly, what is this procedure called?
Thank you all :)
keep on coding the code.
public void i_PlayerName() {
String playerName;
Scanner i_playerName = new Scanner(System.in);
System.out.println("ENTER YOUR SHIP NAME");
playerName = i_playerName.nextLine();
System.out.println("Your vessel has been named " + playerName);
}
Assuming you meant alphabets when you said only strings are allowed, this should do it.
public static void main(String[] Args) {
String playerName = "";
System.out.print("Enter ship name: ");
Scanner scanner = new Scanner(System.in);
String i_playerName = scanner.next();
System.out.println();
char[] chars = i_playerName.toCharArray();
boolean isChar = true;
for (char c : chars) {
if (!Character.isLetter(c)) {
isChar = false;
}
}
if(isChar == true) {
System.out.println("Your vessel has been named: " + i_playerName);
}
else {
System.out.println("User input is not accepted.");
}
}
when the scanner is reading if you assign it to a String type it will take the input as a String regardless if the user inputs numbers or Strings. If you want to handle the scenario when user inputs value other than String you can do it with regular expression and if the input is not a match then output the error. Use below method to check if input is a String.
public boolean isStringValue(String s){
String pattern= "[a-zA-Z]*";
return s.matches(pattern);
}
//use method above:
String input = scan.next();
if(isStringValue(input)){
//your code
} else {
//output some error
}
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 6 years ago.
Improve this question
I'm having a problem with making a 2d array that stores user input and shows an error when the name that you enter for example is already stored in that array.
this is my program so far...
import java.io.*;
import java.lang.*;
public class a extends b{
public static void main (String args[]) throws Exception{
String phonebook[][] = new String[2][];
BufferedReader input = new BufferredReader (new InputStreamReader (System.in));
System.out.println("[1] Add contacts");
System.out.println("[2] View all contacts");
int choice = input.nextInt();
selection(choice);
}
}
import java.io.*;
import java.lang.*;
public class b{
public static void selection(int choice){
case 1:
System.out.println("Enter name: ");
phonebook[0][0] = input.nextLine();
System.out.println("Enter landline or phone numbers: ");
phonebook[0][1] = input.next();
for(int x = 0; x < phonebook.length; x++){
for (int y = 0; y < phonebook[x].length ; y++){
}
}
break;
case 2:
show_phonebook(phonebook);
break;
default:
System.out.println("ERROR");
break;
}
public static void show_phonebook(String phonebook[][]){
System.out.println(phonebook[x][y]);
System.out.println();
}
}
I know this code looks shit but I'm still a noob. I don't know how to do the error thing so a little help will be very grateful. Thanks
Class names in Java Start with an Capital "A extends B"
I don't see a profit in inheriting another Class here. Define the methods in Class A
You will need a proper switch(argument) case: and so on....
showing all contancts should loop through the filled arrays.
For your error message solution: define a input string and try to check the indexes in the forloop equality: if(array [x][y].equals(input)){ code...}
Edit: you can make your check if "better" by first .toLowerCase the input and String at Array[x][y].toLowerCase -> the improvement would be that the user can check for MaRTin and if there was already an mArtIN stored, it will trigger.
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 8 years ago.
Improve this question
I'm kind of new to this stuff, but what i want to do is just print out 00s from an int array that i created. I used a stringBuilder() to get rid of the commas and stuff. Now when I print out the numbers, they must have a space after every third 0 (a total of 11 0s). How do I do that? I only get a space after every 0 :-(.
here is what I got so far.
public class AccountNumber {
private int[] digits = new int [11];
// Methods Returns a string representation
public String toString() {
StringBuilder builder = new StringBuilder();
for (int value :digits) {
builder.append(value + " ");
}
String text = builder.toString();
return text;
//return Arrays.toString(digits);
}
public AccountNumber ( boolean random ){
}
}
The output I want is 000 000 000 00
I have another (main) class which creates the object for me. That's where the printing should happen.
public class Test1 {
public static void main (String [] args) {
//Random rand = new Random(false);
AccountNumber acc = new AccountNumber(false);
System.out.println(acc.toString());
//AccountNumber.AccountNumber();
}
}
Thank you
You are trying to pretty print 11-digit account number on your Account class. You want to insert space after each 3 digits. If my assumptions are correct, you just need a counter to see which digit you're on and test if that digit can be divided by three:
int index= 0;
for (int value :digits) {
builder.append(value);
if (index %3 == 0) {
builder.append(" ");
}
++index;
}
This could be written in more clear way by using classic for loop, but I don't know which type your digits field is.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am writing a program for a school assignment to create one string array of 3 riddles and another string array of 3 answers to each riddle. However when I input the correct answer to the riddle it keeps on showing the else part of the if-else statement. Here's my code:
import java.util.Scanner;
import java.util.Random;
public class riddleProgram {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int index;
int chosenRiddles = rand.nextInt(2);
//declares the riddles in the program as well as choosing a random riddle from the three presented
String[]riddle = new String[3];
riddle[0] = "What starts with a T, ends with a T, and has T in it?";
riddle[1] = "The day before two days after the day before tommorrow is Saturday. What day is it today?";
riddle[2] = "What grows up while growing down?";
//declares the answers to the riddles
String[]answer = new String[3];
answer[0] = ("teapot");
answer[1] = ("friday");
answer[2] = ("goose");
//asks user to enter guessed answer for the randomly presented riddle
for (index=0; index<3; index++); {
System.out.println(riddle[chosenRiddles]);
System.out.print("Enter your answer for the presented riddle (lowercase): ");
String inputtedAnswer = input.nextLine();
//if user inputs right answer, congratulates user
//if user inputs incorrect answer, tells user the correct answer
if (inputtedAnswer == answer[chosenRiddles]) {
System.out.println("Congratulations, you have gotten the right answer!"); }
else {
System.out.println("Sorry you had the wrong answer. The right answer is " + answer[chosenRiddles] + ".");}
}
}
}
never compare strings with ==
you should always use .equals( )
if (answer[chosenRiddles].equals(inputtedAnswer)) {
you should also try to have the constant value (the one that will always exist) on the left of these, to prevent possible NullPointerExceptions.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm Raymond, computer programming student. I have problem about arrays. Are instructor ask us to do a program that goes like this.
in this codes below. i want to display the same item code i entered. but the problem is that once i answered yes and input again number, the only thing that display is the last number or code i enter.
import java.util.Scanner;
public class _TindahanArray {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String ans, i = "";
int x;
do {
System.out.print("Item code:");
i += a.next();
System.out.print("\nAnother item? [y/n]:");
ans = a.next();
} while (ans.equals("y"));
String[] code = new String[2];
for (x = 0; x < 1; x++) {
code[x] = i;
System.out.print(code[x]);
code[x] = "\n";
System.out.print(code[x]);
}
}
}
As you shown some efforts, I just want to update your code.
Your code is fine for only printing two item codes.
Use collection ArrayList to store the item codes. I am using String array list.
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayTest {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String ans;
ArrayList<String> itemCodeList = new ArrayList<String>(); //create array list
do{
System.out.print("Item code:");
itemCodeList.add(a.next()); //add item code into array list
System.out.print("\nAnother item? [y/n]:");
ans = a.next();
}while(ans.equals("y"));
for (String code : itemCodeList)
{
System.out.println(code);
}
}
}
ArrayList example