-1

我收到此错误消息:The value of the local variable chaine2 is not used

编码:

package com.example.Projet_java;

public class MyFirstClass 
                         {
  public static void main(String[] args) {
     { String chaine = new String("HELLO"),
      chaine2 = new String();
      chaine2 = chaine.toLowerCase();
     }
                                         }
                          }

我尝试遵循以下线程 Java 错误“未使用局部变量的值” 但没有成功。

有人知道我该如何解决吗?

4

6 回答 6

0
  1. chaine2 = new String() is redundant. Delete that.
  2. You should use the value of chaine2, which currently you don't. For example, print it out.
于 2013-04-14T21:06:04.960 回答
0

It's the chaine2 = new String(); You're assigning a new String() to chaine2, and then immediately discarding it when you reassign it in the next line with chaine2 = chaine.toLowerCase();.

于 2013-04-14T21:06:28.163 回答
0

The value of the local variable chaine2 is not used is a warning and not an error.

Your IDE is saying that you never use the variable chaine2, that is, you neither use it in other operations, nor store it anywhere, nor print it on screen nor anything... Anyway your code will run!

Despite of what is being said in other answers, warnings are very useful notifications about things that may lead to errors, so they're very useful while programming, because your IDE will notice issues that you may not notice. So you shouldn't discard them while learning Java!


EDIT: If what you want to do is to get the String "HELLO" in lowercase, don't seek anymore... you got it! The only point is that you have it stored in a avariable chaine2 but you don't do anything with it... Just do:

System.out.println("Printing chaine2: " + chaine2);

And you will see the result printed on the console.

于 2013-04-14T21:07:24.093 回答
0

学习一门特定的语言,即使是一开始也不应该让程序员忘记仔细设计它的算法。您的算法应始终尽可能是最佳的。

Moderns IDE 有助于不要忘记 ;) => 一个无用的变量?(因为在您的情况下,chaine2初始化后根本不使用)=> 把它扔掉!

因此,您应该真正注意您最喜欢的 IDE(或其他来源)抛出的任何警告,即使对于简单的“Hello World”算法也是如此。

于 2013-04-14T21:21:12.140 回答
-1

You are setting an object to chaine2,

chaine2 = new String();

but you overwrite it at the next line, so the previously created empty String is not used for anything.

chaine2 = chaine.toLowerCase();

The compiler finds it odd, since the first line is useless, and warns you in case it is a logic error (although it is a correct program and will compile and run correctly).

于 2013-04-14T21:05:55.067 回答
-2

It's a warning, not an error. This is the way compiler informs you thay you create variable which you never use. This variable is useless, so there is no point in creating it. You can just ignore this warning if you're learning Java, because it doesn't prevent your code to being compiled and execute. It's just a tip for you: "Hey, you have a variable you don'tuse! Maybe you've missed something?"

于 2013-04-14T21:06:49.823 回答