I apologize for how I asked my previous question but hope that I can make this question clearer. I am trying to write a code where a user can place information under the columns of firstname, lastname and marks but I have failed.
With this code I have written the values under num are supposed to be automatic.
Please help me out and thank you.
package school;
import java.util.Scanner;
class Assign1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("NUM\t FIRSTNAME \t LASTNAME \t MARKS \t GRADE");
int i=1;
String f = sc.nextLine();
while(i<=2) {
System.out.print(i+ "\t");
System.out.print("\t" + f);
i++;
}
}
}
I think I understood your question. Correct me if I'm wrong.
You want the mentioned columns to be printed and the user to input data under each column. You also want the number column to print numbers automatically. Here is the code for that program:
import java.util.Scanner;
class Assign1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("NUM\t FIRSTNAME\t LASTNAME\t MARKS\t GRADE");
int i=1;
String firstName = "";
String lastName = "";
int marks = 0;
String grade = "";
while(i<=2) {
System.out.print(i+ "\t ");
firstName = sc.next();
lastName = sc.next();
marks = sc.nextInt();
grade = sc.next();
i++;
}
}
}
To store each kind of column data, we need different variables of the proper type. Next, we are inputting data from the user while staying inside the loop. Since i=1, the while condition is true 2 times and the user is able to enter 2 different records.
The output will be like this:
Related
I have a For Loop and it's asking the user how many times the loop should be looped inside the loop. How do I loop it the number of times given without repeating the question "how many names would you like to input"?
The issue is that I don't want to repeat the question after the user answered it. When the user answers the question, I want it to ask for the names x amount of times and then move on.
The main problem is that I need to ask how many times to loop it after the name is asked. It's says it the assignment sheet.
Thanks so much!
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
System.out.println("How many names would you like to input?");
num = input.nextInt;
}
You must move your num getter code outside of loop like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many names would you like to input?");
int num = input.nextInt();
String names[] = new String[num];
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
}
}
Always move these kinds of questions out of the loop rather than inside.
System.out.println("How many names would you like to input?");
num = input.next();
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
}
num = input.next();
You are asking a numbers not a string should change the .next() to either nextInt or nextShort.
#DevilsHnd the first code won't work indeed, I never saw that String [] = new String [] use array before plus this will explain better why.
#J.A.P link with code may work
import java.util.Scanner;
public class Newpro{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("how many times you want to loop?")
int num = sc.nextInt();//input the no of times you want to loop
String names[i] = new String[num];//initialize a string array for reading names
for(i=0;i<num;i++){
System.out.println("enter name#"+(i+1));
names[i]=sc.next();
}
for(j=0;j<num;j++){
//printing the names entered by you
System.out.println("the entered names by you are"+" "+names[j]);
}
as others suggested, you have to move your 'num' getter part out of the loop and after that initialize a string array for reading your names by specifying how many names you want to enter(index of string array = number of names you want to enter and no of times you want to loop as well==>'num') and based on that number the looping will be done with above code.
finally iterate through the array and print the names entered by you.
Edit:1
check with the below code if you need to ask "how many names user wants to input AFTER it asks for a first name.
import java.util.Scanner;
public class Newpro2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//make sure you create a string array with index = no of names you want to
//enter
String[] names = new String[10];
System.out.println("enter name#1");
names[0]= sc.next();
System.out.println("how many inputs you want to give?");
num=sc.nextInt();//give the no of inputs you want to give here
//read the remaining names
for(int i=1;i<num;i++){
System.out.println("enter name#"+(i+1));
names[i] = sc.next();
}
//print all the names entered by you
for(int j=0;j<num;j++){
System.out.println("entered name#"+(j+1)+"by you is"+" "+names[j]);
}
Create a String variable and assign your full name to the variable.
Using the String's substring method print out your first name, middle name, and last name on three separate lines.
Modify your program so that it creates a "Scanner" object to allow the user to type in any three names and store it in the String variable.
Modify your program so that it will print out the three names on separate lines no matter what three names the user enters (Hint: use the String's indexof method).
So for this problem, I am doing it in Java. Here is what I have so far. Thank you!
package stringparser;
import java.util.Scanner;
public class StringParser
{
public static void main(String[] args)
{
String Name = "Billy Bob Joe";
String first = Name.substring(0,5);
String middle = Name.substring(6,12);
String last = Name.substring(13,16);
System.out.println("First name: " + first);
System.out.println("Middle name: " + middle);
System.out.println("Last name: " + last);
Scanner in = new Scanner(System.in);
System.out.print("Type any 3 names: ");
System.out.print("First name: ");
String a = in.nextLine();
System.out.print("Second name: ");
String b = in.nextLine();
System.out.print("Third name: ");
String c = in.next();
}
}
2 ways I interpret this question.
Use Scanner 3 times
Use indexOf to find the nearest space character of the one console input.
In all, I find it painfully inefficient to use String.indexOf
Quickest way, but not necessarily the best way.
public StringParser () {
Scanner in = new Scanner(System.in);
String name = in.nextLine();
System.out.println(name.replace(" ", "\n")); // replacing all spaces with new line characters
}
This program will split the string with space and print all of them as result. You can edit the for loop condition as per your need. Hope it helps :)
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str = in.nextLine();
String[] names = str.split(" ");
for(int i = 0; i < names.length; i++)
{
System.out.println(names[i]);
}
}
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]);
}
}
}
import java.io.*;
import java.util.*;
public class AP_ExamArray
{
//User Input AP Exam Scores Using For Loops
public static void main(String args[])
{
int [] scores = new int[5];
int j;
int sum_exam=0;
for (j=0; j<scores.length; j++)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("Please enter AP Exam Score (1-5): ");
scores[j]=kbReader.nextInt();
sum_exam+=scores[j];
}
//Initializer List Final Percentage
double [] final_percent = {97.3, 89.8, 96.2, 70.1, 93.0};
double sum_percent=0;
int k;
for(k=0; k<final_percent.length;k++)
{
sum_percent+=final_percent[k];
}
// String array containing last name (while loop)
String [] last_name = new String[5];
int i=0;
while (i<last_name.length)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("Please enter last name: ");
last_name[i]=kbReader.next();
i++;
}
//Average Exam Scores
double avg_exam = (double) sum_exam/scores.length;
//Average Final Percentage
double avg_percent = (double) sum_percent/final_percent.length;
}
}
The directions are:
"For your output use a loop to print the student names, percentages, and test score, and be sure to include appropriate data below each column heading:
Student Name Student Percentage Student Test Score."
I'm not sure how to do this!
How about:
for(i=0; i<scores.length; i++)
System.out.println(last_names[i] +"\t"+ final_percent[i] +"\t"+ scores[i]);
A for loop is used because you want to loop through the entire
array of a known size.
If, instead, you wanted to loop only while a certain condition holds
you would use a while loop: (e.g. while(condition) loop;).
System.out.println() will print a new line after each call, and \t will add a tab.
For better formatting check out this Oracle doc on using printf and format
I have recently learned about Setters and Getters. I can use them but the problem is that I have to use them in a loop. Some of the code that I am using is mentioned below.
I am entering Student information in a loop, and then editing it in another loop using Set Get methods. I can use the setter and getter methods without the loop but I am not sure how to use them inside the loop. So please guide me to add students in a stu array.
public static void Addstudents()
{
for(int i=0; i<stu.length; i++)
{
stu[i]=new Stuinfo();
System.out.println("Enter name ");
name= sc.next();
System.out.println("Enter id ");
id= sc.next();
}
}
And to edit the data, I want to run a loop and use the setter method to set the values. Something like this:
public void Modify()
{
String Cid;
System.out.println("You r modifying account");
for (int i=0; i<stu.length;i++)
{
stu[i].setId(id)...// dont know what to do in loop hree
}
}
The question is not clear, I think that to modify a specific account of a single student, you need something like this :
public void Modify() {
String Cid;
System.out.println("Enter your ID :");
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
for (int i=0; i<stu.length;i++)
{
if(id == stu[i].getId()) {
//Change your account details
System.out.println("Enter name ");
name= sc.next();
stu[i].setName(name);
}
}
}
In the example above, you are getting an id as input, and then you are looking up in the array for the input id, and if you find one, you are giving the opportunity to the user to change the account details of that specific user ...
While in the first example you have to set your students instance properties using setters :
public static void Addstudents()
{
for(int i=0; i<stu.length; i++)
{
stu[i]=new Stuinfo();
System.out.println("Enter name ");
stu[i].setName( sc.next() );
System.out.println("Enter id ");
stu[i].setId( sc.next() );
}
}
public void Modify() {
System.out.println("You r modifying account");
Scanner sc = new Scanner(System.in);
for (int i=0; i<stu.length;i++)
{
System.out.println("Enter id");
stu[i].setId(sc.nextInt());
System.out.println("Enter name ");
stu[i].setName(sc.nextLine());
}
}