So far, my code looks like this:
package kittensworld;
import java.util.Scanner;
public class KittensWorld {
public static void main(String[] args){
System.out.println("What is the first kitten's name?");
Scanner scan = new Scanner(System.in);
String kitten1 = scan.nextLine();
System.out.println("What is the second kitten's name?");
String kitten2 = scan.nextLine();
System.out.println("And the third kiten's name?");
String kitten3 = scan.nextLine();
System.out.println("The first kitten's name is " + kitten1);
System.out.println("The second kitten is " + kitten2);
System.out.println("And last but not least, " + kitten3);
}
}
How would I go about looping it so that I can ask for the names of 20 kittens, without copying and pasting it 20 times?
Use for loop and array that'll contain the data:
String[] inputs = new String[NUMBER_OF_INPUTS];
Scanner scanner = new Scanner();
for(i=0; i<NUMBER_OF_INPUTS; i++) {
inputs[i] = scanner.nextLine();
}
If you don't know the number of inputs (but you know what symbol will represent the end of the input), you can use a while loop and an ArrayList.
I think you need to look up this tutorial about this proper loop called for-loop:
String[] kitten = new String [size];
for(int i = 0 ; i < kitten.length; i++){
System.out.println("kitten number "+i+" : ");
kitten [i] = scan.nextLine();
}
package kittensworld;
import java.util.Scanner;
public class KittensWorld {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 20; i++){
System.out.println("What is the kitten's name?");
String kitten = scan.nextLine();
System.out.println("That kitten's name was " + kitten);
}
}
}
package kittensworld;
import java.util.Scanner;
public class KittensWorld {
private static final int NUMBER_OF_KITTENS = 20;
public static void main(String[] args){
String[] kittenNames = new int[NUMBER_OF_KITTENS];
Scanner scan = new Scanner(System.in);
for(int i = 0; i < NUMBER_OF_KITTENS; ++i)
{
System.out.println("What is the name of kitten number " + (i+1) + "?");
kittenNames[i] = scan.nextLine();
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> kittenNames = new ArrayList<>();
int number = 3 ; // number of kitten names ( +1 )
for (int i = 1; i < number; i++) {
System.out.printf("What is the %s kitten's name?\n", ordinal(i));
kittenNames.add(scan.nextLine());
}
System.out.println("===============================================");
for (String name : kittenNames) {
System.out.println(name);
}
}
public static String ordinal(int i) {
String[] sufixes = new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
switch (i % 100) {
case 11:
case 12:
case 13:
return i + "th";
default:
return i + sufixes[i % 10];
}
}
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
import java.util.Scanner;
public class stringclass {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = input.nextInt();
String [] friends = new String[a];
int count=1;
for(int i=0;i<a;i++){
System.out.println("Enter the name of your friend "+count +":");
friends[i] = input.nextLine();
count++;
}
int count1=1;
for (int j=0;j<a;j++){
System.out.println("Name of your friend "+count1+ "is "+friends[j].toUpperCase());
count1++;
}
}
}
I was writing code to display name of friends using string in java by getting input. But index 0 is not getting a entry
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = Integer.parseInt(input.nextLine());
String[] friends = new String[a];
for (int i = 0; i < a; i++) {
System.out.print("Enter the name of your friend " + (i + 1) + ":");
friends[i] = input.nextLine();
}
for (int j = 0; j < a; j++) {
System.out.println("Name of your friend " + (j + 1) + "is " + friends[j].toUpperCase());
}
}
You need to consume the end of the line that contains the input integer, as explained in comments.
import java.util.Scanner;
public class stringclass {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = input.nextInt();
// This is what you want
input.nextLine();
String [] friends = new String[a];
int count=1;
for(int i=0;i<a;i++){
System.out.println("Enter the name of your friend "+count +":");
friends[i] = input.nextLine();
count++;
}
int count1=1;
for (int j=0;j<a;j++){
System.out.println("Name of your friend "+count1+ "is "+friends[j].toUpperCase());
count1++;
}
}
}
I want get first name when input the name with array and looping
Example :
Enter the name :
1. Alvin Indra
2. Sada Rika
Output :
1. Alvin
2. Sada
Code:
public static void main(String[] args) {
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
System.out.println("First Name : ");
for(int i=0;i<n;i++){
if(teman[i] == ' '){ // this is where I need help
System.out.println((i+1)+". "+teman[i].substring(0,i));
}
}
}
Here you go
String name = "John Smith";
System.out.println(name.split(" ")[0]);
Using this will replace that second for loop, you don't need to cycle through each letter to look for a space you can just use the split method on the string and specifiy the character in which to split the string up and then call the first element.
Updated complete implementation
import java.util.Scanner;
public class testest {
public static void main(String[] args){
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
for(int i=0;i<n;i++){
System.out.println("First Name : ");
System.out.println(teman[i].split(" ")[0]);
System.out.print("\n");
}
}
}
You are probably looking for using contains and indexOf methods of String class in java, to use them as :
if (teman[i].contains(" ")) {
System.out.println((i + 1) + ". " + teman[i].substring(0, teman[i].indexOf(" ")));
}
My goal is to ask the user to enter a bunch of strings in a loop, and when they enter "stop", the loop breaks and prints all those strings with a comma at the end of each word. For example, if the user enters "first", "second", "third", and "fourth", then the program would print the following:
first, second, third, fourth
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int i;
String s;
String[] listOfStrings = new String[1000];
String last = "";
System.out.println("Please enter some Strings: ");
for (i = 1; i>0; i++) {
listOfStrings[i] = kb.next();
last = listOfStrings[i] + ",";
if (listOfStrings[i].equalsIgnoreCase("stop")) {
break;
}
}
System.out.print(last);
There is a problem because it always just winds up printing the last word and nothing else. Any help would be greatly appreciated.
I would use an ArrayList:
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<String>();
while (sc.hasNext()) {
String s = sc.next();
if (s.equalsIgnoreCase("stop")) {
break;
} else {
list.add(s);
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + ",");
}
If you want everything in one line, you can do this:
Scanner sc = new Scanner(System.in);
String line = "";
while (sc.hasNext()) {
String s = sc.next();
if (s.equalsIgnoreCase("stop")) {
break;
} else {
line += s + ", ";
}
}
System.out.println(line.substring(0, line.length()-2));
I want to enter a string of numbers, delimited by ",". I don't know how long it will be. The input will be passed to the program and will end with the letter "x".
JAVA!
import java.util.Scanner;
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
int sumTotal=0;
while(scan.nextByte() != 'x') {
num = scan.nextInt();
sumTotal += num;
}
System.out.println(sumTotal);
scan.close();
}
}
PLEASE help! :)
//////////////
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x");
userInput = scan.next();
} while (!userInput.matches("(?:\\d+(?:,\\d+)*)x") || !userInput.matches("\\d+( \\d+)*x"));
scan.close();
String[] numberStrings;
if (userInput.contains(",")) {
numberStrings = userInput.replace("x", "").split(","); // 4x is now 4 and split by ','
} else {
numberStrings = userInput.replace("x", "").split(" ");
}
int sum = 0;
for (String i : numberStrings) {
sum += Integer.valueOf(i);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}
}
Try this
public static void main(String[] args) {
int result = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value");
String string = sc.nextLine();
string = string.replace("x", "");
String[] strArray = string.split(",");
for (String str : strArray) {
result += Integer.valueOf(str);
}
System.out.println("Result is " + result);
}
Input is 1,2,3,4x
Output is Result is 10
import java.io.Console;
import java.util.Scanner;
class MainClass{
public static void main(String args[]) {
int sum=0;
Console c=System.console();
Scanner scan = new Scanner(c.readLine());
scan.useDelimiter("[,x]");
while(scan.hasNextInt())
sum+=scan.nextInt();
scan.close();
System.out.print(sum);
}
}
This does the job as well. Additionally it tells the user what input is expected and if the entered list does not match the format.
public static void main(final String[] args) {
final Scanner userInputScanner = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x or 1 2 3 4x");
userInput = userInputScanner.nextLine();
} while (!(userInput.matches("\\d+(,\\d+)*x") || userInput.matches("\\d+( \\d+)*x")));
userInputScanner.close();
final String[] numberStrings = userInput.replace("x", "").split("[, ]");
int sum = 0;
for (final String numberString : numberStrings) {
sum += Integer.valueOf(numberString);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}
My code works fine. However the output seems incorrect when I enter -1 from name or age input. How do I remove null values and "-1" and display the existed array?
import java.util.Scanner;
public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);
public final static int arrayLoop = 5;
public static String[] nameList = new String[arrayLoop];
public static int[] age = new int[arrayLoop];
public static void main(String[] args) {
System.out.println("NAME & AGE SYSTEM\n-----------------\n");
for(int i=0; i<arrayLoop; i++) {
System.out.print("Name: ");
nameList[i] = key.nextLine();
if(nameList[i].equals("-1"))
break;
System.out.print("Age: ");
age[i] = keyNum.nextInt();
if(age[i] < 0)
break;
}
System.out.println("----------");
for(int i=0; i<nameList.length; i++) {
System.out.println(nameList[i] + " " + age[i]);
}
}
}
Currently, when you input -1, the loop exits. That is, as soon as you input -1, the loop is not run again. This is because you use the break statement.
If you'd like to let -1 allow the user to start the current entry again, you'll need to do two things:
if (nameList[i].equals("-1")) {
// Take the loop variable down one.
i--;
// Instead of break, continue to the next iteration.
continue;
}
If you want to keep the loop how it is, but only print non-null values, modify your printing code:
for(int i=0; i<nameList.length; i++) {
if (nameList[i] == null || nameList[i].equals("-1") || age[i] < 0) {
// Invalid; go to the next one.
continue;
} else { // (not strictly necessary)
System.out.println(nameList[i] + " " + age[i]);
}
}
Try to use a List instead a Array, something like this:
import java.util.Scanner;
public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);
public final static int arrayLoop = 5;
public static List<String> nameList = new ArrayList<String>();
public static List<Integer> ages = new ArrayList<Integer>();
public static void main(String[] args) {
System.out.println("NAME & AGE SYSTEM\n-----------------\n");
while (true){
System.out.print("Name: ");
String name = key.nextLine();
if(name.equals("-1"))
break;
System.out.print("Age: ");
Integer age = keyNum.nextInt();
if(age < 0)
break;
nameList.add(name);
ages.add(age);
}
System.out.println("----------");
for(int i=0; i<nameList.length; i++) {
System.out.println(nameList[i] + " " + age[i]);
}
}
}