Java:你可以在每次循环时改变同一个字符串的值吗? [英] Java: can you change the value of the same string every time it loops?

查看:443
本文介绍了Java:你可以在每次循环时改变同一个字符串的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个非常基本的Java计算器程序,要求用户输入,并根据他输入的内容(如果add或else)将两个值相加或相减。 b
$ b

问题是,我想让它循环,所以在每个方程式完成并显示结果后,再次询问用户是否要加或减。有没有什么办法,而不使用数组,每次程序循环时更改字符串的值?

  import java.util 。扫描器; 

public class BasicCalculator {
public static void main(String [] args){

Scanner input = new Scanner(System.in);

(int i = 0; i <999; i ++){
System.out.println(你想添加还是减去?
String answer1 = input.nextLine();
if(answer1.equalsIgnoreCase(add)){
System.out.println(Enter first value);
int addv1 = input.nextInt();
System.out.println(输入第二个值);
int addv2 = input.nextInt();
int ans = addv1 + addv2;
System.out.println(答案是:+ ans);
} else {
System.out.println(Enter first value);
int subv1 = input.nextInt();
System.out.println(输入第二个值);
int subv2 = input.nextInt();
int ans2 = subv1 - subv2;
System.out.println(答案是:+ ans2);



$ b $ / code $ / pre

解决方案每次给String变量赋值时,它都会引用一个新的String对象,并引用旧的String对象,对象丢失。所以,不,你不改变相同的字符串的值(你不能,因为字符串是不可变的),你正在改变变量所指的字符串。


I'm doing a very basic calculator program in java that asks for the users input, and based on what he inputs(if "add" or else) either adds up the two values or subtracts them.

The problem is, i want it to loop, so after every equation is finished and the result is displayed, it asks the user again if he wants to add or subtract. Is there any way, without using arrays, to change the value of the String each time the program loops?

import java.util.Scanner;

public class BasicCalculator {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        for(int i = 0; i<999; i++) {
            System.out.println("Do you want to add or subtract?");
            String answer1 = input.nextLine();
            if (answer1.equalsIgnoreCase("add")) {
                System.out.println("Enter first value");
                int addv1 = input.nextInt();
                System.out.println("Enter second value");
                int addv2 = input.nextInt();
                int ans = addv1 + addv2;
                System.out.println("The answer is: " + ans);
            } else {
                System.out.println("Enter first value");
                int subv1 = input.nextInt();
                System.out.println("Enter second value");
                int subv2 = input.nextInt();
                int ans2 = subv1 - subv2;
                System.out.println("The answer is: " +ans2);
            }
        }
    }
}

解决方案

Each time you assign a value to the String variable, answer1, it refers to a new String object, and the reference to the old String object is lost. So, no, you are not changing the value of the same String (and you can't, since String is immutable), you are changing the String that the variable is referring to.

这篇关于Java:你可以在每次循环时改变同一个字符串的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆