This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm new in Java and I find it very complicated because of the errors that I come across with. So I have a problem with this piece of code:
Main Class:
public class Main {
public static void main(String[] args){
Answer a = new Answer();
String ans = null;
while(ans != "A"){
ans = a.create();
System.out.print(ans + "\n");
}
}
}
Answer class:
import java.util.Scanner;
public class Answer {
public String create(){
Scanner s = new Scanner(System.in);
return s.next();
}
}
I want the program to allow me to write something. Then, if what I've written hasn't been the letter A, the program must allow me to write something else, otherwise has to stop. But, even though I write "A", the program is still keeping on, allowing me to write something else. What's wrong with the code?
String can't be compared properly using the != operator. Instead you should use while(!ans.equals("A")). Secondly, try not to recreate the Scanner object in the create method. This is a resource waste.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Looking for some help here. I'm trying to make this method work. Whenever I run the method, it throws IllegalArgumentException even if I do type in A,B,C or D. I am using an inputReader class. Here is the code for my DriverExam class. Please let me know where I am going wrong. I'd like it so the only valid answers are a,b,c,or d. I have to use a while loop and everything I've tried won't help me match the driverAnswers.
public class DriverExam
{
// instance variables
public static final String[] ANSWERS = {"B","D","A","A","C","A","B","A","C","D","B","C","D","A","D","C","C","B","D","A"};
private String [] driverAnswers;
private InputReader inputReader;
public DriverExam(){
driverAnswers = new String[20];
inputReader = new InputReader();
}
public void promptStudentAnswers(){
int index = 0;
while(index < driverAnswers.length){
System.out.println("enter answer");
String driverAnswers = inputReader.readString();
if(driverAnswers != ANSWERS[index]){
throw new IllegalArgumentException(" answers can only be A,B,C or D");
} else{
index++;
}
}
}
}
First, you want to test if the answer is one of A, B, C or D (not that the answer matches something in the correct answers array). Also, your driverAnswers is masked because you created another local variable with that name. Basically, I think you wanted something like
public void promptStudentAnswers() {
int index = 0;
while (index < driverAnswers.length) {
System.out.println("enter answer");
String answer = inputReader.readString().trim().toUpperCase();
if (answer.length() == 1 && "ABCD".indexOf(answer) != -1) {
driverAnswers[index] = answer;
index++;
} else {
System.out.println("Answers can only be A,B,C or D");
}
}
}
This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 4 years ago.
Newbie here.
I just want to ask, how to disallow someone to enter the same element in an array?
this is my code currently and it's not working properly:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String[] username=new String[5];
for (int c=0;c<5;c++)
{
System.out.print("Enter client name: ");
username[c]=input.nextLine();
if (username.equals(username[c]))
{
System.out.println("The client already exist.");
}
}
}
}
p.s. I hope you guys can help me.
While you can use an array to handle this problem in java there is a data structure that handle your problem very easily.
This data structure is a Set:
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
Try using a data structure such as a set, which makes it easy to determine if a certain username be already present:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<String> users = new HashSet<>();
while (users.size() < 5) {
System.out.print("Enter client name: ");
String username = input.nextLine();
if (!users.add(username)) {
System.out.println("The client already exist.");
}
}
}
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
I am trying to write a program, but my client might not type in the information in the correct format. How do I tell if a String is an int in Java (so I can throw an error message that I write and allows them to retry)? I.e., is there a method in java that will allow me to check if String str is of type int?
String input=kb.nextLine();
if(input.(isInteger method)&&(int)input==otherint)
do stuff inside here;
else
do different stuff;
An answer should include the imports needed (if any) and basic method. Also, as simple as possible would be very good. If this is actually a copy of a question, post the link (I looked for a while but couldn't find anything on google or here that seemed like it would solve my problem).
Create a methode in a class say IntegerCheck.java:
public Boolean isInteger (String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (Exception e)
{
return false;
}
}
Then use it in your program:
First import the class:
import <package name>.IntegerCheck;
Inside the required function:
IntegerCheck obj=new IntegerCheck();
String input=kb.nextLine(); //Get user input using Scanner or any other method, make sure the return type is string.
if(obj.isInteger(input))
{
//Success.
}
else
{
//throw an error message that I write and allows them to retry
}
package main.java;
public class Test {
public static boolean isNumeric(String s){
// 11 Because might be negative, but 32bit integer overflow is
// 10 characters long.
if (s.length() > 11) return false;
int i = 0;
if (s.startsWith("-")) i++;
for(; i < s.length(); i++){
if (!Character.isDigit(s.charAt(i))) return false;
}
return true;
}
public static void main(String[] args){
System.out.println(Test.isNumeric("100"));
System.out.println(Test.isNumeric("aa"));
System.out.println(Test.isNumeric("12a"));
System.out.println(Test.isNumeric("1002"));
System.out.println(Test.isNumeric("-11232"));
System.out.println(Test.isNumeric("999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"));
System.out.println(Test.isNumeric("4294967294"));
}
}
Edit I forgot to include negative numbers.
Edit Rough way to handle integer overflow.
Mind you this will only work with integers. Regular expressions seem a bit overkill for this, but aren't a bad solution. You should not use exceptions to control program flow as per this question: Why not use exceptions as regular flow of control?
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 7 years ago.
Currently I am working on an assignment within BlueJ.
The question I have is simple (I hope). The method I wish to use within the while loop is "getRearWheelDrive()" which checks how many Lamborghinis within the ArrayList< Lamborghini > inventory have rear wheel drive. rearWheelDrive is a boolean variable.
Also I can not use a for-loop for this question, otherwise I would as it would be much easier. I am limited to the while loop.
The error message I receive is: "non-static method getIsRearWheelDrive() cannot be referenced from a static context" -I tried to create a static method but it didn't work either.
//
How do I check all the Lamborghini objects within the ArrayList library and then return an int value of how many total have rearWheelDrive? Also with the current code I have, would it cause the loop to finish once it got to the end of the index, or would it infinitely loop?
public int howManyAreRearWheelDrive()
{
int indexPlace = 0;
int number = 0;
int i = 0;
while(indexPlace <= inventory.size())
{
indexPlace++;
inventory.get(i);
i++;
if(Lamborghini.getIsRearWheelDrive() == true) {
number++;
}
}
return number;
}
Without seeing the rest of the relevant classes in play here:
while(indexPlace < inventory.size())
{
if(inventory.get(indexPlace++).getIsRearWheelDrive() == true) {
number++;
}
}
You need to call getIsRearWheelDrive from an instance of the Lambroghini class not from the class itself. Only static variables can be called using the class name which is not the case here.
In this example it would be
inventory.get(i).getIsRearWheelDrive();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am trying to create a program that takes a file name as a parameter, opens that file, reads in all of the text in that file (about 1 paragraph) and then give the user a few options to manipulate the paragraph.
I am having trouble with the scanner which asks the user for the command. For example, if the user presses 1, I want it to take the user to public void palindrome (), but it won't compile.
I haven't written in the code yet for public void palindrome, but there shouldn't be any compiling errors.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
import java.io.File;
public class Test {
public static void main (String [] args) {
Scanner scanner = new Scanner(new File(args[0]));
ArrayList<String> strings = new ArrayList<String>();
while( scanner.hasNext() ) {
strings.add( scanner.next() );
}
ArrayList<String> a = new ArrayList<String>(strings);
while (true) {
System.out.println ("\nWhat would you like to do? Here are your options: \nPress 1 to Print all palindromes \nPress 2 to Replace any letter \nPress 3 to remove all occurences of a word \nPress 4 to exit\n");
Scanner s = new Scanner(System.in);
String command = s.next();
if (command.equals("1")) {
a.palindrome();
} else if (command.equals("2")){
a.letter();
} else if (command.equals("3")){
a.word();
} else if (command.equals("4")){
System.exit(0);
}
}
}
public void palindrome () {
}
public void letter () {
}
public void word () {
}
}
You have defined a as an Arraylist. and are calling a.palindrome().
An Arraylist does not have the method palindrome(), I believe you just want to call palindrome() of your Test class.
To do this either:
Create an instance of Test within your main class then call palindrome() on that instance (preferred option)
or
make the method static then call Test.palindrome()
In either case you may want to consider having it take in argument of an Arraylist
What you need to do is Create an instance of your Test class
Test test = new Test();
Then call
test.palindrome();
Compiler fails because, since you called a.palindrome() and a being an instance of ArrayList<String>(), and it doesn't have a method ArrayList class doesn't have a method called palindrome()