I'm trying to make a program that asks the user to type in 3 cities and the program
is supposed to take the 3 cities , and put them in a String Array , the first city in
[0],second in [1] and third in [2] , I got it to ask for them , collect the answers
but it's only Printing out the first answer, not all 3. Any ideas how I can fix that?
My code looks like this atm
public static void main(String[] args) {
String ans;
String[] favoritStad = new String [3];
Scanner scanner1 = new Scanner (System.in);
System.out.println("skriv in 3 favoritstäder");
String Användarinlägg1 = scanner1.nextLine();
String Användarinlägg2 = scanner1.nextLine();
String Användarinlägg3 = scanner1.nextLine();
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg1;
favoritStad[2] = Användarinlägg1;
System.out.print(Användarinlägg1);
}
Användarinlägg is userinputt , favorit stad is favcity
the string "ans" was just an idea I tried to make to collect all 3 answers and print it out
but never figured it out
Solved it ! Just needed to add
System.out.print(Användarinlägg2);
System.out.print(Användarinlägg3);
As I suggested in my comment below your question - use a for loop. Also always check twice if you are not using the same variable (for example Användarinlägg1) over and over.
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
for(int i=0; i<favoritStad.length; i++) {
System.out.println(favoritStad[i]);
}
In your code you've added the same element 3 times.
You need to use:
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
And in order to print you can use for loop or just:
System.out.print(favoritStad[0]);
System.out.print(favoritStad[1]);
System.out.print(favoritStad[2]);
You can use for loop to print all the values of an array. You can use something like below:
for (int i=0; i<favoritStad.length();i++){
System.out.println(favoritStad[i])
}
Try this way
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
Now Print Array:
1st way :
for(int i=0; i<favoritStad.length; i++) {
System.out.println(favoritStad[i]);
}
2nd way:
for(String s :favoritStad) {
System.out.println(s);
}
Also you need to print...
System.out.print(favoritStad);
instead of
System.out.print(Användarinlägg1);
Related
I am facing a problem taking all the lines from standard input and write them to standard output in reverse order.
That is output each line in the reverse order of input.
Below is my code:
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
//get input
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by
\"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
append += input + " ";
}
sc.close();
System.out.println("The current append: " + append);
String stringArray[] = append.split(" strings" + "");
System.out.println("\n\nThe reverse order is:\n");
for (int i = 0; i < stringArray.length; i++) {
System.out.println(stringArray[i]);
}
}
}
When I run my code with sample inputs like below:
Type some text with line breaks, end by "-1":
My name is John.
David is my best friend.
James also is my best friend.
-1
I get the following output:
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
My name is John. David is my best friend. James also is my best friend.
Whereas, the required output is something like below:
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
James also is my best friend.
David is my best friend.
My name is John.
Can anyone help me to check what is wrong with my code and fix it?
Try the below Code.
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by\"-1\":");
List<String> list= new LinkedList<String>();
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
list.add(input);
}
sc.close();
System.out.println("The current append: " + append);
Collections.reverse(list);
for (String string : list) {
System.out.println(string);
}
}
}
Hope This will help you
Instead of appending the input to the append string you should add the input string to a List and then print it from the bottom or use the Collections.reverse() method and then print it straight
Edit - basically same implementation as previous answers, though uses a for loop:
import java.util.ArrayList;
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
//create arraylist for lines
ArrayList<String> lines = new ArrayList<String>();
//get input
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by \"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
lines.add(input);
}
sc.close();
System.out.println("The current append: ");
for(String line : lines){
System.out.print(line + ". ");
}
System.out.println("\n\nThe reverse order is:\n");
for (int i = lines.size()-1; i >=0 ; i--) {
System.out.println(lines.get(i));
}
}
}
1 - 1 way to do it is run loop from backword.
for (int i = stringArray.length; i >=0 ; i++) {
System.out.println(stringArray[i]);
}
2 - Use Collections.reverse() method on list and print it. like
List<String> list = Arrays.asList(stringArray);
Collections.reverse(list );
System.out.println("Modified List: " + list );
You can use a Stack data structure that has LIFO behavior for insert and read of elements. Tha more complete Java Stack implementation is Deque that has the method "descendingOrder" that returns an iterator of elements in reverse order.
Deque deque = new LinkedList();
// We can add elements to the queue in various ways
deque.add("Element 1 (Tail)"); // add to tail
deque.addFirst("Element 2 (Head)");
deque.addLast("Element 3 (Tail)");
deque.push("Element 4 (Head)"); //add to head
deque.offer("Element 5 (Tail)");
deque.offerFirst("Element 6 (Head)");
deque.offerLast("Element 7 (Tail)");
Iterator reverse = deque.descendingIterator();
System.out.println("Iterating over Deque with Reverse Iterator");
while (reverse.hasNext()) {
System.out.println("\t" + reverse.next());
}
You can either use Collections.reverse() as suggested by other answers. But the standard way of reversing is done using Stack. Stack is a LIFO data structure which exactly exhibits your required behaviour. You'll need to push all your results to a Stack and pop it until Stack becomes empty. Something like below snippet will give you an outline.
String input = " Hello \n World \n Here you go";
List<String> inputList = Arrays.asList(input.split("\n"));
Stack<String> myStringStack = new Stack<>();
myStringStack.addAll(inputList); // This is to exhibit your input scenario from user.
while (!myStringStack.isEmpty()) { // While your stack is not empty, keep popping!
System.out.println(myStringStack.pop());
}
I need to create an array of strings from user input and print the first letter of each element. I'm aware that I need to convert the array to a string somehow, but unsure how to accomplish this. I was unsuccessful with Arrays.toString
Following is my code:
import java.util.Scanner;
import java.util.Arrays;
class Main{
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
System.out.println("How many names would you like to enter in this array?: ");
int numName = inp.nextInt();
String nameArray[] = new String[numName];
System.out.println("Enter the names: ");
for(int i = 0; i <= nameArray.length; i++){
nameArray[i] = inp.nextLine();
}
System.out.println(nameArray.charAt(0));
}
}
You need to iterate over every String in the Array and then print the first char. You can do this using charAt() and a loop.
for(String str : nameArray) {
System.out.println(str.charAt(0));
}
Or you can use Arrays.stream():
Arrays.stream(nameArray).forEach(e -> System.out.println(e.charAt(0)));
Also just a few problems with your code:
You are going to enter into this problem, because nextInt() does not consume the newline. Add a blank nextLine() call after nextInt()
You are looping until <= array.length which will cause an indexOutOfBounds error. You need to only loop until less than array.length
Just do another iteration over the "nameArray", and get the first character of each array element, and print it.
For example, you can use for-each:
for(String name : nameArray) {
System.out.println(name.charAt(0));
}
Arrays.stream(nameArray).map(s -> s.charAt(0)).forEach(System.out::println);
I am tryting to split string by "," using StringTokenizer but not able to get whole values , token count shows 3 but printing only two elements, i have added my code below
if i have tried with two other inputs
"Ravi,Tuti,786" - same output
"Ravi,Tuti,786,pincode" getting three tokens not last one
public class Tokenizer{
public static void main(String[] args){
String str = "Ravi,Tuti,786";//survival of fittest,journey to get job,update skill,try,get job";
StringTokenizer stk = new StringTokenizer(str,",");
System.out.println(stk.countTokens());
for(int i=0;i<=stk.countTokens();i++){
System.out.println(stk.nextToken());}
}
}
output is
3
Ravi
Tuti
Use hasMoreTokens() with nextToken:
public class Tokenizer{
public static void main(String[] args){
String str = "Ravi,Tuti,786";//survival of fittest,journey to get job,update skill,try,get job";
StringTokenizer stk = new StringTokenizer(str,",");
System.out.println(stk.countTokens());
while (stk.hasMoreTokens()) {
System.out.println(stk.nextToken());
}
}
}
The problem with your approach is that you are running countTokens in the for loop, which changes after nextToken is called.
If you want to use a for loop, you need to save the token count to a variable:
int numTokens = stk.countTokens();
for (int i = 0; i < numTokens; i++) {
System.out.println(stk.nextToken());
}
You should use hasTokens() method.
for( ; stk.hasMoreTokens() ; ) {
System.out.println(stk.nextToken());
}
The countTokens() method returns:
the number of tokens remaining in the string using the current delimiter set.
So in your if loop it keeps getting evaluating and returning smaller numbers. To prevent this you can resolve it to a variable
int length = stk.countTokens();
for(int i=0;i<length;i++){
System.out.println(stk.nextToken());
}
If you do not wish to introduce another variable you can start i at what countTokens() returns and then loop until i is more that zero (While subtracting from i instead of adding)
for(int i=stk.countTokens();i>0;i--){
System.out.println(stk.nextToken());
}
Output:
3
Ravi
Tuti
786
Good day, guys,
I'm working on a program which requires me to input a name (E.g Patrick-Connor-O'Neill). The name can be composed of as many names as possible, so not necessarily restricted to solely 3 as seen in the example above.But the point of the program is to return the initials back so in this case PCO. I'm writing to ask for a little clarification. I need to separate the names out from the hyphens first, right? Then I need to take the first character of the names and print that out?
Anyway, my question is basically how do I separate the string if I don't know how much is inputted? I get that if it's only like two terms I would do:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
I did attempt to do the code, and all I have so far is:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
}
}
}
I'm taking a crash course in programming, so easy concepts are hard for me.Thanks for reading!
You don't need to split it a second time. By doing String[] x = input.split("-"); you have an Array of Strings. Now you can iterate over them which you already do with the enhanced for loop. It should look like this
String[] x = input.split("-");
String initials = "";
for (String name : x) {
initials += name.charAt(0);
}
System.out.println(initials);
Here are some Java Docs for the used methods
String#split
String#charAt
Assignment operator +=
You can do it without splitting the string by using String.indexOf to find the next -; then just append the subsequent character to the initials:
String initials = "" + input.charAt(0);
int next = -1;
while (true) {
next = input.indexOf('-', next + 1);
if (next < 0) break;
initials += input.charAt(next + 1);
}
(There are lots of edge cases not handled here; omitted to get across the main point of the approach).
In your for-each loop append first character of all the elements of String array into an output String to get the initials:
String output = "";
for(String i : x) {
output = output + y.charAt(0);
}
This will help.
public static void main(String[] args) {
String output = "";
String input = "Patrick-Connor-O'Neil-Saint-Patricks-Day";
String[] brokenInput = input.split("-");
for (String temp : brokenInput) {
if (!temp.equals(""))
output = output + temp.charAt(0);
}
System.out.println(output);
}
You could totally try something like this (a little refactor of your code):
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.println("What's your name?");
input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
System.out.println(y);
}
}
}
I think it's pretty easy and straightforward from here if you want to simply isolate the initials. If you are new to Java make sure you use a lot of System.out since it helps you a lot with debugging.
Good coding.
EDIT: You can use #Mohit Tyagi 's answer with mine to achieve the full thing if you are cheating :P
This might help
String test = "abs-bcd-cde-fgh-lik";
String[] splitArray = test.split("-");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < splitArray.length; i++) {
stringBuffer.append(splitArray[i].charAt(0));
}
System.out.println(stringBuffer);
}
Using StringBuffer will save your memory as, if you use String a new object will get created every time you modify it.
package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.