我正在尝试制作某门学科缺席的学生的成绩单 例如,如果学生缺席两个科目,则输出应为:
subject marks
sub1 78
sub2 84
sub3 Absent
sub4 Absent
sub5 34
-------------------
Total:xx Average:xx
import java.util.*;
public class ReportCard {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Student name: ");
String name=sc.nextLine();
System.out.print("Enter number of Subject: ");
int no=sc.nextInt();
String[] marks =new String[no];
for(int i=0;i<marks.length;i++)
{
System.out.print("Enter marks of subject"+(i+1)+":");
marks[i]=sc.nextLine();
}
reportCard(marks, name);
sc.close();
}
static void reportCard(String[] marks,String name)
{
System.out.print("---------------------------------------\n");
System.out.print("\t REPORT CARD\n");
System.out.println("NAME:"+name);
System.out.println("---------------------------------------\n");
System.out.println("SUBJECT\t\t MARKS");
int total=0;
for(int i=0;i<marks.length;i++)
{
if(marks[i]=="Absent")
{
break;
}
else
{
total=total+marks[i]
}
System.out.println("Subject "+(i+1)+"\t\t"+marks[i]);
}
System.out.print("---------------------------------------\n");
float avg;
avg=((float)total/marks.length);
System.out.print("Total: "+total+"\t Average:"+avg);
}
}
字符串不能转换为int
答案 0 :(得分:0)
Integer.parseInt([STRING GOES HERE])将返回一个整数。
答案 1 :(得分:0)
total=total+marks[i]
-此行取一个int(总计)并将其设置为等于自身加marks[i]
。 marks[i]
是一个字符串,因为它来自字符串数组。
看来marks
唯一不能转换为int的值是“不存在”,因此在检查以确保不存在该值之后,可以将此值转换为一个int,以便可以将其添加到您的int总数中。
尝试在parseInt()
周围添加marks[i]
,使行total=total+parseInt(marks[i])
。请务必确保您强制转换的值只是整数的String版本,否则会遇到问题。
答案 2 :(得分:0)
使用java包装器类可以很容易地将字符串转换为有效的整数。您可以进一步了解他们here!
例如:
String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);
这里Integer是包装器类。请注意int和Integer之间的区别
<-进行投票,如果有帮助的话-> :)
答案 3 :(得分:0)
您需要将等级转换为数值。但是,您还需要注意确保该值实际上是数字。
root@08c7a05c8129:/usr/lib/Wt/examples/hello# ls /usr/include/Wt
Auth WBatchEditProxyModel WDateValidator WHTML5Audio WLocalizedStrings WPopupWidget WSslInfo WTimePicker
Chart WBoostAny WDefaultLayout WHTML5Video WLogger WProgressBar WStackedWidget WTimeValidator
Dbo WBootstrapTheme WDefaultLoadingIndicator WIOService WMatrix4x4 WPushButton WStandardItem WTimer
Ext WBorder WDialog WIcon WMeasurePaintDevice WRadioButton WStandardItemModel WTimerWidget
Http WBorderLayout WDllDefs.h WIconPair WMediaPlayer WRandom WStatelessSlot WToolBar
Json WBoxLayout WDoubleSpinBox WIdentityProxyModel WMemoryResource WRasterImage WStreamResource WTransform
Mail WBreak WDoubleValidator WImage WMenu WReadOnlyProxyModel WString WTree
Payment WBrush WEnvironment WInPlaceEdit WMenuItem WRectArea WStringListModel WTreeNode
Render WButtonGroup WEvent WIntValidator WMessageBox WRectF WStringStream WTreeTable
Utils WCalendar WException WInteractWidget WMessageResourceBundle WRegExp WStringUtil WTreeTableNode
WAbstractArea WCanvasPaintDevice WFileResource WItemDelegate WMessageResources WRegExpValidator WSubMenuItem WTreeView
WAbstractGLImplementation WCheckBox WFileUpload WItemSelectionModel WModelIndex WResource WSuggestionPopup WVBoxLayout
WAbstractItemDelegate WCircleArea WFitLayout WJavaScript WNavigationBar WScrollArea WSvgImage WValidationStatus
WAbstractItemModel WClientGLWidget WFlags WJavaScriptPreamble WObject WScrollBar WTabWidget WValidator
WAbstractItemView WColor WFlashObject WJavaScriptSlot WOverlayLoadingIndicator WSelectionBox WTable WVector3
WAbstractListModel WCombinedLocalizedStrings WFont WLabel WPaintDevice WServer WTableCell WVector4
WAbstractMedia WComboBox WFontMetrics WLayout WPaintedWidget WServerGLWidget WTableColumn WVectorImage
WAbstractProxyModel WCompositeWidget WFormModel WLayoutItem WPainter WShadow WTableRow WVideo
WAbstractSpinBox WConfig.h WFormWidget WLayoutItemImpl WPainterPath WSignal WTableView WViewWidget
WAbstractTableModel WContainerWidget WGLWidget WLength WPanel WSignalMapper WTemplate WVirtualImage
WAbstractToggleButton WCssDecorationStyle WGenericMatrix WLengthValidator WPdfImage WSlider WTemplateFormView WVmlImage
WAccordionLayout WCssStyleSheet WGlobal WLineEdit WPen WSocketNotifier WText WWebWidget
WAggregateProxyModel WCssTheme WGoogleMap WLineF WPoint WSortFilterProxyModel WTextArea WWidget
WAnchor WDate WGradient WLink WPointF WSound WTextEdit WWidgetItem
WAnimation WDateEdit WGridLayout WLoadingIndicator WPolygonArea WSpinBox WTheme
WApplication WDatePicker WGroupBox WLocalDateTime WPopupMenu WSplitButton WTime
WAudio WDateTime WHBoxLayout WLocale WPopupMenuItem WSslCertificate WTimeEdit
运行上述命令时,可以输入整数或字符串。它将相应地处理它们。如果 Scanner scan = new Scanner(System.in);
String str;
while (!(str = scan.nextLine()).equalsIgnoreCase("end")) {
int grade;
try {
grade = Integer.parseInt(str);
System.out.println("numeric grade = " + grade);
}
catch (IllegalArgumentException ie) {
System.out.println("No grade - " + str);
}
}
方法尝试将单词转换为parseInt
,则会抛出int
,并对其进行适当的捕获和处理。
答案 4 :(得分:0)
尝试与此一起工作:
import java.util.*;
import com.sun.jndi.url.iiop.iiopURLContext;
import sun.audio.ContinuousAudioDataStream;
public class Main {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Student Name: ");
String name=sc.nextLine();
System.out.print("Enter Number of Subjects: ");
int no=sc.nextInt();
sc.nextLine();
String[] marks =new String[no];
for(int i=0;i<marks.length;i++)
{
System.out.print("Enter marks for subject "+(i+1)+": ");
marks[i]=sc.nextLine();
}
reportCard(marks, name);
sc.close();
}
static void reportCard(String[] marks,String name)
{
System.out.print("---------------------------------------\n");
System.out.print("\t REPORT CARD\n");
System.out.println("NAME:"+name);
System.out.println("---------------------------------------\n");
System.out.println("SUBJECT\t\t MARKS");
int total=0;
for(int i=0;i<marks.length;i++)
{
if(i=="Absent")
{
break;
}
else
{
total = total + Integer.parseInt(marks[i]);
}
System.out.println("Subject "+(i+1)+"\t\t"+marks[i]);
}
System.out.print("---------------------------------------\n");
float avg;
avg=((float)total/marks.length);
System.out.print("Total: "+total+"\t Average:"+avg);
}
}
答案 5 :(得分:0)
1-创建一个类型为string
的数组StringArray
string[] StringArray = new string[] {"1","2","3"};
2-1-创建一个类型为int
的数组IntArray
int[] IntArray = new int[StringArray.Length];
3编写此代码以转换
for (int i = 0; i < IntArray.Length; i++)
{
IntArray[i] = int.Parse(StringArray[i]);
}
答案 6 :(得分:0)
lambda表达式将 total
的计算与表格打印分开:
…
System.out.println( "SUBJECT\t\t MARKS" );
for( int i = 0; i < marks.length; i++ ) {
System.out.println( "Subject " + (i + 1) + "\t\t" + marks[i] );
}
System.out.print( "---------------------------------------\n" );
int total = Stream.of( marks ).filter( m -> ! "Absent".equals( m ) ).collect(
Collectors.summingInt( Integer::parseInt ) );
float avg = ((float)total / marks.length);
System.out.print( "Total: " + total + "\t Average:" + avg ); // Total: 196 Average:39.2
如果marks[]
包含空字符串,则lambda表达式将失败,并故意NumberFormatException