Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}
Related
public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}
I'm trying to convert the user input from the question of students name and score into a array.
I also need help to printout the array.
The while loop is using boolean loopNaming as its condition, and i is updated everytime the loop occurs.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
String[] name = new String[i];
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1;
}
System.out.println(name[i]);
}
}
You can simplify the logic of your program and write something like this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> nameList = new ArrayList<String>();
List<Double> scoreList = new ArrayList<Double>();
while (true) {
System.out.printf("Enter first name of student or done to finish: ");
String fname = keyboard.next();
if (fname.equals("done")) {
break;
}
System.out.printf("Enter last name of student: ");
String lname = keyboard.next();
nameList.add(fname + " " + lname);
System.out.println("Enter score: ");
scoreList.add(keyboard.nextDouble());
}
keyboard.close();
System.out.println("Names: " + nameList);
System.out.println("scores: " + scoreList);
}
I have changed the array to an arraylist and moved i=i+1; to inside else segment. Also changed the final print statement to print the list.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<String>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name.add(keyboard.next());
if(name.get(i).equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i=i+1;
}
}
System.out.println(name);
}
I would firstly recommend using a List data structure:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming = true;
List<String> name = new ArrayList<>();
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
}
System.out.println(name.toString());
}
However, if you very much would like to use an array, you could make your own method to increase the size of your array each time a new name is added:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
int i = 0;
boolean loopNaming = true;
String[] name = {};
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name = increaseArray(name);
name[i] = input;
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i++;
}
}
System.out.println(Arrays.toString(name));
}
public static String[] increaseArray(String[] arr) {
String[] temp = new String[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
return temp;
}
I was unsure what your plan was with your score variable, but this would be two ways to achieve your desired result.
I hope this helps.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if(input.equals("done"))
{
loopNaming = false;
}
else
{ name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1; //no need to use
}
System.out.println(name);
}
You should use a dynamic list because You can't resize an array in Java. The second point when the user gives "done", you should not put it in the list so check it before the insertion.
You declared your String array with size 0. that's why you cant add elements in to it.
import java.util.Scanner;
public class NameArray {
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
double score[] = new double[10];
boolean loopNaming=true;
int i=0;
String namae;
String[] name = new String[10];
int count = 0;
while(loopNaming==true){
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done")){
loopNaming = false;
}
else{
System.out.println("Enter score: ");
score[i] = keyboard.nextDouble();
count++;
}
i=i+1;
}
for(int j = 0; j < count; j++) {
System.out.println(name[j]+" "+score[j]);
}
}
}
Try this code or you can go for any other data structures.
When I tried to run this code noOfSub() methods executed properly;
but GC() method faces the following problem:
Enter the number of subjects:
2
Enter Your Subject 1 Grade:
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35)
Java Result: 1
Here is my code:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i=1;
Scanner gradeInput = new Scanner(System.in);
String[] grade = new String[noOfSubjects];
int[] credit = new int[noOfSubjects];
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC() {
while(i<=noOfSubjects)
{
System.out.println("Enter Your Subject "+i+" Grade:" );
grade[i] = gradeInput.nextLine();
System.out.println("Enter the Subject "+i+" Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
When you do:
public int noOfSubjects;
noOfSubjects is set to 0 which is its default value
So when you have the following code:
String[] grade = new String[noOfSubjects];
it essentially means,
String[] grade = new String[0]; //create a new String array with size 0
which creates an empty array for you.
So when you do,
grade[i] = gradeInput.nextLine(); //where i is 1
you get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35
because there is no index 1 in String[] grade.
Problem in your array initialization. You can initialize your array after take the input from user.
For example :
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
And change your while condition. Instead of this you use
while(i < noOfSubjects)
and set i = 0
If you want to get the size for the array from the user, create the array after getting it from stdin. Otherwise it will create a array with the size of 0 which is the default value for int in java.
Separate your declaration and initalization
String[] grade = null;
int[] credit = null;
...
noOfSubjects = scan.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
Why don't you use ArrayList because the size of array isn't know for you
public class GPA {
public int noOfSubjects;
public int i=0;
Scanner gradeInput = new Scanner(System.in);
List<String> grade = new ArrayList<>();
List<Integer> credit = new ArrayList<>();
public void noOfSub(){
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC(){
while(i<noOfSubjects)
{
System.out.println("Enter Your Subject "+(i+1)+" Grade:" );
grade.add(gradeInput.nextLine());
System.out.println("Enter the Subject "+(i+1)+" Credit:");
credit.add(gradeInput.nextInt());
gradeInput.nextLine();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
Note : i added gradeInput.nextLine() after i++ because the Scanner.nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine() so i fire a blank gradeInput.nextLine() call after gradeInput.nextInt() to consume rest of that line including newline
Since the noOfSubjects has run time value so the code should be:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i = 0;
Scanner gradeInput = new Scanner(System.in);
String[] grade;
int[] credit;
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
public void GC() {
while (i < noOfSubjects) {
System.out.println("Enter Your Subject " + (i + 1) + " Grade:");
grade[i] = gradeInput.next();
System.out.println("Enter the Subject " + (i + 1) + " Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
for (int j = 0; j < grade.length; j++) {
System.out.println(grade[j] + " " + credit[j]);
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
I have to read strings from the user based on a number n and store n strings in n different variables. I'm stuck with how to put them into different strings. Please help me out.
This is my code:
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
for (int i=0; i<=b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}
So if b = 5, i have to input 5 strings from the user and store them in 5 different string variables. I'm able to take it from the user but not able to assign them into different variables. Can u please help me out?
Thanks.
If you know exactly the number of input then use an Array, if not use a ArrayList
With Arrays
String []inpupts = new String[b];
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs[i] = in.nextLine();
}
With ArrayList
List<String> inpupts = new ArrayList<String>();
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs.add(in.nextLine());
}
From your code (<= b) I am assuming you just started learning Java. Therefore, I edited your solution and am proposing the following, if this is okay?
public static void main(String[] args) {
int b;
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
//necessary to do due to Enter key pressed by user
in.nextLine();
String s[] = new String[b];
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s[i] = in.nextLine();
// You can check at the same time if this is what you entered
System.out.println("I have received this sring: "+s[i]+"\n");
}
Create an array and store it in an array like below:
String s[] = new String[b];//use b+1 if you need b+1 entries
for (int i=0; i<b; i++) {//use <=b is you need b+1 entries
System.out.println("Enter a string: ");
s[i] = in.nextLine();
}
You can then access your values as:
for (int i=0; i<b; i++) //use <=b is you need b+1 entries
System.out.println("Entered string was : " + s[i]);
}
Solution :
You can use something like this.
You can change your code as :
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
in.nextLine(); // To get a new line
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}
I am trying to do input to an array until it is full and after that print the entire array. But I cannot get the loop to run until the array is full and after that print all.
Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++){
course[i] = input.next();
grade [i] = input.nextInt();
if (i == course.length)
break;
//System.out.println("\nHow do you want to order course and grade?");
//System.out.print(" 1 - Ascending?\n"
// + " 2 - Decending?\n");
//System.out.println("Name and grade is " + course[i] + " " + grade[i]);
System.out.println(Arrays.toString(course)+(grade));
}
}
}
How can get the loop to run and then jump to the print statement?
the variable i in the loop can never be equal to course.length because the loop runs only until i < course.length. So the if block is redundant anyway.
The printing statement should be AFTER the for block, otherwise you'd be printing the array in each iteration.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade [i] = input.nextInt();
}
System.out.println(Arrays.toString(course)+(grade));
}
There should be a } after grade [i] = input.nextInt();.
And the following if is not necessary at all.
It seems the loop would do the job if it was closed after the two assignment statements. The check afterwards isn't useful and could be removed.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String[2]; // creating array
int[] grade = new int[2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade[i] = input.nextInt();
}
System.out.println(Arrays.toString(course) + (grade));
}
if (i == course.length) is unnecesery because when i == length then for loop finish working and for-loop-body doesn't call so remove this line and put instead of it close loop "}"
Next is printing your array. Change the last line to:
System.out.println(Arrays.toString(course) + Arrays.toString((grade)));