I'm trying to store input in the array indoor_games and output it to the screen, but when I'm executing the code, it abruptly ends the execution after accepting 1 value.
package games;
import java.util.*;
import java.lang.*;
class Indoor{
String name;
Indoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Outdoor{
String name;
Outdoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
for(int i=0;i<size;i++){
name = sc.next();
indoor_games[i] = new Indoor(name);
}
for(int i=0;i<size;i++)
indoor_games[i].display();
}
}
Updated code with nextLine added but still the same problem:
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
sc.nextLine(); //To consume the newline character
Indoor[] indoor_games = new Indoor[size];
for(int i = 0 ; i < size ; i++){
name = sc.nextLine();
indoor_games[i] = new Indoor(name);
}
for(int i = 0 ; i < size; i++)
indoor_games[i].display();
}
}
Output(Command Line)
D:\Docs Dump\School stuff\JAVA\Java slips>java games.Slip20
Enter number of Players in Indoor Games:
3
Neeraj
D:\Docs Dump\School stuff\JAVA\Java slips>
As you can see, the scanner only accepts "Neeraj" and the program ends
execution.
just replace sc.next() by sc.nextLine()
This is because nextLine() required. But be aware use it, documentation say that:
Advances this scanner past the current line and returns the input
* that was skipped.
This method returns the rest of the current line, excluding any line
* separator at the end. The position is set to the beginning of the next
* line.
Known that you should use before loop and problem will be solved.
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
sc.nextLine();
for (int i = 0; i < size; i++) {
System.out.println("Please write a name:");
indoor_games[i] = new Indoor(sc.nextLine());
}
Hey thanks for the answers and help. It was actually a compilation problem, I was compiling the package in a wrong way. It's working now.
Related
// Problem Statement: WAP to create a class Library and use methods addBook and showAvailableBooks to store and show books in the library.
// I am new to java and I am getting an issue after running the below program. I am not able to fill the first index place of the array addBook.
package com.company;
import java.util.Scanner;
class Library{
Scanner sc = new Scanner(System.in);
int numOfBooks;
String[] addBook;
Library(){
System.out.print("Enter the number of books you want to add to the library: ");
numOfBooks = sc.nextInt();
this.addBook = new String[numOfBooks]; //New String called "addBook" is being created.
}
public String[]addBook(){
for(int i=0; i<numOfBooks; i++){
int j = i+1;
System.out.print("Add Book "+j+" Name: ");
this.addBook[i] = sc.nextLine();
}
return addBook;
}
public void showAvailableBooks(){
for(int i=0; i<numOfBooks; i++){
System.out.println(addBook[i]);
}
}
}
public class CWH_51_Exercise_4 {
public static void main(String[] args) {
Library l = new Library();
l.addBook();
l.showAvailableBooks();
}
}
That it's probably caused by sc.nextInt() in your Library contructor. It reads the int given, but it does not read the '\n' character (origined when you press enter).
When nextLine() is called for first time, it reads that missing '\n'.
Try calling nextLine() after every nextInt().
System.out.print("Enter the number of books you want to add to the library: ");
numOfBooks = sc.nextInt();
sc.nextLine(); // Consume '\n'
this.addBook = new String[numOfBooks];
i suggest you avoid using sc.nextInt() and use this instead:
numOfBooks = Integer.parseInt(sc.nextLine());
See this question for the explanation
I am very new to java and this community. I am looking for someone to possibly be able to explain why my code is going into an infinite loop. I believe it has something to do with my while loop. The program compiles but when I enter a phrase i want for my acronym builder to create the program dosent do anything, it just blinks at the next line. When i press ctrl c to exit, it then shows the acronym.
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym{
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
while (input.hasNext() )
{
phraseToChange = input.next();
acroynmArray[wordCounter] = phraseToChange.charAt(0);
wordCounter++;
}
for (int i = 0;i < wordCounter ; i++ )
{
System.out.print(acroynmArray[i]);
}
}
}
The problem is not truly caused by your while loop but because the fact that scanner will keep asking user new input (system.in stream will always open) until EOF. Therefore, the problem can be solve using StringTokenizer if it's allowed by your professor. Down here is the code example
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym{
public static void main(String[] args) {
String phraseToChange = "";
boolean phraseToChange2 = true;
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String nextLine = input.nextLine();
StringTokenizer st = new StringTokenizer(nextLine, " ");
while (st.hasMoreTokens())
{
phraseToChange = st.nextToken();
acroynmArray[wordCounter] = phraseToChange.charAt(0);
wordCounter++;
}
System.out.println("reach here");
for (int i = 0;i < wordCounter ; i++ )
{
System.out.print(acroynmArray[i]);
}
}
}
The reason of why your loop never ends it the fact that System.in stream is always open. You should change the condition to while (!phraseToChange.equals("exit")) or something. Then the user will be able to finish the input by sending "exit" string to your program.
If you don't have to use a while loop with input.hasNext() you can use this. May want to clean up where necessary, but I believe this does what you want.
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym {
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char[100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String[] line = input.nextLine().split(" ");
for (int i = 0; i < line.length; i++) {
phraseToChange = line[i];
acroynmArray[i] = phraseToChange.charAt(0);
wordCounter++;
}
for (int i = 0; i < wordCounter; i++) {
System.out.print(acroynmArray[i]);
}
}
}
Sample build output:
run:
This program builds acronyms
Enter a phrase:
Google Rocks Socks
GRSBUILD SUCCESSFUL (total time: 4 seconds)
Code snippet that causes the change:
String[] line = input.nextLine().split(" ");
for (int i = 0; i < line.length; i++) {
phraseToChange = line[i];
acroynmArray[i] = phraseToChange.charAt(0);
wordCounter++;
}
Alternatively you could use this:
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String line = input.nextLine(); // Obtain user entered line
acroynmArray[0] = line.charAt(0); // First letter is known; set it
wordCounter++; // increment wordCounter
//Loop the characters in the retrieved line
for(int i = 0; i < line.length(); i++){
// If it's whitespace then we know the next character must be the letter we want
if(Character.isWhitespace(line.charAt(i))){
acroynmArray[wordCounter] = line.charAt(i+1); // Set it
wordCounter++;
}
}
But as Tom said in my deleted post, this is quite fragile code. It works, until it doesn't, as in it wouldn't take much to break it as it doesn't handle trailing and starting whitespaces
I have to design a program that gets 3 user-inputs in the form:
Name1 (any number of spaces) age1
Name2 (any number of spaces) age3
Name3 (any number of spaces) age3
Then print line which has the highest age (suppose Name3 age3 had the highest age I'd print his line).
My Code:
import java.util.*;
public class RankAge{
public static void main(String[] args){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n1 = sc.nextLine();
String n2 = sc.nextLine();
String n3 = sc.nextLine();
}
}
I know how to scan the user-inputs, but i don't know how to do a comparison of the number within the acquired string to print a specific one (also since there can be any number of spaces it seems even more complicated to me).
You can use split to get the person's age:
String age = "Jon 57".split("\\s+")[1]; // contains "57"
You can then use Integer.parseInt(age) to get the person's age, as a number.
If you need to allow the user to input a name with spaces, you can adjust the number in square brackets ([]). For example, [2] would require the user to input a first name and last name.
Managed to do it with frenchDolphin's suggestion. This is the code i used (it's quite beginner friendly):
import java.util.*;
public class RankAge{
public static void main(String[] args){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n1 = sc.nextLine();
String a1 = n1.split("\\s+")[1];
String n2 = sc.nextLine();
String a2 = n2.split("\\s+")[1];
String n3 = sc.nextLine();
String a3 = n3.split("\\s+")[1];
if(Integer.parseInt(a1) > Integer.parseInt(a2)){
} if(Integer.parseInt(a1) > Integer.parseInt(a3)){
System.out.println(n1);
}else if(Integer.parseInt(a2) > Integer.parseInt(a3)){
System.out.println(n2);
}else{
System.out.println(n3);
}
}
}
+1 because at first look it seemed very simple but when I started implementing the complexities started showing up. Here is the complete solution for your problem,
import java.util.*;
public class RankAge {
public static void main(String s[]){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n[] = new String[3];
for(int i=0;i<3;i++){
n[i] = sc.nextLine();
}
int age[] = new int[3];
age[0] = Integer.parseInt(n[0].split("\\s+")[1]);
age[1] = Integer.parseInt(n[1].split("\\s+")[1]);
age[2] = Integer.parseInt(n[2].split("\\s+")[1]);
int ageTemp[] = age;
for(int i=0;i<age.length;i++){
for(int j=i+1;j<age.length;j++){
int tempAge = 0;
String tempN = "";
if(age[i]<ageTemp[j]){
tempAge = age[i];
tempN = n[i];
age[i] = age[j];
n[i] = n[j];
age[j] = tempAge;
n[j] = tempN;
}
}
}
for(int i=0;i<3;i++){
System.out.println(n[i]);
}
}
}
i write one program that get input from user as "Enter number of students:" then add the student names into it and print it in console. I write one code that run fine but problem is the loop is already ramble one time the code is not properly working i also want to know that how to get inputs using command line argument without Scanner and store it in String Array
Current Output is like that
Here is my code please help and i am in learning phrase of Java
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns
the input that was skipped.
Try placing a scanner.nextLine(); after each nextInt() if you intend
to ignore the rest of the line.
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
You can use array args[]
Need not pass number of students there.
So what ever name you pass on command prompt after java <className> shall be stored in this array and you can iterate over it.
Add in.nextLine(); after you assign this int totalstudents = in.nextInt();
use ArrayList instead of String Array
declare header file
import java.util.ArrayList;
change your code
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
Try this code:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}
I am writing a random chance game to pick a random winner. I am using a for loop to input the players into an array, but it doesn't let me input anything for the first player. Here is the code:
import java.util.Scanner;
import java.util.Random;
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.println("How many people will play???");
int playernum = input.nextInt();
String players[] = new String[playernum];
for(int i = 0; i < playernum; i++){
System.out.println("Who is player #" + (i+1)+"?");
players[i] = input.nextLine();
}
System.out.println("The winner is: " + players[rand.nextInt(playernum)]);
}
}
The input.nextInt() call reads the integer but leaves the new line character unread in the input stream, so the input.nextLine() call in the loop just reads that character in the first iteration.
So, you need the following -
int playernum = input.nextInt();
input.nextLine(); //read the unread new line character from the input stream
Use the following code. Comments in the code explain changes.
import java.util.Scanner;
import java.util.Random;
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.println("How many people will play???");
int playernum = input.nextInt();
input.nextLine(); //ADDED LINE
String players[] = new String[playernum];
for(int i = 0; i < playernum; i++){
System.out.println("Who is player #" + (i+1)+"?");
players[i] = input.nextLine();
}
System.out.println("The winner is: " + players[rand.nextInt(playernum)]);
}
}
We added input.nextLine(); because input.nextInt(); leaves a leftover new line character that we need to clear out. It was putting this new line character as player 1
-Henry
Use input.next() instead of input.nextLine() in the for loop. That way, the unused new line character won't be a problem, like #BheshGurung explains in his answer.
I think your issue is on this line players[i] = input.nextLine();.
I think what you're looking for is, players[i] = input.next();
"Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end."
See the API description here.