initialization problems? - java

I am trying to make a program that lets the user enter an unknown value of names and then output the longest name entered. This is my code so far. When i compile I have several errors and they are all the same "cannot find symbol". Do i need to initialize those variables if so where?
import java.util.Scanner;
public class Name
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
longestName(kb);
}
public static void longestName(Scanner sc)
{
String name=kb.nextLine();
biggestName=name;
System.out.println("Type -1 if you want to quit");
int number=kb.nextInt();
While (number !=-1);
{
String name1=kb.nextLine();
if (name1.length() > biggestName)
{
biggestName=name1;
}
System.out.println("Do you want to continue? Type -1 to quit.");
int number1=kb.nextInt();
}
System.out.println("Longest name is "+biggestName);
}
}
Thanks for the help guys fixed the errors, and some other changes and the program gives the correct output.
import java.util.Scanner;
public class Name
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
longestName(kb);
}
public static void longestName(Scanner kb)
{
String biggestName;
System.out.println("Enter the first name");
String name=kb.nextLine();
biggestName=name;
System.out.println("Type -1 if you want to quit");
int number=kb.nextInt();
while (number !=-1)
{
System.out.println("Enter another name");
Scanner kb1 = new Scanner(System.in);
String name1=kb1.nextLine();
int length1=biggestName.length();
int length2=name1.length();
if (length2 > length1)
{
biggestName=name1;
}
System.out.println("Do you want to continue? Type -1 to quit.");
number=kb.nextInt();
}
System.out.println("Longest name is "+biggestName);
}
}

There are quite a few errors in your code. Without explaining every error in detail, here is an example of a modified version which works:
import java.util.Scanner;
public class Name
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
longestName(kb);
}
public static void longestName(Scanner sc)
{
System.out.println("Enter name, or type '-1' if you want to quit");
String name=sc.nextLine();
String biggestName="";
while (!name.equals("-1"))
{
if (name.length() > biggestName.length())
{
biggestName=name;
}
name=sc.nextLine();
}
System.out.println("Longest name is "+biggestName);
}
}

You passed in your Scanner to longestName, but in longestName, you named the parameter sc. Use sc instead of kb in longestName.
Use lowercase while instead of While; remove the semicolon following the while; a semicolon there means that that is the body, instead of the { } block below it.
I assume that at the bottom of the while loop, that you want to assign the next integer to number, not a new variable number1 that immediately goes out of scope.
You didn't declare what biggestName is (or name).

Two errors here :
While (number !=-1);
While should be while, and the ; makes an infinite loop.
And another problem is that you don't change number in the loop anyway.

1-
public static void longestName(Scanner sc)
Either change the name of the scanner to kb, or change every kb within the method to sc.
2- See Scanner issue when using nextLine after nextXXX
3- Use while instead of While, and remove the ;.

I can see the below problems in the code:
longestName() method should be using the reference name sc instead of kb (since kb is having scope only in main method)
The variable biggestName is not declared. It should be either declared as a class variable or a variable in longestName() method and should be of type String
It is not While, it is while with 'w' in smaller case
There should not be a semicolon after the while statement
At the end of the while loop, the number to be compared for the while loop is to be calculated and is currently assigned to wrong variable. kb.nextInt() should be assigned to variable number and not to number1 since the variable number1 is never read/used.
The > operator can not be applied for String types. In the line if (name1.length() > biggestName), we are comparing int with String and will result in compilation error. The line should be modified as if (name1.length() > biggestName.length())
Method nextInt() will cause InputMismatchException to be thrown if you are providing an input which is not a number.
Now I feel I should have written a corrected code like Joe Elleson did. But hope this answer helps.

Related

Scanner variable cannot be resolved

In my program, the user will be asked to input 3 integers. The integers will then be read using the Scanner class and listed back to the user.
This is my code:
import java.util.Scanner;
public class Echoer
{
public static void main(String[] args)
{
/* The Data Below Will Read The Numbers Input Into The Prompt*/
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Three Integers: ");
int number;
number = input.nextInt();
Scan.close();
System.out.println("Thanks. The Numbers You Entered Are: " + number);
}
}
This is the error it returns:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Scan cannot be resolved
Why does it return this error? How can I fix this issue?
In your code, you never defined what Scan was. Use input.close() rather than Scan.close().
Scan cannot be resolved
means that you never defined Scan. This is because you said Scan.close(). You need to change it to input.close() because input is the name of the instance of the Scanner class.
As others pointed out, you have to close input instead of Scan as shown below.
import java.util.Scanner;
public class Echoer
{
public static void main(String[] args)
{
/* The Data Below Will Read The Numbers Input Into The Prompt*/
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Three Integers: ");
int number;
number = input.nextInt();
input.close();
System.out.println("Thanks. The Numbers You Entered Are: "+number);
}
}

How to make java scanner accept more than one string input?

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}
Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.
Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).
You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

My code isn't working

I am a beginner programmer and i am trying a program for my father.
import java.util.*;
import java.lang.*;
import java.io.*;
class Employee
{
String m1,m2,m3,m4,m5,m6,m7;
void main()
{
Scanner w=new Scanner(System.in);
Scanner n=new Scanner(System.in);
System.out.println("Please enter your name ");
String name=w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client=n.nextInt();
m1=name;//Storing name
if(client==1)//If statement storing client
{
m2="XXXXXX";
}
else
{
System.out.println("You have entered a wrong choice");
return;
}
String msg=m1+"\t"+m2;
System.out.println(msg);
}
}
This Code will give the output "as you have entered a wrong choice'"
It jumps to elsse statement. What is the error and is there an easier way to run this program. Thanks
Could yo please inform me on my error as
Ok try this code:
import java.util.Scanner;
public class Try
{
static String m1,m2,m3,m4,m5,m6,m7;
public static void main(String[] args)
{
Scanner w=new Scanner(System.in);
System.out.println("Please enter your name ");
String name=w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client=w.nextInt();
m1=name;//Storing name
if(client==1)//If statement storing client
{
m2="XXXXXX";
}
else
{
System.out.println("You have entered a wrong choice");
return;
}
String msg=m1+"\t"+m2;
System.out.println(msg);
}
}
You have missed you main method signature. In Java there is a specification of main method. Your main method should be like
public static void main(String []args){
}
In your case you main method should be
public static void main(String args[]) {
String m1, m2, m3, m4, m5, m6, m7;
Scanner w = new Scanner(System.in);
Scanner n = new Scanner(System.in);
System.out.println("Please enter your name ");
String name = w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client = n.nextInt();
m1 = name;//Storing name
if (client == 1)//If statement storing client
{
m2 = "XXXXXX";
} else {
System.out.println("You have entered a wrong choice");
return;
}
String msg = m1 + "\t" + m2;
System.out.println(msg);
}
Your problem are the 2 scanners.
Because a scanner work with an iterator, that keep the position inside the given inputstream (in this case), when you instantiate the 2 scanners, they both set their iterator at the same position into the stream, then you use "w.nextLine();", and the first scanner advances trough the stream returning the first line, as you wish, but the second scanner, that you haven't used, is still at the beginning of the stream, so basically when you use n.nextInt();, the scanner tries to parse your name as int, and it's strange that it doesn't throws an InputMismatchException, as it should do ("https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29").
Rework your code as #Sarthak Mittal suggested and it should work.
PS: keep in mind indentation, it's important, really
First:
void main()
There is no such thing in Java. It should be,
public static void main(String[] args)
To know the meanings of public, static, String[] args read this: Explanation of 'String args[]' and static in 'public static void main(String[] args)'
Secondly,
int client = n.nextInt();
The value inside client depends on your input. If you input 2 or 3 instead of 1, your code'll definitely go to the else part. So make sure your input is 1.
Thirdly,
Get rid of the extra scanner. You need only one.
The rest of your code is ok.

Use of Scanner class in recursive functions

I am trying to use a recursive method/function, which uses the Scanner class. Closing the scanner, causes an exception to be thrown the next time the same method is called within the recursion. A workaround to this is not to close the scanner at all, but this is not a right approach. I suspect the same scanner object is used between recursive calls, so that's why closing it creates havoc. If my assumption is correct then closing the scanner in the last method call would be a valid workaround (i.e. no actual resource leak). Is there anything I may be missing before jumping into Scanner and related implementation code?
EDIT
The answers provided were really useful and enlightening. In summary, the problem is the constant re-opening and closing of the scanner, and not recursion per se. The reason I would avoid passing the scanner object as parameter is that this example simulates a larger project, calling multiple recursive functions and I would have to pass the scanner object in all of them.
On the practical side, and from the answers provided, I think just closing the scanner in the last recursive call would work without having any resource leaks. Any related opinions would be welcome, esp. if you see something wrong with my approach.
Here is an example of my initial experiment:
package scanner;
import java.util.Scanner;
public class Main {
public static void acceptValidInput() {
System.out.print("Enter a number greater than 10: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
// Adding this will make an exception to be thrown:
sc.close();
if (i <= 10) {
acceptValidInput();
}
}
public static void main(String[] args) {
acceptValidInput();
System.out.println("Your input is valid");
}
}
Once you start to consume an input stream using a Scanner, you should not try to read from it in any other way anymore. In other words, after you have constructed a Scanner to read from System.in, you need to use it for all further reading from System.in. This is because Scanner buffers input, so you have no idea how much input it has already consumed but not emitted yet.
Therefore, I recommend that you construct one Scanner, then use it for all the reading:
public class Main {
public static void acceptValidInput(Scanner sc) {
System.out.print("Enter a number greater than 10: ");
int i = sc.nextInt();
if (i <= 10) {
acceptValidInput(sc);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
acceptValidInput(sc);
System.out.println("Your input is valid");
sc.close();
}
}
It works:
package scanner;
import java.util.Scanner;
public class Main {
public static void acceptValidInput(Scanner sc) {
int i = sc.nextInt();
if (i <= 10) {
System.out.print("Enter a number greater than 10: ");
acceptValidInput(sc);
}
}
public static void main(String[] args) {
System.out.print("Enter a number greater than 10: ");
Scanner sc = new Scanner(System.in);
acceptValidInput(sc);
sc.close();
System.out.println("Your input is valid");
}
}
The result is:
Enter a number greater than 10: 4
Enter a number greater than 10: 5
Enter a number greater than 10: 11
Your input is valid
Process finished with exit code 0
Closing the scanner closes also the underlying input stream. In this case it is the System.in stream - you shouldn't do this. Either do not close it or create a single scanner for all method calls.
public class abc{
public void acceptValidInput() {
System.out.print("Enter a number greater than 10: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
// Adding this will make an exception to be thrown:
if (i <= 10) {
acceptValidInput();
}
}
public static void main(String[] args) {
while(true){
abc a=new abc();
a.acceptValidInput();
System.out.println("Your input is valid");
}
}}
try this.

How do I set the statement if to read letters instead of numbers?

"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...

Categories

Resources