简体   繁体   中英

Char array inputted from user to string conversion

Ask user for char inputs then when user is done inputting enough char then the char array will be converted to string and returned as a string. Not sure where i went wrong but i think maybe at the looping part.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class App {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<Character> charIn = new ArrayList<Character>();
        String word;
        boolean cond = false; 

        while (!cond) {
            System.out.print("Please enter a Character: ");
            charIn.add(sc.next().charAt(0));
            if (sc.next() == "0") {
                cond = true;
            }

        }
        word = charIn.toString();
        System.out.println(word);

    }

Every time you call sc.next() , sistem will request form user input. call next once and put result to variable. The problem is also in checking equality of string next == "0" . The truly equality of string objects in java is done across equals method.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class App {

    public static void main(String[] args) {
            List<Character> charIn = new ArrayList<Character>();
            String word = "";
            boolean cond = false;
            Scanner sc = new Scanner(System.in);

            while (cond == false) {
                System.out.print("Please enter a Character: ");
                String next = sc.next();
                charIn.add(next.charAt(0));
                if ("0".equals(next)) {
                    cond = true;
                }else{
                    cond = false;
                }

            }
            word = charIn.toString();
            System.out.println(word);

        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM