Question

I am trying to take a string of numbers seperated by a single space and covert...

I am trying to take a string of numbers seperated by a single space and covert them into a string array. I have created the following code but it only works if the numbers are seperated a a comma or something similar to that.

Example of what I am trying to achieve:

string input = "1 1 1 1 1" turn it into.... int[] x = {1,1,1,1} so that it is printed as... [1, 1, 1, 1]   

This is the code I have so far....

public static void main(String[] args) {

       Scanner input = new Scanner(System.in);

       System.out.println("Welcome to the Guess The CodeGame!");

       System.out.println("Please enter the code you want to use wiht a ' ' in between each number");

       String x = input.next();

       String[] strArray = x.split(","); // this only works with a comma, doesnt work with a x.split(" ");

       int[] intArray = new int[strArray.length];

       for (int i = 0; i < strArray.length; i++) {

           intArray[i] = Integer.parseInt(strArray[i]);

           System.out.println(Arrays.toString(intArray));

       }

       System.out.println(Arrays.toString(intArray));

   }

Homework Answers

Answer #1

Note:

The code you wrote every thing was right.But a small change.To read the String with spaces we have to use

nextLine() method of Scanner class Object.But you used next() method.That was the only change.

next() method of Scanner class is used to read the word.

nextLine() method of Scanner class is used to read the sentence with spaces.

____________________

StringToIntArray.java

import java.util.Arrays;
import java.util.Scanner;

public class StringToIntArray {

   public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Guess The CodeGame!");
System.out.println("Please enter the code you want to use with a ' ' in between each number");
String x = input.nextLine();
String[] strArray = x.split(" "); // this only works with a comma, doesnt work with a x.split(" ");
int[] intArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);

}
System.out.println(Arrays.toString(intArray));

   }

}

_______________________

Output:

Welcome to the Guess The CodeGame!
Please enter the code you want to use with a ' ' in between each number
1 1 1 1 1 1 1
[1, 1, 1, 1, 1, 1, 1]

_____________Thank You

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Covert the following Java program to a Python program: import java.util.Scanner; /** * Displays the average...
Covert the following Java program to a Python program: import java.util.Scanner; /** * Displays the average of a set of numbers */ public class AverageValue { public static void main(String[] args) { final int SENTINEL = 0; int newValue; int numValues = 0;                         int sumOfValues = 0; double avg; Scanner input = new Scanner(System.in); /* Get a set of numbers from user */ System.out.println("Calculate Average Program"); System.out.print("Enter a value (" + SENTINEL + " to quit): "); newValue =...
Hello, I am trying to create a Java program that reads a .txt file and outputs...
Hello, I am trying to create a Java program that reads a .txt file and outputs how many times the word "and" is used. I attempted modifying a code I had previously used for counting the total number of tokens, but now it is saying there is an input mismatch. Please help! My code is below: import java.util.*; import java.io.*; public class Hamlet2 { public static void main(String[] args) throws FileNotFoundException { File file = new File("hamlet.txt"); Scanner fileRead =...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public void addStudent(String student) {         if (numberOfStudents == students.length) {             String[] a = new String[students.length + 1];            ...
4.9.1: Nested loops: Indent text. JAVA Print numbers 0, 1, 2, ..., userNum as shown, with...
4.9.1: Nested loops: Indent text. JAVA Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Hint: Use i and j as loop variables (initialize i and j explicitly). Note: Avoid any other spaces like spaces after the printed number. Ex: userNum = 3 prints: 0 1 2 3 Please use my template import java.util.Scanner; public class...
I am writing code in java to make the design below. :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) I already have...
I am writing code in java to make the design below. :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) I already have this much public class Main { int WIDTH = 0; double HEIGHT = 0; public static void drawSmileyFaces() { System.out.println(" :-):-):-):-):-):-)"); } public static void main (String[] args) { for (int WIDTH = 0; WIDTH < 3; WIDTH++ ) { for(double HEIGHT = 0; HEIGHT < 2; HEIGHT++) { drawSmileyFaces(); } } } } I am pretty sure that alot of this is wrong...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
7.6 LAB: Exception handling to detect input String vs. Integer The given program reads a list...
7.6 LAB: Exception handling to detect input String vs. Integer The given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. The program fails and throws an exception if the second input on a line is a String rather than an Integer. At FIXME in the code, add a try/catch statement to catch java.util.InputMismatchException, and output 0 for the age. Ex: If the input is: Lee 18 Lua...
I am trying to figure out how to find the most common word length in the...
I am trying to figure out how to find the most common word length in the british dictionary. I have inputted the text file for the british dictionary into my program. I tried a tedious way, but it doesn't seem effective. Can someone help me? String longestWord = "";        int maxLength =0;        int count1 =0, count2 =0, count3=0, count4=0, count5=0, count6=0, count7=0, count8=0, count9=0, count10=0;        Scanner scanFile = new Scanner (new File("BritishDictionary.txt"));       ...
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
Provide A UML for the Following CODE public class Employee{ public String strName, strSalary; public Employee(){...
Provide A UML for the Following CODE public class Employee{ public String strName, strSalary; public Employee(){    strName = " ";    strSalary = "$0";    } public Employee(String Name, String Salary){    strName = Name;    strSalary = Salary;    } public void setName(String Name){    strName = Name;    } public void setSalary(String Salary){    strSalary = Salary;    } public String getName(){    return strName;    } public String getSalary(){    return strSalary;    } public String...