I have a tutorial work based on vectors in java se. The task is to prompt the user to input ten words in a string and then we are supposed to split the words into single words and add each of them into a vector element. However, right at the beginning, I'm already facing problems with my codes. Right now, I even have problem finding out the size of the vectors so could you guys help me out here? Thanks!
import java.util.*;
class TenWords
{
public static void main (String [] args)
{
Vector <String> words = new Vector <String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter ten words");
String a;
while(userInput.hasNext())
{
a = userInput.next();
words.add(a);
System.out.println(a);
}
int s = words.size();
System.out.println(s);
}
}
In this case userInput.hasNext() always returns true. So you need a finite loop. Use for loop
import java.util.Scanner;
import java.util.Vector;
public class TenWords {
public static void main(String[] args) {
Vector<String> words = new Vector<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter ten words");
String a;
for (int i = 0; i < 10; i++) {
a = userInput.next();
words.add(a);
System.out.println(a);
}
int s = words.size();
System.out.println(s);
}
}
Related
This is the problem I'm trying to solve:
My code is the following:
import java.util.Scanner;
public class LineByLine {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
}
}
My code is showing as wrong and I'm unsure why. Any explanations?
You should arrange your code like:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
scanner.close();
}
Also you could use hasNext method instead of while(true) part:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String sentence = scanner.nextLine();
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
}
scanner.close();
}
You'll need to place:
Scanner scanner = new Scanner(System.in);
outside of the while loop.
The reason:
You only need to create a single Scanner object. This has to be done before you enter the loop since the instantiation will consume the standard input - this means that after the first iteration of the loop, there will be no standard input left to instantiate the object once again.
You can also think about it more mechanically than that:
If you had a loop that was meant to iterate through numbers, you wouldn't want to be resetting your loop counter each time, right? Its quite a similar thing in this case.
I need to write a loop that takes in two values from the user-given list and then work with those values in the loop. My issue is that I can not seem to get the loop to take in the 2 values from the String.
Here is my code:
import java.util.Scanner;
public class practice2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter numbers seperated by commas");
String numbers = input.nextLine();
Scanner s = new Scanner(numbers);
s.useDelimiter(",");
for(int i =0; i<numbers.length(); i+=2 ) {
int newnum = i/25;
System.out.println(newnum);
}
}
}
Here, to get the values - do as below
public static void main(String[] args) {
System.out.println("enter numbers seperated by commas");
Scanner input = new Scanner (System.in);
String[] numbers = input.nextLine().split(",\\s*");
//to read number
System.out.println(numbers[0] + " - " + numbers[1]);
//to use them as int
int i = Integer.parseInt(numbers[0]);
System.out.println(++i);
}
I want to have a user input a random string of letters, put those in an array, then sort them alphabetically. Problem I have is putting the input into an array. What I have is:
import java.util.Scanner;
public class ArraySort {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
int stringLength = input.length();
String[] stringArray = new String[stringLength];
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = input;
}
System.out.println(stringArray);
}
}
This gives me [Ljava.lang.String;#55f96302 when I print.
You have two problems, you're not printing the Array correctly, and you're storing the entire input in each cell of the array. Try:
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = input.charAt(i)+"";
System.out.println(stringArray[i]);
}
You are making 2 major mistakes:
1) You are assigning each string the whole input stringArray[i] = input;
2) You have to iterate over each element of your string array.
In Java8 this could be done easily with Arrays.stream().
A corrected Version of your code is:
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
int stringLength = input.length();
String[] stringArray = new String[stringLength];
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = Character.toString(input.charAt(i));
}
Arrays.stream(stringArray).forEach(System.out::print);
}
}
Btw. String[] stringArray=input.split(""); would be much shorter.
Additional:
If you want sorted output:
stringArray=Arrays.stream(stringArray).sorted().toArray(String[]::new);
Arrays.stream(stringArray).forEach(System.out::print);
And you are done.
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
String[] stringArray=input.split("");
stringArray=Arrays.stream(stringArray).sorted().toArray(String[]::new);
Arrays.stream(stringArray).forEach(System.out::print);
}
}
To get the String form of an array, use the Arrays class toString method.
System.out.println(Arrays.toString(stringArray));
Also note the sort method of this class, although in the code's current state each item of your array will be equal to the input line.
So I'm new to Java and I figured I'd do something simple like a for loop to print out an array of strings or something,
My code ended up like this:
package package.four;
import java.util.Scanner;
public class arrayrecurse {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Please enter 5 words");
String a = in.next();
String b = in.next();
String c = in.next();
String d = in.next();
String e = in.next();
String[] s = {a, b, c, d, e};
for(int i = 0; i< s.length;){
System.out.println(s[i]);
i++;
}
in.close();
}
}
It works fine but my question is if it's possible to make a for loop cycle through variables.
For examples if I wanted something like:
for(words = 5; words > 0;){
String a = in.next();
a++}
Where would it change the variables each time I enter a new word.
Would it be possible to do something like that or do I need to type out the String variable = in.next(); every time I want to enter a new word input from the console?
You can call next() inside the loop, but you need to declare the variable outside the loop if you want to use it afterwards, also, there is no ++ operator for String or array in Java:
String[] inputs = new String[5];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
Use an ArrayList to store the input variables.
That is:
import java.util.*;
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (String s: inputVars)
{
System.out.println(s);
}
}
Or alternatively, if you want to change the contents of the ArrayList:
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (int i = 0; i < inputVars.size(); i++)
{
System.out.println(inputVars.get(i));
//Change the variable
inputVars.set(i, "Hello, " + inputVars.get(i));
}
}
I've been trying to add elements to a TreeSet using a loop that accepts user input. The problem I'm running into is that the loop I created is only filling the TreeSet with the first element that the user inputs. I was using all string variables in this example and I was also attempting to use the word 'end' as a sentinel value to terminate the loop and then print out the elements that had been added to the TreeSet. My only problem is not being able to fill the TreeSet with more than the first user input element. This is the code I used:
import java.util.*;
import java.util.Scanner;
public class TestRun {
public static void main(String[] args) {
java.util.TreeSet wordList = new java.util.TreeSet();
Scanner input = new Scanner(System.in);
String word;
System.out.print("Enter a word: ");
wordList.add(input.next());
while(!(word = input.nextLine()).equals("end")){
System.out.print("Enter a word: ");
}
java.util.Iterator iterator = wordList.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
}
}
You're missing a call to wordList.add in your loop:
while(!(word = input.nextLine()).equals("end")){
wordList.add(word); // The call you were missing
System.out.print("Enter a word: ");
}
import java.util.Scanner;
import java.util.TreeSet;
public class largestandSmallestelementinanArray {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int size=0;
System.out.println("enter the size of an array");
size = sc.nextInt();
TreeSet tr = new TreeSet();
while(size>0)
{
tr.add(sc.nextInt());
size--;
}
System.out.println(tr);
}
}