开发者

Why is the variable read from the Scanner method next() or nextDouble() equal to a String or double respectively [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

For example,

If I declare a String variable and a double variable

String d = "dragon";
double = 1.45;

And then I have a text file and on the first line of the file it is...

A dragon is 1.45

So I open the file

 {
         try {
             x = new Scanner(new File("Dragon.txt"));

         }
         catch(Exception e)
         {
             System.out.println("Could not find file");
         }
     }
// And then read in the data, in this case I use hasNext which returns a String.
     public void readFileData()
     {
         while(x.hasNext())
         {

  // Remember, this is the first line of the text file: A dragon is 1.45
         String a1 = x.next();  // al = "A";
         String a2 = x.next();  // a2 = "dragon;

// And I test a2 to see it is equal to dragon, however it is not.

         if(d == a2)
         {
             System.out.println("Wow");
         }
         else
             System.out.println("Naw man");
         String a3 = x.next();
         String a4 = x.next(); 

// Of course I do the same thing for the a4 variable and of course the String variables are repl开发者_开发知识库aced with double and nextdouble() method is used.

Thank you very much in advance to anyone who can help!


Use String.equals when comparing strings. == checks if the reference is the same. String.equals tests if the objects are the same.

So instead of if(d==a2) use if(d.equals(a2))


Try if (d.equals(a2)), use equals for String comparison.


First you're trying to compare reference values, not the contents of the String objects.

As others have noted, you need to use the String.equals(String otherString) method.

Next, you're reading 1.45 in as a String, not a double. These two things are not comparable. You need to read in 1.45 as a double;

String a1 = x.next();
String a2 = x.next();
String a3 = x.next();
double d1 = x.nextDouble();

This would convert your line A dragon is 1.45 to three Strings ('A', 'dragon', 'is') and a double (1.45)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜